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