]>
Commit | Line | Data |
---|---|---|
db400f44 | 1 | import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs' |
b1d40cff | 2 | import { catchError, map, mergeMap, share, tap } from 'rxjs/operators' |
2295ce6c | 3 | import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http' |
df98563e | 4 | import { Injectable } from '@angular/core' |
df98563e | 5 | import { Router } from '@angular/router' |
2295ce6c | 6 | import { NotificationsService } from 'angular2-notifications' |
c5911fd3 C |
7 | import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared' |
8 | import { User } from '../../../../../shared/models/users' | |
2295ce6c | 9 | import { UserLogin } from '../../../../../shared/models/users/user-login.model' |
63c4db6d | 10 | import { environment } from '../../../environments/environment' |
df98563e | 11 | import { RestExtractor } from '../../shared/rest' |
2295ce6c C |
12 | import { AuthStatus } from './auth-status.model' |
13 | import { AuthUser } from './auth-user.model' | |
cd4d7a2c | 14 | import { objectToUrlEncoded } from '@app/shared/misc/utils' |
a20776fc | 15 | import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage' |
b1d40cff | 16 | import { I18n } from '@ngx-translate/i18n-polyfill' |
c13e2bf3 | 17 | import { HotkeysService, Hotkey } from 'angular2-hotkeys' |
2295ce6c | 18 | |
d592e0a9 C |
19 | interface UserLoginWithUsername extends UserLogin { |
20 | access_token: string | |
21 | refresh_token: string | |
22 | token_type: string | |
23 | username: string | |
24 | } | |
25 | ||
c5911fd3 | 26 | type UserLoginWithUserInformation = UserLoginWithUsername & User |
b1794c53 C |
27 | |
28 | @Injectable() | |
29 | export class AuthService { | |
63c4db6d C |
30 | private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local' |
31 | private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token' | |
32 | private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me' | |
a20776fc C |
33 | private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = { |
34 | CLIENT_ID: 'client_id', | |
35 | CLIENT_SECRET: 'client_secret' | |
36 | } | |
b1794c53 | 37 | |
df98563e | 38 | loginChangedSource: Observable<AuthStatus> |
2de96f4d | 39 | userInformationLoaded = new ReplaySubject<boolean>(1) |
c13e2bf3 | 40 | hotkeys: Hotkey[] |
ec769c89 | 41 | redirectUrl: string |
b1794c53 | 42 | |
a20776fc C |
43 | private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID) |
44 | private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET) | |
df98563e C |
45 | private loginChanged: Subject<AuthStatus> |
46 | private user: AuthUser = null | |
47f8de28 | 47 | private refreshingTokenObservable: Observable<any> |
ccf6ed16 | 48 | |
df98563e | 49 | constructor ( |
d592e0a9 | 50 | private http: HttpClient, |
7ddd02c9 | 51 | private notificationsService: NotificationsService, |
c13e2bf3 | 52 | private hotkeysService: HotkeysService, |
14ad0c27 | 53 | private restExtractor: RestExtractor, |
b1d40cff C |
54 | private router: Router, |
55 | private i18n: I18n | |
db400f44 | 56 | ) { |
df98563e C |
57 | this.loginChanged = new Subject<AuthStatus>() |
58 | this.loginChangedSource = this.loginChanged.asObservable() | |
23a5a916 | 59 | |
bd5c83a8 | 60 | // Return null if there is nothing to load |
df98563e | 61 | this.user = AuthUser.load() |
c13e2bf3 RK |
62 | |
63 | // Set HotKeys | |
64 | this.hotkeys = [ | |
65 | new Hotkey('m s', (event: KeyboardEvent): boolean => { | |
66 | this.router.navigate([ '/videos/subscriptions' ]) | |
67 | return false | |
68 | }, undefined, 'Go to my subscriptions'), | |
69 | new Hotkey('m v', (event: KeyboardEvent): boolean => { | |
70 | this.router.navigate([ '/my-account/videos' ]) | |
71 | return false | |
72 | }, undefined, 'Go to my videos'), | |
73 | new Hotkey('m i', (event: KeyboardEvent): boolean => { | |
74 | this.router.navigate([ '/my-account/video-imports' ]) | |
75 | return false | |
76 | }, undefined, 'Go to my imports'), | |
77 | new Hotkey('m c', (event: KeyboardEvent): boolean => { | |
78 | this.router.navigate([ '/my-account/video-channels' ]) | |
79 | return false | |
80 | }, undefined, 'Go to my channels') | |
81 | ] | |
1553e15d | 82 | } |
b1794c53 | 83 | |
d592e0a9 C |
84 | loadClientCredentials () { |
85 | // Fetch the client_id/client_secret | |
d592e0a9 | 86 | this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL) |
db400f44 C |
87 | .pipe(catchError(res => this.restExtractor.handleError(res))) |
88 | .subscribe( | |
89 | res => { | |
90 | this.clientId = res.client_id | |
91 | this.clientSecret = res.client_secret | |
a20776fc C |
92 | |
93 | peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId) | |
94 | peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret) | |
95 | ||
db400f44 C |
96 | console.log('Client credentials loaded.') |
97 | }, | |
98 | ||
99 | error => { | |
100 | let errorMessage = error.message | |
101 | ||
102 | if (error.status === 403) { | |
25acef90 | 103 | errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text }) |
b1d40cff C |
104 | errorMessage += this.i18n( |
105 | 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.' | |
106 | ) | |
db400f44 C |
107 | } |
108 | ||
109 | // We put a bigger timeout | |
110 | // This is an important message | |
b1d40cff | 111 | this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 }) |
db400f44 C |
112 | } |
113 | ) | |
d592e0a9 C |
114 | } |
115 | ||
df98563e C |
116 | getRefreshToken () { |
117 | if (this.user === null) return null | |
bd5c83a8 | 118 | |
df98563e | 119 | return this.user.getRefreshToken() |
bd5c83a8 C |
120 | } |
121 | ||
df98563e | 122 | getRequestHeaderValue () { |
d592e0a9 C |
123 | const accessToken = this.getAccessToken() |
124 | ||
125 | if (accessToken === null) return null | |
126 | ||
127 | return `${this.getTokenType()} ${accessToken}` | |
1553e15d C |
128 | } |
129 | ||
df98563e C |
130 | getAccessToken () { |
131 | if (this.user === null) return null | |
bd5c83a8 | 132 | |
df98563e | 133 | return this.user.getAccessToken() |
1553e15d C |
134 | } |
135 | ||
df98563e C |
136 | getTokenType () { |
137 | if (this.user === null) return null | |
bd5c83a8 | 138 | |
df98563e | 139 | return this.user.getTokenType() |
1553e15d C |
140 | } |
141 | ||
df98563e C |
142 | getUser () { |
143 | return this.user | |
1553e15d C |
144 | } |
145 | ||
df98563e | 146 | isLoggedIn () { |
d592e0a9 | 147 | return !!this.getAccessToken() |
1553e15d C |
148 | } |
149 | ||
df98563e | 150 | login (username: string, password: string) { |
d592e0a9 | 151 | // Form url encoded |
cd4d7a2c C |
152 | const body = { |
153 | client_id: this.clientId, | |
154 | client_secret: this.clientSecret, | |
155 | response_type: 'code', | |
156 | grant_type: 'password', | |
157 | scope: 'upload', | |
158 | username, | |
159 | password | |
f954b5da | 160 | } |
d592e0a9 C |
161 | |
162 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') | |
cd4d7a2c | 163 | return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers }) |
db400f44 C |
164 | .pipe( |
165 | map(res => Object.assign(res, { username })), | |
166 | mergeMap(res => this.mergeUserInformation(res)), | |
167 | map(res => this.handleLogin(res)), | |
168 | catchError(res => this.restExtractor.handleError(res)) | |
169 | ) | |
4fd8aa32 C |
170 | } |
171 | ||
df98563e | 172 | logout () { |
bd5c83a8 | 173 | // TODO: make an HTTP request to revoke the tokens |
df98563e | 174 | this.user = null |
724fed29 | 175 | |
df98563e | 176 | AuthUser.flush() |
e62f6ef7 | 177 | |
df98563e | 178 | this.setStatus(AuthStatus.LoggedOut) |
c13e2bf3 RK |
179 | |
180 | this.hotkeysService.remove(this.hotkeys) | |
ec769c89 B |
181 | |
182 | this.redirectUrl = null | |
bd5c83a8 C |
183 | } |
184 | ||
df98563e | 185 | refreshAccessToken () { |
47f8de28 C |
186 | if (this.refreshingTokenObservable) return this.refreshingTokenObservable |
187 | ||
df98563e | 188 | console.log('Refreshing token...') |
bd5c83a8 | 189 | |
df98563e | 190 | const refreshToken = this.getRefreshToken() |
bd5c83a8 | 191 | |
d592e0a9 C |
192 | // Form url encoded |
193 | const body = new HttpParams().set('refresh_token', refreshToken) | |
194 | .set('client_id', this.clientId) | |
195 | .set('client_secret', this.clientSecret) | |
196 | .set('response_type', 'code') | |
197 | .set('grant_type', 'refresh_token') | |
bd5c83a8 | 198 | |
d592e0a9 | 199 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') |
bd5c83a8 | 200 | |
47f8de28 | 201 | this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers }) |
db400f44 C |
202 | .pipe( |
203 | map(res => this.handleRefreshToken(res)), | |
204 | tap(() => this.refreshingTokenObservable = null), | |
205 | catchError(err => { | |
206 | this.refreshingTokenObservable = null | |
207 | ||
208 | console.error(err) | |
209 | console.log('Cannot refresh token -> logout...') | |
210 | this.logout() | |
211 | this.router.navigate([ '/login' ]) | |
212 | ||
213 | return observableThrowError({ | |
b1d40cff | 214 | error: this.i18n('You need to reconnect.') |
db400f44 | 215 | }) |
a20776fc C |
216 | }), |
217 | share() | |
db400f44 | 218 | ) |
47f8de28 C |
219 | |
220 | return this.refreshingTokenObservable | |
4fd8aa32 C |
221 | } |
222 | ||
d592e0a9 | 223 | refreshUserInformation () { |
af5e743b | 224 | const obj = { |
33c4972d C |
225 | access_token: this.user.getAccessToken(), |
226 | refresh_token: null, | |
227 | token_type: this.user.getTokenType(), | |
228 | username: this.user.username | |
df98563e | 229 | } |
af5e743b | 230 | |
d592e0a9 | 231 | this.mergeUserInformation(obj) |
db400f44 C |
232 | .subscribe( |
233 | res => { | |
234 | this.user.patch(res) | |
235 | this.user.save() | |
cadb46d8 | 236 | |
db400f44 C |
237 | this.userInformationLoaded.next(true) |
238 | } | |
239 | ) | |
af5e743b C |
240 | } |
241 | ||
d592e0a9 C |
242 | private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> { |
243 | // User is not loaded yet, set manually auth header | |
244 | const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`) | |
245 | ||
bcd9f81e | 246 | return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers }) |
db400f44 | 247 | .pipe(map(res => Object.assign(obj, res))) |
b1794c53 C |
248 | } |
249 | ||
d592e0a9 | 250 | private handleLogin (obj: UserLoginWithUserInformation) { |
7da18e44 | 251 | const hashTokens = { |
df98563e C |
252 | accessToken: obj.access_token, |
253 | tokenType: obj.token_type, | |
254 | refreshToken: obj.refresh_token | |
255 | } | |
bd5c83a8 | 256 | |
ce5496d6 | 257 | this.user = new AuthUser(obj, hashTokens) |
df98563e | 258 | this.user.save() |
bd5c83a8 | 259 | |
df98563e | 260 | this.setStatus(AuthStatus.LoggedIn) |
efc32059 | 261 | this.userInformationLoaded.next(true) |
c13e2bf3 RK |
262 | |
263 | this.hotkeysService.add(this.hotkeys) | |
bd5c83a8 C |
264 | } |
265 | ||
d592e0a9 | 266 | private handleRefreshToken (obj: UserRefreshToken) { |
df98563e C |
267 | this.user.refreshTokens(obj.access_token, obj.refresh_token) |
268 | this.user.save() | |
bd5c83a8 | 269 | } |
629d8d6f | 270 | |
df98563e C |
271 | private setStatus (status: AuthStatus) { |
272 | this.loginChanged.next(status) | |
629d8d6f | 273 | } |
b1794c53 | 274 | } |