]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
8a2ba77d6b16d30bb40f6bd47f530df4cccab392
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
1 import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
2 import { Injectable } from '@angular/core'
3 import { Router } from '@angular/router'
4 import { NotificationsService } from 'angular2-notifications'
5 import 'rxjs/add/observable/throw'
6 import 'rxjs/add/operator/do'
7 import 'rxjs/add/operator/map'
8 import 'rxjs/add/operator/mergeMap'
9 import { Observable } from 'rxjs/Observable'
10 import { ReplaySubject } from 'rxjs/ReplaySubject'
11 import { Subject } from 'rxjs/Subject'
12 import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
13 import { User } from '../../../../../shared/models/users'
14 import { UserLogin } from '../../../../../shared/models/users/user-login.model'
15 import { environment } from '../../../environments/environment'
16 import { RestExtractor } from '../../shared/rest'
17 import { UserConstructorHash } from '../../shared/users/user.model'
18 import { AuthStatus } from './auth-status.model'
19 import { AuthUser } from './auth-user.model'
20
21 interface UserLoginWithUsername extends UserLogin {
22 access_token: string
23 refresh_token: string
24 token_type: string
25 username: string
26 }
27
28 type UserLoginWithUserInformation = UserLoginWithUsername & User
29
30 @Injectable()
31 export class AuthService {
32 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
33 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
34 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
35
36 loginChangedSource: Observable<AuthStatus>
37 userInformationLoaded = new ReplaySubject<boolean>(1)
38
39 private clientId: string
40 private clientSecret: string
41 private loginChanged: Subject<AuthStatus>
42 private user: AuthUser = null
43
44 constructor (
45 private http: HttpClient,
46 private notificationsService: NotificationsService,
47 private restExtractor: RestExtractor,
48 private router: Router
49 ) {
50 this.loginChanged = new Subject<AuthStatus>()
51 this.loginChangedSource = this.loginChanged.asObservable()
52
53 // Return null if there is nothing to load
54 this.user = AuthUser.load()
55 }
56
57 loadClientCredentials () {
58 // Fetch the client_id/client_secret
59 // FIXME: save in local storage?
60 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
61 .catch(res => this.restExtractor.handleError(res))
62 .subscribe(
63 res => {
64 this.clientId = res.client_id
65 this.clientSecret = res.client_secret
66 console.log('Client credentials loaded.')
67 },
68
69 error => {
70 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
71 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
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 HttpParams().set('client_id', this.clientId)
117 .set('client_secret', this.clientSecret)
118 .set('response_type', 'code')
119 .set('grant_type', 'password')
120 .set('scope', 'upload')
121 .set('username', username)
122 .set('password', password)
123
124 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
125
126 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
127 .map(res => Object.assign(res, { username }))
128 .flatMap(res => this.mergeUserInformation(res))
129 .map(res => this.handleLogin(res))
130 .catch(res => this.restExtractor.handleError(res))
131 }
132
133 logout () {
134 // TODO: make an HTTP request to revoke the tokens
135 this.user = null
136
137 AuthUser.flush()
138
139 this.setStatus(AuthStatus.LoggedOut)
140 }
141
142 refreshAccessToken () {
143 console.log('Refreshing token...')
144
145 const refreshToken = this.getRefreshToken()
146
147 // Form url encoded
148 const body = new HttpParams().set('refresh_token', refreshToken)
149 .set('client_id', this.clientId)
150 .set('client_secret', this.clientSecret)
151 .set('response_type', 'code')
152 .set('grant_type', 'refresh_token')
153
154 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
155
156 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
157 .map(res => this.handleRefreshToken(res))
158 .catch(err => {
159 console.error(err)
160 console.log('Cannot refresh token -> logout...')
161 this.logout()
162 this.router.navigate(['/login'])
163
164 return Observable.throw({
165 error: 'You need to reconnect.'
166 })
167 })
168 }
169
170 refreshUserInformation () {
171 const obj = {
172 access_token: this.user.getAccessToken(),
173 refresh_token: null,
174 token_type: this.user.getTokenType(),
175 username: this.user.username
176 }
177
178 this.mergeUserInformation(obj)
179 .subscribe(
180 res => {
181 this.user.displayNSFW = res.displayNSFW
182 this.user.autoPlayVideo = res.autoPlayVideo
183 this.user.role = res.role
184 this.user.videoChannels = res.videoChannels
185 this.user.account = res.account
186
187 this.user.save()
188
189 this.userInformationLoaded.next(true)
190 }
191 )
192 }
193
194 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
195 // User is not loaded yet, set manually auth header
196 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
197
198 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
199 .map(res => Object.assign(obj, res))
200 }
201
202 private handleLogin (obj: UserLoginWithUserInformation) {
203 const hashUser: UserConstructorHash = {
204 id: obj.id,
205 username: obj.username,
206 role: obj.role,
207 email: obj.email,
208 displayNSFW: obj.displayNSFW,
209 autoPlayVideo: obj.autoPlayVideo,
210 videoQuota: obj.videoQuota,
211 videoChannels: obj.videoChannels,
212 account: obj.account
213 }
214 const hashTokens = {
215 accessToken: obj.access_token,
216 tokenType: obj.token_type,
217 refreshToken: obj.refresh_token
218 }
219
220 this.user = new AuthUser(hashUser, hashTokens)
221 this.user.save()
222
223 this.setStatus(AuthStatus.LoggedIn)
224 this.userInformationLoaded.next(true)
225 }
226
227 private handleRefreshToken (obj: UserRefreshToken) {
228 this.user.refreshTokens(obj.access_token, obj.refresh_token)
229 this.user.save()
230 }
231
232 private setStatus (status: AuthStatus) {
233 this.loginChanged.next(status)
234 }
235 }