]>
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' | |
c5911fd3 C |
12 | import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared' |
13 | import { User } from '../../../../../shared/models/users' | |
2295ce6c | 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 | ||
c5911fd3 | 28 | type UserLoginWithUserInformation = UserLoginWithUsername & User |
b1794c53 C |
29 | |
30 | @Injectable() | |
31 | export class AuthService { | |
63c4db6d C |
32 | private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local' |
33 | private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token' | |
34 | private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me' | |
b1794c53 | 35 | |
df98563e | 36 | loginChangedSource: Observable<AuthStatus> |
2de96f4d | 37 | userInformationLoaded = new ReplaySubject<boolean>(1) |
b1794c53 | 38 | |
df98563e C |
39 | private clientId: string |
40 | private clientSecret: string | |
41 | private loginChanged: Subject<AuthStatus> | |
42 | private user: AuthUser = null | |
ccf6ed16 | 43 | |
df98563e | 44 | constructor ( |
d592e0a9 | 45 | private http: HttpClient, |
7ddd02c9 | 46 | private notificationsService: NotificationsService, |
14ad0c27 C |
47 | private restExtractor: RestExtractor, |
48 | private router: Router | |
49 | ) { | |
df98563e C |
50 | this.loginChanged = new Subject<AuthStatus>() |
51 | this.loginChangedSource = this.loginChanged.asObservable() | |
23a5a916 | 52 | |
bd5c83a8 | 53 | // Return null if there is nothing to load |
df98563e | 54 | this.user = AuthUser.load() |
1553e15d | 55 | } |
b1794c53 | 56 | |
d592e0a9 C |
57 | loadClientCredentials () { |
58 | // Fetch the client_id/client_secret | |
59 | // FIXME: save in local storage? | |
60 | this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL) | |
61 | .catch(res => this.restExtractor.handleError(res)) | |
62 | .subscribe( | |
63 | res => { | |
64 | this.clientId = res.client_id | |
65 | this.clientSecret = res.client_secret | |
66 | console.log('Client credentials loaded.') | |
67 | }, | |
68 | ||
69 | error => { | |
70 | let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n` | |
71 | errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.' | |
72 | ||
73 | // We put a bigger timeout | |
74 | // This is an important message | |
75 | this.notificationsService.error('Error', errorMessage, { timeOut: 7000 }) | |
76 | } | |
77 | ) | |
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 C |
115 | // Form url encoded |
116 | const body = new HttpParams().set('client_id', this.clientId) | |
117 | .set('client_secret', this.clientSecret) | |
118 | .set('response_type', 'code') | |
119 | .set('grant_type', 'password') | |
120 | .set('scope', 'upload') | |
121 | .set('username', username) | |
122 | .set('password', password) | |
123 | ||
124 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') | |
125 | ||
126 | return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers }) | |
127 | .map(res => Object.assign(res, { username })) | |
128 | .flatMap(res => this.mergeUserInformation(res)) | |
bd5c83a8 | 129 | .map(res => this.handleLogin(res)) |
d592e0a9 | 130 | .catch(res => this.restExtractor.handleError(res)) |
4fd8aa32 C |
131 | } |
132 | ||
df98563e | 133 | logout () { |
bd5c83a8 | 134 | // TODO: make an HTTP request to revoke the tokens |
df98563e | 135 | this.user = null |
724fed29 | 136 | |
df98563e | 137 | AuthUser.flush() |
e62f6ef7 | 138 | |
df98563e | 139 | this.setStatus(AuthStatus.LoggedOut) |
bd5c83a8 C |
140 | } |
141 | ||
df98563e C |
142 | refreshAccessToken () { |
143 | console.log('Refreshing token...') | |
bd5c83a8 | 144 | |
df98563e | 145 | const refreshToken = this.getRefreshToken() |
bd5c83a8 | 146 | |
d592e0a9 C |
147 | // Form url encoded |
148 | const body = new HttpParams().set('refresh_token', refreshToken) | |
149 | .set('client_id', this.clientId) | |
150 | .set('client_secret', this.clientSecret) | |
151 | .set('response_type', 'code') | |
152 | .set('grant_type', 'refresh_token') | |
bd5c83a8 | 153 | |
d592e0a9 | 154 | const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') |
bd5c83a8 | 155 | |
d592e0a9 | 156 | return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers }) |
bd5c83a8 | 157 | .map(res => this.handleRefreshToken(res)) |
f595d394 C |
158 | .catch(err => { |
159 | console.error(err) | |
160 | console.log('Cannot refresh token -> logout...') | |
161 | this.logout() | |
162 | this.router.navigate(['/login']) | |
163 | ||
164 | return Observable.throw({ | |
165 | error: 'You need to reconnect.' | |
166 | }) | |
df98563e | 167 | }) |
4fd8aa32 C |
168 | } |
169 | ||
d592e0a9 | 170 | refreshUserInformation () { |
af5e743b | 171 | const obj = { |
33c4972d C |
172 | access_token: this.user.getAccessToken(), |
173 | refresh_token: null, | |
174 | token_type: this.user.getTokenType(), | |
175 | username: this.user.username | |
df98563e | 176 | } |
af5e743b | 177 | |
d592e0a9 | 178 | this.mergeUserInformation(obj) |
2de96f4d C |
179 | .subscribe( |
180 | res => { | |
181 | this.user.displayNSFW = res.displayNSFW | |
7efe153b | 182 | this.user.autoPlayVideo = res.autoPlayVideo |
2de96f4d C |
183 | this.user.role = res.role |
184 | this.user.videoChannels = res.videoChannels | |
1e1265b3 | 185 | this.user.account = res.account |
2de96f4d C |
186 | |
187 | this.user.save() | |
cadb46d8 C |
188 | |
189 | this.userInformationLoaded.next(true) | |
2de96f4d C |
190 | } |
191 | ) | |
af5e743b C |
192 | } |
193 | ||
d592e0a9 C |
194 | private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> { |
195 | // User is not loaded yet, set manually auth header | |
196 | const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`) | |
197 | ||
bcd9f81e | 198 | return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers }) |
c5911fd3 | 199 | .map(res => Object.assign(obj, res)) |
b1794c53 C |
200 | } |
201 | ||
d592e0a9 | 202 | private handleLogin (obj: UserLoginWithUserInformation) { |
bcd9f81e C |
203 | const hashUser: UserConstructorHash = { |
204 | id: obj.id, | |
205 | username: obj.username, | |
206 | role: obj.role, | |
207 | email: obj.email, | |
208 | displayNSFW: obj.displayNSFW, | |
7efe153b | 209 | autoPlayVideo: obj.autoPlayVideo, |
bcd9f81e C |
210 | videoQuota: obj.videoQuota, |
211 | videoChannels: obj.videoChannels, | |
1e1265b3 | 212 | account: obj.account |
bcd9f81e | 213 | } |
7da18e44 | 214 | const hashTokens = { |
df98563e C |
215 | accessToken: obj.access_token, |
216 | tokenType: obj.token_type, | |
217 | refreshToken: obj.refresh_token | |
218 | } | |
bd5c83a8 | 219 | |
bcd9f81e | 220 | this.user = new AuthUser(hashUser, hashTokens) |
df98563e | 221 | this.user.save() |
bd5c83a8 | 222 | |
df98563e | 223 | this.setStatus(AuthStatus.LoggedIn) |
efc32059 | 224 | this.userInformationLoaded.next(true) |
bd5c83a8 C |
225 | } |
226 | ||
d592e0a9 | 227 | private handleRefreshToken (obj: UserRefreshToken) { |
df98563e C |
228 | this.user.refreshTokens(obj.access_token, obj.refresh_token) |
229 | this.user.save() | |
bd5c83a8 | 230 | } |
629d8d6f | 231 | |
df98563e C |
232 | private setStatus (status: AuthStatus) { |
233 | this.loginChanged.next(status) | |
629d8d6f | 234 | } |
b1794c53 | 235 | } |