]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Make it possible to change path used by upgrade.sh on command line
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
CommitLineData
db400f44
C
1import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
2import { catchError, map, mergeMap, tap } from 'rxjs/operators'
2295ce6c 3import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
df98563e 4import { Injectable } from '@angular/core'
df98563e 5import { Router } from '@angular/router'
2295ce6c 6import { NotificationsService } from 'angular2-notifications'
c5911fd3
C
7import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
8import { User } from '../../../../../shared/models/users'
2295ce6c 9import { UserLogin } from '../../../../../shared/models/users/user-login.model'
63c4db6d 10import { environment } from '../../../environments/environment'
df98563e 11import { RestExtractor } from '../../shared/rest'
2295ce6c
C
12import { AuthStatus } from './auth-status.model'
13import { AuthUser } from './auth-user.model'
14
d592e0a9
C
15interface UserLoginWithUsername extends UserLogin {
16 access_token: string
17 refresh_token: string
18 token_type: string
19 username: string
20}
21
c5911fd3 22type UserLoginWithUserInformation = UserLoginWithUsername & User
b1794c53
C
23
24@Injectable()
25export class AuthService {
63c4db6d
C
26 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
27 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
28 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
b1794c53 29
df98563e 30 loginChangedSource: Observable<AuthStatus>
2de96f4d 31 userInformationLoaded = new ReplaySubject<boolean>(1)
b1794c53 32
df98563e
C
33 private clientId: string
34 private clientSecret: string
35 private loginChanged: Subject<AuthStatus>
36 private user: AuthUser = null
47f8de28 37 private refreshingTokenObservable: Observable<any>
ccf6ed16 38
df98563e 39 constructor (
d592e0a9 40 private http: HttpClient,
7ddd02c9 41 private notificationsService: NotificationsService,
14ad0c27
C
42 private restExtractor: RestExtractor,
43 private router: Router
db400f44 44 ) {
df98563e
C
45 this.loginChanged = new Subject<AuthStatus>()
46 this.loginChangedSource = this.loginChanged.asObservable()
23a5a916 47
bd5c83a8 48 // Return null if there is nothing to load
df98563e 49 this.user = AuthUser.load()
1553e15d 50 }
b1794c53 51
d592e0a9
C
52 loadClientCredentials () {
53 // Fetch the client_id/client_secret
54 // FIXME: save in local storage?
55 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
db400f44
C
56 .pipe(catchError(res => this.restExtractor.handleError(res)))
57 .subscribe(
58 res => {
59 this.clientId = res.client_id
60 this.clientSecret = res.client_secret
61 console.log('Client credentials loaded.')
62 },
63
64 error => {
65 let errorMessage = error.message
66
67 if (error.status === 403) {
68 errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
69 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), ' +
70 'in particular the "webserver" section.'
71 }
72
73 // We put a bigger timeout
74 // This is an important message
75 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
76 }
77 )
d592e0a9
C
78 }
79
df98563e
C
80 getRefreshToken () {
81 if (this.user === null) return null
bd5c83a8 82
df98563e 83 return this.user.getRefreshToken()
bd5c83a8
C
84 }
85
df98563e 86 getRequestHeaderValue () {
d592e0a9
C
87 const accessToken = this.getAccessToken()
88
89 if (accessToken === null) return null
90
91 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
92 }
93
df98563e
C
94 getAccessToken () {
95 if (this.user === null) return null
bd5c83a8 96
df98563e 97 return this.user.getAccessToken()
1553e15d
C
98 }
99
df98563e
C
100 getTokenType () {
101 if (this.user === null) return null
bd5c83a8 102
df98563e 103 return this.user.getTokenType()
1553e15d
C
104 }
105
df98563e
C
106 getUser () {
107 return this.user
1553e15d
C
108 }
109
df98563e 110 isLoggedIn () {
d592e0a9 111 return !!this.getAccessToken()
1553e15d
C
112 }
113
df98563e 114 login (username: string, password: string) {
d592e0a9 115 // Form url encoded
bf9ae5ce
C
116 const body = new URLSearchParams()
117 body.set('client_id', this.clientId)
118 body.set('client_secret', this.clientSecret)
119 body.set('response_type', 'code')
120 body.set('grant_type', 'password')
121 body.set('scope', 'upload')
122 body.set('username', username)
123 body.set('password', password)
d592e0a9
C
124
125 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bf9ae5ce 126 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body.toString(), { headers })
db400f44
C
127 .pipe(
128 map(res => Object.assign(res, { username })),
129 mergeMap(res => this.mergeUserInformation(res)),
130 map(res => this.handleLogin(res)),
131 catchError(res => this.restExtractor.handleError(res))
132 )
4fd8aa32
C
133 }
134
df98563e 135 logout () {
bd5c83a8 136 // TODO: make an HTTP request to revoke the tokens
df98563e 137 this.user = null
724fed29 138
df98563e 139 AuthUser.flush()
e62f6ef7 140
df98563e 141 this.setStatus(AuthStatus.LoggedOut)
bd5c83a8
C
142 }
143
df98563e 144 refreshAccessToken () {
47f8de28
C
145 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
146
df98563e 147 console.log('Refreshing token...')
bd5c83a8 148
df98563e 149 const refreshToken = this.getRefreshToken()
bd5c83a8 150
d592e0a9
C
151 // Form url encoded
152 const body = new HttpParams().set('refresh_token', refreshToken)
153 .set('client_id', this.clientId)
154 .set('client_secret', this.clientSecret)
155 .set('response_type', 'code')
156 .set('grant_type', 'refresh_token')
bd5c83a8 157
d592e0a9 158 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 159
47f8de28 160 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
db400f44
C
161 .pipe(
162 map(res => this.handleRefreshToken(res)),
163 tap(() => this.refreshingTokenObservable = null),
164 catchError(err => {
165 this.refreshingTokenObservable = null
166
167 console.error(err)
168 console.log('Cannot refresh token -> logout...')
169 this.logout()
170 this.router.navigate([ '/login' ])
171
172 return observableThrowError({
173 error: 'You need to reconnect.'
174 })
175 })
176 )
47f8de28
C
177
178 return this.refreshingTokenObservable
4fd8aa32
C
179 }
180
d592e0a9 181 refreshUserInformation () {
af5e743b 182 const obj = {
33c4972d
C
183 access_token: this.user.getAccessToken(),
184 refresh_token: null,
185 token_type: this.user.getTokenType(),
186 username: this.user.username
df98563e 187 }
af5e743b 188
d592e0a9 189 this.mergeUserInformation(obj)
db400f44
C
190 .subscribe(
191 res => {
192 this.user.patch(res)
193 this.user.save()
cadb46d8 194
db400f44
C
195 this.userInformationLoaded.next(true)
196 }
197 )
af5e743b
C
198 }
199
d592e0a9
C
200 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
201 // User is not loaded yet, set manually auth header
202 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
203
bcd9f81e 204 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
db400f44 205 .pipe(map(res => Object.assign(obj, res)))
b1794c53
C
206 }
207
d592e0a9 208 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 209 const hashTokens = {
df98563e
C
210 accessToken: obj.access_token,
211 tokenType: obj.token_type,
212 refreshToken: obj.refresh_token
213 }
bd5c83a8 214
ce5496d6 215 this.user = new AuthUser(obj, hashTokens)
df98563e 216 this.user.save()
bd5c83a8 217
df98563e 218 this.setStatus(AuthStatus.LoggedIn)
efc32059 219 this.userInformationLoaded.next(true)
bd5c83a8
C
220 }
221
d592e0a9 222 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
223 this.user.refreshTokens(obj.access_token, obj.refresh_token)
224 this.user.save()
bd5c83a8 225 }
629d8d6f 226
df98563e
C
227 private setStatus (status: AuthStatus) {
228 this.loginChanged.next(status)
629d8d6f 229 }
b1794c53 230}