]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Upgrade Angular first step
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
CommitLineData
2295ce6c 1import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
df98563e 2import { Injectable } from '@angular/core'
df98563e 3import { Router } from '@angular/router'
2295ce6c
C
4import { NotificationsService } from 'angular2-notifications'
5import 'rxjs/add/observable/throw'
2de96f4d 6import 'rxjs/add/operator/do'
df98563e
C
7import 'rxjs/add/operator/map'
8import 'rxjs/add/operator/mergeMap'
2295ce6c
C
9import { Observable } from 'rxjs/Observable'
10import { ReplaySubject } from 'rxjs/ReplaySubject'
11import { Subject } from 'rxjs/Subject'
c5911fd3
C
12import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
13import { User } from '../../../../../shared/models/users'
2295ce6c 14import { UserLogin } from '../../../../../shared/models/users/user-login.model'
63c4db6d 15import { environment } from '../../../environments/environment'
df98563e 16import { RestExtractor } from '../../shared/rest'
2295ce6c
C
17import { AuthStatus } from './auth-status.model'
18import { AuthUser } from './auth-user.model'
19
d592e0a9
C
20interface UserLoginWithUsername extends UserLogin {
21 access_token: string
22 refresh_token: string
23 token_type: string
24 username: string
25}
26
c5911fd3 27type UserLoginWithUserInformation = UserLoginWithUsername & User
b1794c53
C
28
29@Injectable()
30export class AuthService {
63c4db6d
C
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'
b1794c53 34
df98563e 35 loginChangedSource: Observable<AuthStatus>
2de96f4d 36 userInformationLoaded = new ReplaySubject<boolean>(1)
b1794c53 37
df98563e
C
38 private clientId: string
39 private clientSecret: string
40 private loginChanged: Subject<AuthStatus>
41 private user: AuthUser = null
47f8de28 42 private refreshingTokenObservable: Observable<any>
ccf6ed16 43
df98563e 44 constructor (
d592e0a9 45 private http: HttpClient,
7ddd02c9 46 private notificationsService: NotificationsService,
14ad0c27
C
47 private restExtractor: RestExtractor,
48 private router: Router
49 ) {
df98563e
C
50 this.loginChanged = new Subject<AuthStatus>()
51 this.loginChangedSource = this.loginChanged.asObservable()
23a5a916 52
bd5c83a8 53 // Return null if there is nothing to load
df98563e 54 this.user = AuthUser.load()
1553e15d 55 }
b1794c53 56
d592e0a9
C
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 => {
490b595a
C
70 let errorMessage = error.message
71
72 if (error.status === 403) {
73 errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
09becad8
C
74 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), ' +
75 'in particular the "webserver" section.'
490b595a 76 }
d592e0a9
C
77
78 // We put a bigger timeout
79 // This is an important message
80 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
81 }
82 )
83 }
84
df98563e
C
85 getRefreshToken () {
86 if (this.user === null) return null
bd5c83a8 87
df98563e 88 return this.user.getRefreshToken()
bd5c83a8
C
89 }
90
df98563e 91 getRequestHeaderValue () {
d592e0a9
C
92 const accessToken = this.getAccessToken()
93
94 if (accessToken === null) return null
95
96 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
97 }
98
df98563e
C
99 getAccessToken () {
100 if (this.user === null) return null
bd5c83a8 101
df98563e 102 return this.user.getAccessToken()
1553e15d
C
103 }
104
df98563e
C
105 getTokenType () {
106 if (this.user === null) return null
bd5c83a8 107
df98563e 108 return this.user.getTokenType()
1553e15d
C
109 }
110
df98563e
C
111 getUser () {
112 return this.user
1553e15d
C
113 }
114
df98563e 115 isLoggedIn () {
d592e0a9 116 return !!this.getAccessToken()
1553e15d
C
117 }
118
df98563e 119 login (username: string, password: string) {
d592e0a9 120 // Form url encoded
bf9ae5ce
C
121 const body = new URLSearchParams()
122 body.set('client_id', this.clientId)
123 body.set('client_secret', this.clientSecret)
124 body.set('response_type', 'code')
125 body.set('grant_type', 'password')
126 body.set('scope', 'upload')
127 body.set('username', username)
128 body.set('password', password)
d592e0a9
C
129
130 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bf9ae5ce 131 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body.toString(), { headers })
d592e0a9
C
132 .map(res => Object.assign(res, { username }))
133 .flatMap(res => this.mergeUserInformation(res))
bd5c83a8 134 .map(res => this.handleLogin(res))
d592e0a9 135 .catch(res => this.restExtractor.handleError(res))
4fd8aa32
C
136 }
137
df98563e 138 logout () {
bd5c83a8 139 // TODO: make an HTTP request to revoke the tokens
df98563e 140 this.user = null
724fed29 141
df98563e 142 AuthUser.flush()
e62f6ef7 143
df98563e 144 this.setStatus(AuthStatus.LoggedOut)
bd5c83a8
C
145 }
146
df98563e 147 refreshAccessToken () {
47f8de28
C
148 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
149
df98563e 150 console.log('Refreshing token...')
bd5c83a8 151
df98563e 152 const refreshToken = this.getRefreshToken()
bd5c83a8 153
d592e0a9
C
154 // Form url encoded
155 const body = new HttpParams().set('refresh_token', refreshToken)
156 .set('client_id', this.clientId)
157 .set('client_secret', this.clientSecret)
158 .set('response_type', 'code')
159 .set('grant_type', 'refresh_token')
bd5c83a8 160
d592e0a9 161 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 162
47f8de28
C
163 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
164 .map(res => this.handleRefreshToken(res))
165 .do(() => this.refreshingTokenObservable = null)
166 .catch(err => {
167 this.refreshingTokenObservable = null
168
169 console.error(err)
170 console.log('Cannot refresh token -> logout...')
171 this.logout()
172 this.router.navigate([ '/login' ])
173
174 return Observable.throw({
175 error: 'You need to reconnect.'
176 })
177 })
178
179 return this.refreshingTokenObservable
4fd8aa32
C
180 }
181
d592e0a9 182 refreshUserInformation () {
af5e743b 183 const obj = {
33c4972d
C
184 access_token: this.user.getAccessToken(),
185 refresh_token: null,
186 token_type: this.user.getTokenType(),
187 username: this.user.username
df98563e 188 }
af5e743b 189
d592e0a9 190 this.mergeUserInformation(obj)
2de96f4d
C
191 .subscribe(
192 res => {
ce5496d6 193 this.user.patch(res)
2de96f4d 194 this.user.save()
cadb46d8
C
195
196 this.userInformationLoaded.next(true)
2de96f4d
C
197 }
198 )
af5e743b
C
199 }
200
d592e0a9
C
201 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
202 // User is not loaded yet, set manually auth header
203 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
204
bcd9f81e 205 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
c5911fd3 206 .map(res => Object.assign(obj, res))
b1794c53
C
207 }
208
d592e0a9 209 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 210 const hashTokens = {
df98563e
C
211 accessToken: obj.access_token,
212 tokenType: obj.token_type,
213 refreshToken: obj.refresh_token
214 }
bd5c83a8 215
ce5496d6 216 this.user = new AuthUser(obj, hashTokens)
df98563e 217 this.user.save()
bd5c83a8 218
df98563e 219 this.setStatus(AuthStatus.LoggedIn)
efc32059 220 this.userInformationLoaded.next(true)
bd5c83a8
C
221 }
222
d592e0a9 223 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
224 this.user.refreshTokens(obj.access_token, obj.refresh_token)
225 this.user.save()
bd5c83a8 226 }
629d8d6f 227
df98563e
C
228 private setStatus (status: AuthStatus) {
229 this.loginChanged.next(status)
629d8d6f 230 }
b1794c53 231}