]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Refractor notification service
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
CommitLineData
db400f44 1import { Observable, ReplaySubject, Subject, throwError as observableThrowError } from 'rxjs'
b1d40cff 2import { catchError, map, mergeMap, share, tap } from 'rxjs/operators'
2295ce6c 3import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
df98563e 4import { Injectable } from '@angular/core'
df98563e 5import { Router } from '@angular/router'
f8b2c1b4 6import { Notifier } from '@app/core/notification'
c5911fd3
C
7import { OAuthClientLocal, User as UserServerModel, UserRefreshToken } from '../../../../../shared'
8import { User } from '../../../../../shared/models/users'
2295ce6c 9import { UserLogin } from '../../../../../shared/models/users/user-login.model'
63c4db6d 10import { environment } from '../../../environments/environment'
df98563e 11import { RestExtractor } from '../../shared/rest'
2295ce6c
C
12import { AuthStatus } from './auth-status.model'
13import { AuthUser } from './auth-user.model'
cd4d7a2c 14import { objectToUrlEncoded } from '@app/shared/misc/utils'
a20776fc 15import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
b1d40cff 16import { I18n } from '@ngx-translate/i18n-polyfill'
dae5ca24 17import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2295ce6c 18
d592e0a9
C
19interface UserLoginWithUsername extends UserLogin {
20 access_token: string
21 refresh_token: string
22 token_type: string
23 username: string
24}
25
c5911fd3 26type UserLoginWithUserInformation = UserLoginWithUsername & User
b1794c53
C
27
28@Injectable()
29export class AuthService {
63c4db6d
C
30 private static BASE_CLIENT_URL = environment.apiUrl + '/api/v1/oauth-clients/local'
31 private static BASE_TOKEN_URL = environment.apiUrl + '/api/v1/users/token'
32 private static BASE_USER_INFORMATION_URL = environment.apiUrl + '/api/v1/users/me'
a20776fc
C
33 private static LOCAL_STORAGE_OAUTH_CLIENT_KEYS = {
34 CLIENT_ID: 'client_id',
35 CLIENT_SECRET: 'client_secret'
36 }
b1794c53 37
df98563e 38 loginChangedSource: Observable<AuthStatus>
2de96f4d 39 userInformationLoaded = new ReplaySubject<boolean>(1)
c13e2bf3 40 hotkeys: Hotkey[]
b1794c53 41
a20776fc
C
42 private clientId: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID)
43 private clientSecret: string = peertubeLocalStorage.getItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET)
df98563e
C
44 private loginChanged: Subject<AuthStatus>
45 private user: AuthUser = null
47f8de28 46 private refreshingTokenObservable: Observable<any>
ccf6ed16 47
df98563e 48 constructor (
d592e0a9 49 private http: HttpClient,
f8b2c1b4 50 private notifier: Notifier,
c13e2bf3 51 private hotkeysService: HotkeysService,
14ad0c27 52 private restExtractor: RestExtractor,
b1d40cff
C
53 private router: Router,
54 private i18n: I18n
db400f44 55 ) {
df98563e
C
56 this.loginChanged = new Subject<AuthStatus>()
57 this.loginChangedSource = this.loginChanged.asObservable()
23a5a916 58
bd5c83a8 59 // Return null if there is nothing to load
df98563e 60 this.user = AuthUser.load()
c13e2bf3
RK
61
62 // Set HotKeys
63 this.hotkeys = [
64 new Hotkey('m s', (event: KeyboardEvent): boolean => {
65 this.router.navigate([ '/videos/subscriptions' ])
66 return false
e33f888b 67 }, undefined, this.i18n('Go to my subscriptions')),
c13e2bf3
RK
68 new Hotkey('m v', (event: KeyboardEvent): boolean => {
69 this.router.navigate([ '/my-account/videos' ])
70 return false
e33f888b 71 }, undefined, this.i18n('Go to my videos')),
c13e2bf3
RK
72 new Hotkey('m i', (event: KeyboardEvent): boolean => {
73 this.router.navigate([ '/my-account/video-imports' ])
74 return false
e33f888b 75 }, undefined, this.i18n('Go to my imports')),
c13e2bf3
RK
76 new Hotkey('m c', (event: KeyboardEvent): boolean => {
77 this.router.navigate([ '/my-account/video-channels' ])
78 return false
e33f888b 79 }, undefined, this.i18n('Go to my channels'))
c13e2bf3 80 ]
1553e15d 81 }
b1794c53 82
d592e0a9
C
83 loadClientCredentials () {
84 // Fetch the client_id/client_secret
d592e0a9 85 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
db400f44
C
86 .pipe(catchError(res => this.restExtractor.handleError(res)))
87 .subscribe(
88 res => {
89 this.clientId = res.client_id
90 this.clientSecret = res.client_secret
a20776fc
C
91
92 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_ID, this.clientId)
93 peertubeLocalStorage.setItem(AuthService.LOCAL_STORAGE_OAUTH_CLIENT_KEYS.CLIENT_SECRET, this.clientSecret)
94
db400f44
C
95 console.log('Client credentials loaded.')
96 },
97
98 error => {
99 let errorMessage = error.message
100
101 if (error.status === 403) {
25acef90 102 errorMessage = this.i18n('Cannot retrieve OAuth Client credentials: {{errorText}}.\n', { errorText: error.text })
b1d40cff
C
103 errorMessage += this.i18n(
104 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
105 )
db400f44
C
106 }
107
f8b2c1b4
C
108 // We put a bigger timeout: this is an important message
109 this.notifier.error(errorMessage, this.i18n('Error'), 7000)
db400f44
C
110 }
111 )
d592e0a9
C
112 }
113
df98563e
C
114 getRefreshToken () {
115 if (this.user === null) return null
bd5c83a8 116
df98563e 117 return this.user.getRefreshToken()
bd5c83a8
C
118 }
119
df98563e 120 getRequestHeaderValue () {
d592e0a9
C
121 const accessToken = this.getAccessToken()
122
123 if (accessToken === null) return null
124
125 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
126 }
127
df98563e
C
128 getAccessToken () {
129 if (this.user === null) return null
bd5c83a8 130
df98563e 131 return this.user.getAccessToken()
1553e15d
C
132 }
133
df98563e
C
134 getTokenType () {
135 if (this.user === null) return null
bd5c83a8 136
df98563e 137 return this.user.getTokenType()
1553e15d
C
138 }
139
df98563e
C
140 getUser () {
141 return this.user
1553e15d
C
142 }
143
df98563e 144 isLoggedIn () {
d592e0a9 145 return !!this.getAccessToken()
1553e15d
C
146 }
147
df98563e 148 login (username: string, password: string) {
d592e0a9 149 // Form url encoded
cd4d7a2c
C
150 const body = {
151 client_id: this.clientId,
152 client_secret: this.clientSecret,
153 response_type: 'code',
154 grant_type: 'password',
155 scope: 'upload',
156 username,
157 password
f954b5da 158 }
d592e0a9
C
159
160 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
cd4d7a2c 161 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
db400f44
C
162 .pipe(
163 map(res => Object.assign(res, { username })),
164 mergeMap(res => this.mergeUserInformation(res)),
165 map(res => this.handleLogin(res)),
166 catchError(res => this.restExtractor.handleError(res))
167 )
4fd8aa32
C
168 }
169
df98563e 170 logout () {
bd5c83a8 171 // TODO: make an HTTP request to revoke the tokens
df98563e 172 this.user = null
724fed29 173
df98563e 174 AuthUser.flush()
e62f6ef7 175
df98563e 176 this.setStatus(AuthStatus.LoggedOut)
c13e2bf3
RK
177
178 this.hotkeysService.remove(this.hotkeys)
bd5c83a8
C
179 }
180
df98563e 181 refreshAccessToken () {
47f8de28
C
182 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
183
df98563e 184 console.log('Refreshing token...')
bd5c83a8 185
df98563e 186 const refreshToken = this.getRefreshToken()
bd5c83a8 187
d592e0a9
C
188 // Form url encoded
189 const body = new HttpParams().set('refresh_token', refreshToken)
190 .set('client_id', this.clientId)
191 .set('client_secret', this.clientSecret)
192 .set('response_type', 'code')
193 .set('grant_type', 'refresh_token')
bd5c83a8 194
d592e0a9 195 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 196
47f8de28 197 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
db400f44
C
198 .pipe(
199 map(res => this.handleRefreshToken(res)),
200 tap(() => this.refreshingTokenObservable = null),
201 catchError(err => {
202 this.refreshingTokenObservable = null
203
204 console.error(err)
205 console.log('Cannot refresh token -> logout...')
206 this.logout()
207 this.router.navigate([ '/login' ])
208
209 return observableThrowError({
b1d40cff 210 error: this.i18n('You need to reconnect.')
db400f44 211 })
a20776fc
C
212 }),
213 share()
db400f44 214 )
47f8de28
C
215
216 return this.refreshingTokenObservable
4fd8aa32
C
217 }
218
d592e0a9 219 refreshUserInformation () {
c199c427 220 const obj: UserLoginWithUsername = {
33c4972d
C
221 access_token: this.user.getAccessToken(),
222 refresh_token: null,
223 token_type: this.user.getTokenType(),
224 username: this.user.username
df98563e 225 }
af5e743b 226
d592e0a9 227 this.mergeUserInformation(obj)
db400f44
C
228 .subscribe(
229 res => {
230 this.user.patch(res)
231 this.user.save()
cadb46d8 232
db400f44
C
233 this.userInformationLoaded.next(true)
234 }
235 )
af5e743b
C
236 }
237
d592e0a9
C
238 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
239 // User is not loaded yet, set manually auth header
240 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
241
bcd9f81e 242 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
db400f44 243 .pipe(map(res => Object.assign(obj, res)))
b1794c53
C
244 }
245
d592e0a9 246 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 247 const hashTokens = {
df98563e
C
248 accessToken: obj.access_token,
249 tokenType: obj.token_type,
250 refreshToken: obj.refresh_token
251 }
bd5c83a8 252
ce5496d6 253 this.user = new AuthUser(obj, hashTokens)
df98563e 254 this.user.save()
bd5c83a8 255
df98563e 256 this.setStatus(AuthStatus.LoggedIn)
efc32059 257 this.userInformationLoaded.next(true)
c13e2bf3
RK
258
259 this.hotkeysService.add(this.hotkeys)
bd5c83a8
C
260 }
261
d592e0a9 262 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
263 this.user.refreshTokens(obj.access_token, obj.refresh_token)
264 this.user.save()
bd5c83a8 265 }
629d8d6f 266
df98563e
C
267 private setStatus (status: AuthStatus) {
268 this.loginChanged.next(status)
629d8d6f 269 }
b1794c53 270}