]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/core/auth/auth.service.ts
Move to angular cli
[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, UserRole, VideoChannel } from '../../../../../shared'
13 import { Account } from '../../../../../shared/models/accounts'
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 interface UserLoginWithUserInformation extends UserLogin {
29 access_token: string
30 refresh_token: string
31 token_type: string
32 username: string
33 id: number
34 role: UserRole
35 displayNSFW: boolean
36 email: string
37 videoQuota: number
38 account: Account
39 videoChannels: VideoChannel[]
40 }
41
42 @Injectable()
43 export class AuthService {
44 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
45 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
46 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
47
48 loginChangedSource: Observable<AuthStatus>
49 userInformationLoaded = new ReplaySubject<boolean>(1)
50
51 private clientId: string
52 private clientSecret: string
53 private loginChanged: Subject<AuthStatus>
54 private user: AuthUser = null
55
56 constructor (
57 private http: HttpClient,
58 private notificationsService: NotificationsService,
59 private restExtractor: RestExtractor,
60 private router: Router
61 ) {
62 this.loginChanged = new Subject<AuthStatus>()
63 this.loginChangedSource = this.loginChanged.asObservable()
64
65 // Return null if there is nothing to load
66 this.user = AuthUser.load()
67 }
68
69 loadClientCredentials () {
70 // Fetch the client_id/client_secret
71 // FIXME: save in local storage?
72 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
73 .catch(res => this.restExtractor.handleError(res))
74 .subscribe(
75 res => {
76 this.clientId = res.client_id
77 this.clientSecret = res.client_secret
78 console.log('Client credentials loaded.')
79 },
80
81 error => {
82 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
83 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
84
85 // We put a bigger timeout
86 // This is an important message
87 this.notificationsService.error('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 = new HttpParams().set('client_id', this.clientId)
129 .set('client_secret', this.clientSecret)
130 .set('response_type', 'code')
131 .set('grant_type', 'password')
132 .set('scope', 'upload')
133 .set('username', username)
134 .set('password', password)
135
136 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
137
138 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
139 .map(res => Object.assign(res, { username }))
140 .flatMap(res => this.mergeUserInformation(res))
141 .map(res => this.handleLogin(res))
142 .catch(res => this.restExtractor.handleError(res))
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 console.log('Refreshing token...')
156
157 const refreshToken = this.getRefreshToken()
158
159 // Form url encoded
160 const body = new HttpParams().set('refresh_token', refreshToken)
161 .set('client_id', this.clientId)
162 .set('client_secret', this.clientSecret)
163 .set('response_type', 'code')
164 .set('grant_type', 'refresh_token')
165
166 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
167
168 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
169 .map(res => this.handleRefreshToken(res))
170 .catch(err => {
171 console.error(err)
172 console.log('Cannot refresh token -> logout...')
173 this.logout()
174 this.router.navigate(['/login'])
175
176 return Observable.throw({
177 error: 'You need to reconnect.'
178 })
179 })
180 }
181
182 refreshUserInformation () {
183 const obj = {
184 access_token: this.user.getAccessToken(),
185 refresh_token: null,
186 token_type: this.user.getTokenType(),
187 username: this.user.username
188 }
189
190 this.mergeUserInformation(obj)
191 .subscribe(
192 res => {
193 this.user.displayNSFW = res.displayNSFW
194 this.user.role = res.role
195 this.user.videoChannels = res.videoChannels
196 this.user.account = res.account
197
198 this.user.save()
199
200 this.userInformationLoaded.next(true)
201 }
202 )
203 }
204
205 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
206 // User is not loaded yet, set manually auth header
207 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
208
209 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
210 .map(res => {
211 const newProperties = {
212 id: res.id,
213 role: res.role,
214 displayNSFW: res.displayNSFW,
215 email: res.email,
216 videoQuota: res.videoQuota,
217 account: res.account,
218 videoChannels: res.videoChannels
219 }
220
221 return Object.assign(obj, newProperties)
222 }
223 )
224 }
225
226 private handleLogin (obj: UserLoginWithUserInformation) {
227 const hashUser: UserConstructorHash = {
228 id: obj.id,
229 username: obj.username,
230 role: obj.role,
231 email: obj.email,
232 displayNSFW: obj.displayNSFW,
233 videoQuota: obj.videoQuota,
234 videoChannels: obj.videoChannels,
235 account: obj.account
236 }
237 const hashTokens = {
238 accessToken: obj.access_token,
239 tokenType: obj.token_type,
240 refreshToken: obj.refresh_token
241 }
242
243 this.user = new AuthUser(hashUser, hashTokens)
244 this.user.save()
245
246 this.setStatus(AuthStatus.LoggedIn)
247 this.userInformationLoaded.next(true)
248 }
249
250 private handleRefreshToken (obj: UserRefreshToken) {
251 this.user.refreshTokens(obj.access_token, obj.refresh_token)
252 this.user.save()
253 }
254
255 private setStatus (status: AuthStatus) {
256 this.loginChanged.next(status)
257 }
258 }