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