]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
363f58155e7f277871a128d409daf0b75d0ae272
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
1 import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
2 import { catchError, map, mergeMap, share, tap } from 'rxjs/operators'
3 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { Router } from '@angular/router'
6 import { NotificationsService } from 'angular2-notifications'
7 import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
8 import { User } from '../../../../../shared/models/users'
9 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
10 import { environment } from '../../../environments/environment'
11 import { RestExtractor } from '../../shared/rest'
12 import { AuthStatus } from './auth-status.model'
13 import { AuthUser } from './auth-user.model'
14 import { objectToUrlEncoded } from '@app/shared/misc/utils'
15 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
16 import { I18n } from '@ngx-translate/i18n-polyfill'
17
18 interface UserLoginWithUsername extends UserLogin {
19 access_token: string
20 refresh_token: string
21 token_type: string
22 username: string
23 }
24
25 type UserLoginWithUserInformation = UserLoginWithUsername & User
26
27 @Injectable()
28 export class AuthService {
29 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
30 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
31 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
32 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
33 CLIENT_ID: 'client_id',
34 CLIENT_SECRET: 'client_secret'
35 }
36
37 loginChangedSource: Observable<AuthStatus>
38 userInformationLoaded = new ReplaySubject<boolean>(1)
39
40 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
41 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
42 private loginChanged: Subject<AuthStatus>
43 private user: AuthUser = null
44 private refreshingTokenObservable: Observable<any>
45
46 constructor (
47 private http: HttpClient,
48 private notificationsService: NotificationsService,
49 private restExtractor: RestExtractor,
50 private router: Router,
51 private i18n: I18n
52 ) {
53 this.loginChanged = new Subject<AuthStatus>()
54 this.loginChangedSource = this.loginChanged.asObservable()
55
56 // Return null if there is nothing to load
57 this.user = AuthUser.load()
58 }
59
60 loadClientCredentials () {
61 // Fetch the client_id/client_secret
62 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
63 .pipe(catchError(res => this.restExtractor.handleError(res)))
64 .subscribe(
65 res => {
66 this.clientId = res.client_id
67 this.clientSecret = res.client_secret
68
69 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
70 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
71
72 console.log('Client credentials loaded.')
73 },
74
75 error => {
76 let errorMessage = error.message
77
78 if (error.status === 403) {
79 errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{ errorText }}.\n', { errorText: error.text })
80 errorMessage += this.i18n(
81 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
82 )
83 }
84
85 // We put a bigger timeout
86 // This is an important message
87 this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 })
88 }
89 )
90 }
91
92 getRefreshToken () {
93 if (this.user === null) return null
94
95 return this.user.getRefreshToken()
96 }
97
98 getRequestHeaderValue () {
99 const accessToken = this.getAccessToken()
100
101 if (accessToken === null) return null
102
103 return `${this.getTokenType()} ${accessToken}`
104 }
105
106 getAccessToken () {
107 if (this.user === null) return null
108
109 return this.user.getAccessToken()
110 }
111
112 getTokenType () {
113 if (this.user === null) return null
114
115 return this.user.getTokenType()
116 }
117
118 getUser () {
119 return this.user
120 }
121
122 isLoggedIn () {
123 return !!this.getAccessToken()
124 }
125
126 login (username: string, password: string) {
127 // Form url encoded
128 const body = {
129 client_id: this.clientId,
130 client_secret: this.clientSecret,
131 response_type: 'code',
132 grant_type: 'password',
133 scope: 'upload',
134 username,
135 password
136 }
137
138 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
139 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
140 .pipe(
141 map(res => Object.assign(res, { username })),
142 mergeMap(res => this.mergeUserInformation(res)),
143 map(res => this.handleLogin(res)),
144 catchError(res => this.restExtractor.handleError(res))
145 )
146 }
147
148 logout () {
149 // TODO: make an HTTP request to revoke the tokens
150 this.user = null
151
152 AuthUser.flush()
153
154 this.setStatus(AuthStatus.LoggedOut)
155 }
156
157 refreshAccessToken () {
158 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
159
160 console.log('Refreshing token...')
161
162 const refreshToken = this.getRefreshToken()
163
164 // Form url encoded
165 const body = new HttpParams().set('refresh_token', refreshToken)
166 .set('client_id', this.clientId)
167 .set('client_secret', this.clientSecret)
168 .set('response_type', 'code')
169 .set('grant_type', 'refresh_token')
170
171 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
172
173 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
174 .pipe(
175 map(res => this.handleRefreshToken(res)),
176 tap(() => this.refreshingTokenObservable = null),
177 catchError(err => {
178 this.refreshingTokenObservable = null
179
180 console.error(err)
181 console.log('Cannot refresh token -> logout...')
182 this.logout()
183 this.router.navigate([ '/login' ])
184
185 return observableThrowError({
186 error: this.i18n('You need to reconnect.')
187 })
188 }),
189 share()
190 )
191
192 return this.refreshingTokenObservable
193 }
194
195 refreshUserInformation () {
196 const obj = {
197 access_token: this.user.getAccessToken(),
198 refresh_token: null,
199 token_type: this.user.getTokenType(),
200 username: this.user.username
201 }
202
203 this.mergeUserInformation(obj)
204 .subscribe(
205 res => {
206 this.user.patch(res)
207 this.user.save()
208
209 this.userInformationLoaded.next(true)
210 }
211 )
212 }
213
214 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
215 // User is not loaded yet, set manually auth header
216 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
217
218 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
219 .pipe(map(res => Object.assign(obj, res)))
220 }
221
222 private handleLogin (obj: UserLoginWithUserInformation) {
223 const hashTokens = {
224 accessToken: obj.access_token,
225 tokenType: obj.token_type,
226 refreshToken: obj.refresh_token
227 }
228
229 this.user = new AuthUser(obj, hashTokens)
230 this.user.save()
231
232 this.setStatus(AuthStatus.LoggedIn)
233 this.userInformationLoaded.next(true)
234 }
235
236 private handleRefreshToken (obj: UserRefreshToken) {
237 this.user.refreshTokens(obj.access_token, obj.refresh_token)
238 this.user.save()
239 }
240
241 private setStatus (status: AuthStatus) {
242 this.loginChanged.next(status)
243 }
244 }