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