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