]>
Commit | Line | Data |
---|---|---|
df98563e | 1 | import { Injectable } from '@angular/core' |
df98563e C |
2 | import { Router } from '@angular/router' |
3 | import { Observable } from 'rxjs/Observable' | |
4 | import { Subject } from 'rxjs/Subject' | |
d592e0a9 | 5 | import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http' |
df98563e C |
6 | import 'rxjs/add/operator/map' |
7 | import 'rxjs/add/operator/mergeMap' | |
8 | import 'rxjs/add/observable/throw' | |
9 | ||
10 | import { NotificationsService } from 'angular2-notifications' | |
11 | ||
12 | import { AuthStatus } from './auth-status.model' | |
13 | import { AuthUser } from './auth-user.model' | |
d592e0a9 | 14 | import { OAuthClientLocal, UserRole, UserRefreshToken } from '../../../../../shared' |
693b1aba | 15 | // Do not use the barrel (dependency loop) |
df98563e | 16 | import { RestExtractor } from '../../shared/rest' |
d592e0a9 C |
17 | import { UserLogin } from '../../../../../shared/models/users/user-login.model' |
18 | import { User } from '../../shared/users/user.model' | |
19 | ||
20 | interface UserLoginWithUsername extends UserLogin { | |
21 | access_token: string | |
22 | refresh_token: string | |
23 | token_type: string | |
24 | username: string | |
25 | } | |
26 | ||
27 | interface UserLoginWithUserInformation extends UserLogin { | |
28 | access_token: string | |
29 | refresh_token: string | |
30 | token_type: string | |
31 | username: string | |
32 | id: number | |
33 | role: UserRole | |
34 | displayNSFW: boolean | |
35 | email: string | |
36 | } | |
b1794c53 C |
37 | |
38 | @Injectable() | |
39 | export class AuthService { | |
0a381679 | 40 | private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local' |
df98563e | 41 | private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token' |
d592e0a9 | 42 | private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me' |
b1794c53 | 43 | |
df98563e | 44 | loginChangedSource: Observable<AuthStatus> |
b1794c53 | 45 | |
df98563e C |
46 | private clientId: string |
47 | private clientSecret: string | |
48 | private loginChanged: Subject<AuthStatus> | |
49 | private user: AuthUser = null | |
ccf6ed16 | 50 | |
df98563e | 51 | constructor ( |
d592e0a9 | 52 | private http: HttpClient, |
7ddd02c9 | 53 | private notificationsService: NotificationsService, |
14ad0c27 C |
54 | private restExtractor: RestExtractor, |
55 | private router: Router | |
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() |
1553e15d | 62 | } |
b1794c53 | 63 | |
d592e0a9 C |
64 | loadClientCredentials () { |
65 | // Fetch the client_id/client_secret | |
66 | // FIXME: save in local storage? | |
67 | this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL) | |
68 | .catch(res => this.restExtractor.handleError(res)) | |
69 | .subscribe( | |
70 | res => { | |
71 | this.clientId = res.client_id | |
72 | this.clientSecret = res.client_secret | |
73 | console.log('Client credentials loaded.') | |
74 | }, | |
75 | ||
76 | error => { | |
77 | let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n` | |
78 | errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.' | |
79 | ||
80 | // We put a bigger timeout | |
81 | // This is an important message | |
82 | this.notificationsService.error('Error', errorMessage, { timeOut: 7000 }) | |
83 | } | |
84 | ) | |
85 | } | |
86 | ||
df98563e C |
87 | getRefreshToken () { |
88 | if (this.user === null) return null | |
bd5c83a8 | 89 | |
df98563e | 90 | return this.user.getRefreshToken() |
bd5c83a8 C |
91 | } |
92 | ||
df98563e | 93 | getRequestHeaderValue () { |
d592e0a9 C |
94 | const accessToken = this.getAccessToken() |
95 | ||
96 | if (accessToken === null) return null | |
97 | ||
98 | return `${this.getTokenType()} ${accessToken}` | |
1553e15d C |
99 | } |
100 | ||
df98563e C |
101 | getAccessToken () { |
102 | if (this.user === null) return null | |
bd5c83a8 | 103 | |
df98563e | 104 | return this.user.getAccessToken() |
1553e15d C |
105 | } |
106 | ||
df98563e C |
107 | getTokenType () { |
108 | if (this.user === null) return null | |
bd5c83a8 | 109 | |
df98563e | 110 | return this.user.getTokenType() |
1553e15d C |
111 | } |
112 | ||
df98563e C |
113 | getUser () { |
114 | return this.user | |
1553e15d C |
115 | } |
116 | ||
df98563e C |
117 | isAdmin () { |
118 | if (this.user === null) return false | |
7da18e44 | 119 | |
df98563e | 120 | return this.user.isAdmin() |
7da18e44 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)) |
d592e0a9 | 171 | .catch(res => { |
14ad0c27 | 172 | // The refresh token is invalid? |
127d96b9 | 173 | if (res.status === 400 && res.error.error === 'invalid_grant') { |
df98563e C |
174 | console.error('Cannot refresh token -> logout...') |
175 | this.logout() | |
176 | this.router.navigate(['/login']) | |
14ad0c27 C |
177 | |
178 | return Observable.throw({ | |
d592e0a9 | 179 | error: 'You need to reconnect.' |
df98563e | 180 | }) |
14ad0c27 C |
181 | } |
182 | ||
df98563e C |
183 | return this.restExtractor.handleError(res) |
184 | }) | |
4fd8aa32 C |
185 | } |
186 | ||
d592e0a9 | 187 | refreshUserInformation () { |
af5e743b | 188 | const obj = { |
33c4972d C |
189 | access_token: this.user.getAccessToken(), |
190 | refresh_token: null, | |
191 | token_type: this.user.getTokenType(), | |
192 | username: this.user.username | |
df98563e | 193 | } |
af5e743b | 194 | |
d592e0a9 | 195 | this.mergeUserInformation(obj) |
af5e743b C |
196 | .subscribe( |
197 | res => { | |
df98563e C |
198 | this.user.displayNSFW = res.displayNSFW |
199 | this.user.role = res.role | |
af5e743b | 200 | |
df98563e | 201 | this.user.save() |
af5e743b | 202 | } |
df98563e | 203 | ) |
af5e743b C |
204 | } |
205 | ||
d592e0a9 C |
206 | private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> { |
207 | // User is not loaded yet, set manually auth header | |
208 | const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`) | |
209 | ||
210 | return this.http.get<User>(AuthService.BASE_USER_INFORMATION_URL, { headers }) | |
211 | .map(res => { | |
212 | const newProperties = { | |
213 | id: res.id as number, | |
214 | role: res.role as UserRole, | |
215 | displayNSFW: res.displayNSFW as boolean, | |
216 | email: res.email as string | |
217 | } | |
af5e743b | 218 | |
d592e0a9 C |
219 | return Object.assign(obj, newProperties) |
220 | } | |
df98563e | 221 | ) |
b1794c53 C |
222 | } |
223 | ||
d592e0a9 | 224 | private handleLogin (obj: UserLoginWithUserInformation) { |
df98563e C |
225 | const id = obj.id |
226 | const username = obj.username | |
227 | const role = obj.role | |
228 | const email = obj.email | |
229 | const displayNSFW = obj.displayNSFW | |
7da18e44 | 230 | const hashTokens = { |
df98563e C |
231 | accessToken: obj.access_token, |
232 | tokenType: obj.token_type, | |
233 | refreshToken: obj.refresh_token | |
234 | } | |
bd5c83a8 | 235 | |
df98563e C |
236 | this.user = new AuthUser({ id, username, role, displayNSFW, email }, hashTokens) |
237 | this.user.save() | |
bd5c83a8 | 238 | |
df98563e | 239 | this.setStatus(AuthStatus.LoggedIn) |
bd5c83a8 C |
240 | } |
241 | ||
d592e0a9 | 242 | private handleRefreshToken (obj: UserRefreshToken) { |
df98563e C |
243 | this.user.refreshTokens(obj.access_token, obj.refresh_token) |
244 | this.user.save() | |
bd5c83a8 | 245 | } |
629d8d6f | 246 | |
df98563e C |
247 | private setStatus (status: AuthStatus) { |
248 | this.loginChanged.next(status) | |
629d8d6f | 249 | } |
b1794c53 | 250 | } |