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