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