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