]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
4a8814c4e4c5dc6e077952606380fe1f911cd73c
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
1 import { Injectable } from '@angular/core'
2 import { Router } from '@angular/router'
3 import { Observable } from 'rxjs/Observable'
4 import { Subject } from 'rxjs/Subject'
5 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
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'
14 import { OAuthClientLocal, UserRole, UserRefreshToken } from '../../../../../shared'
15 // Do not use the barrel (dependency loop)
16 import { RestExtractor } from '../../shared/rest'
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 }
37
38 @Injectable()
39 export class AuthService {
40 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
41 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
42 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
43
44 loginChangedSource: Observable<AuthStatus>
45
46 private clientId: string
47 private clientSecret: string
48 private loginChanged: Subject<AuthStatus>
49 private user: AuthUser = null
50
51 constructor (
52 private http: HttpClient,
53 private notificationsService: NotificationsService,
54 private restExtractor: RestExtractor,
55 private router: Router
56 ) {
57 this.loginChanged = new Subject<AuthStatus>()
58 this.loginChangedSource = this.loginChanged.asObservable()
59
60 // Return null if there is nothing to load
61 this.user = AuthUser.load()
62 }
63
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
87 getRefreshToken () {
88 if (this.user === null) return null
89
90 return this.user.getRefreshToken()
91 }
92
93 getRequestHeaderValue () {
94 const accessToken = this.getAccessToken()
95
96 if (accessToken === null) return null
97
98 return `${this.getTokenType()} ${accessToken}`
99 }
100
101 getAccessToken () {
102 if (this.user === null) return null
103
104 return this.user.getAccessToken()
105 }
106
107 getTokenType () {
108 if (this.user === null) return null
109
110 return this.user.getTokenType()
111 }
112
113 getUser () {
114 return this.user
115 }
116
117 isAdmin () {
118 if (this.user === null) return false
119
120 return this.user.isAdmin()
121 }
122
123 isLoggedIn () {
124 return !!this.getAccessToken()
125 }
126
127 login (username: string, password: string) {
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))
142 .map(res => this.handleLogin(res))
143 .catch(res => this.restExtractor.handleError(res))
144 }
145
146 logout () {
147 // TODO: make an HTTP request to revoke the tokens
148 this.user = null
149
150 AuthUser.flush()
151
152 this.setStatus(AuthStatus.LoggedOut)
153 }
154
155 refreshAccessToken () {
156 console.log('Refreshing token...')
157
158 const refreshToken = this.getRefreshToken()
159
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')
166
167 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
168
169 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
170 .map(res => this.handleRefreshToken(res))
171 .catch(res => {
172 // The refresh token is invalid?
173 if (res.status === 400 && res.error.error === 'invalid_grant') {
174 console.error('Cannot refresh token -> logout...')
175 this.logout()
176 this.router.navigate(['/login'])
177
178 return Observable.throw({
179 error: 'You need to reconnect.'
180 })
181 }
182
183 return this.restExtractor.handleError(res)
184 })
185 }
186
187 refreshUserInformation () {
188 const obj = {
189 access_token: this.user.getAccessToken(),
190 refresh_token: null,
191 token_type: this.user.getTokenType(),
192 username: this.user.username
193 }
194
195 this.mergeUserInformation(obj)
196 .subscribe(
197 res => {
198 this.user.displayNSFW = res.displayNSFW
199 this.user.role = res.role
200
201 this.user.save()
202 }
203 )
204 }
205
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 }
218
219 return Object.assign(obj, newProperties)
220 }
221 )
222 }
223
224 private handleLogin (obj: UserLoginWithUserInformation) {
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
230 const hashTokens = {
231 accessToken: obj.access_token,
232 tokenType: obj.token_type,
233 refreshToken: obj.refresh_token
234 }
235
236 this.user = new AuthUser({ id, username, role, displayNSFW, email }, hashTokens)
237 this.user.save()
238
239 this.setStatus(AuthStatus.LoggedIn)
240 }
241
242 private handleRefreshToken (obj: UserRefreshToken) {
243 this.user.refreshTokens(obj.access_token, obj.refresh_token)
244 this.user.save()
245 }
246
247 private setStatus (status: AuthStatus) {
248 this.loginChanged.next(status)
249 }
250 }