]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Don't call watching endpoint if history is disabled
[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'
2295ce6c 6import { NotificationsService } from 'angular2-notifications'
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,
7ddd02c9 50 private notificationsService: NotificationsService,
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
108 // We put a bigger timeout
109 // This is an important message
b1d40cff 110 this.notificationsService.error(this.i18n('Error'), errorMessage, { timeOut: 7000 })
db400f44
C
111 }
112 )
d592e0a9
C
113 }
114
df98563e
C
115 getRefreshToken () {
116 if (this.user === null) return null
bd5c83a8 117
df98563e 118 return this.user.getRefreshToken()
bd5c83a8
C
119 }
120
df98563e 121 getRequestHeaderValue () {
d592e0a9
C
122 const accessToken = this.getAccessToken()
123
124 if (accessToken === null) return null
125
126 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
127 }
128
df98563e
C
129 getAccessToken () {
130 if (this.user === null) return null
bd5c83a8 131
df98563e 132 return this.user.getAccessToken()
1553e15d
C
133 }
134
df98563e
C
135 getTokenType () {
136 if (this.user === null) return null
bd5c83a8 137
df98563e 138 return this.user.getTokenType()
1553e15d
C
139 }
140
df98563e
C
141 getUser () {
142 return this.user
1553e15d
C
143 }
144
df98563e 145 isLoggedIn () {
d592e0a9 146 return !!this.getAccessToken()
1553e15d
C
147 }
148
df98563e 149 login (username: string, password: string) {
d592e0a9 150 // Form url encoded
cd4d7a2c
C
151 const body = {
152 client_id: this.clientId,
153 client_secret: this.clientSecret,
154 response_type: 'code',
155 grant_type: 'password',
156 scope: 'upload',
157 username,
158 password
f954b5da 159 }
d592e0a9
C
160
161 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
cd4d7a2c 162 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
db400f44
C
163 .pipe(
164 map(res => Object.assign(res, { username })),
165 mergeMap(res => this.mergeUserInformation(res)),
166 map(res => this.handleLogin(res)),
167 catchError(res => this.restExtractor.handleError(res))
168 )
4fd8aa32
C
169 }
170
df98563e 171 logout () {
bd5c83a8 172 // TODO: make an HTTP request to revoke the tokens
df98563e 173 this.user = null
724fed29 174
df98563e 175 AuthUser.flush()
e62f6ef7 176
df98563e 177 this.setStatus(AuthStatus.LoggedOut)
c13e2bf3
RK
178
179 this.hotkeysService.remove(this.hotkeys)
bd5c83a8
C
180 }
181
df98563e 182 refreshAccessToken () {
47f8de28
C
183 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
184
df98563e 185 console.log('Refreshing token...')
bd5c83a8 186
df98563e 187 const refreshToken = this.getRefreshToken()
bd5c83a8 188
d592e0a9
C
189 // Form url encoded
190 const body = new HttpParams().set('refresh_token', refreshToken)
191 .set('client_id', this.clientId)
192 .set('client_secret', this.clientSecret)
193 .set('response_type', 'code')
194 .set('grant_type', 'refresh_token')
bd5c83a8 195
d592e0a9 196 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 197
47f8de28 198 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
db400f44
C
199 .pipe(
200 map(res => this.handleRefreshToken(res)),
201 tap(() => this.refreshingTokenObservable = null),
202 catchError(err => {
203 this.refreshingTokenObservable = null
204
205 console.error(err)
206 console.log('Cannot refresh token -> logout...')
207 this.logout()
208 this.router.navigate([ '/login' ])
209
210 return observableThrowError({
b1d40cff 211 error: this.i18n('You need to reconnect.')
db400f44 212 })
a20776fc
C
213 }),
214 share()
db400f44 215 )
47f8de28
C
216
217 return this.refreshingTokenObservable
4fd8aa32
C
218 }
219
d592e0a9 220 refreshUserInformation () {
c199c427 221 const obj: UserLoginWithUsername = {
33c4972d
C
222 access_token: this.user.getAccessToken(),
223 refresh_token: null,
224 token_type: this.user.getTokenType(),
225 username: this.user.username
df98563e 226 }
af5e743b 227
d592e0a9 228 this.mergeUserInformation(obj)
db400f44
C
229 .subscribe(
230 res => {
231 this.user.patch(res)
232 this.user.save()
cadb46d8 233
db400f44
C
234 this.userInformationLoaded.next(true)
235 }
236 )
af5e743b
C
237 }
238
d592e0a9
C
239 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
240 // User is not loaded yet, set manually auth header
241 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
242
bcd9f81e 243 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
db400f44 244 .pipe(map(res => Object.assign(obj, res)))
b1794c53
C
245 }
246
d592e0a9 247 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 248 const hashTokens = {
df98563e
C
249 accessToken: obj.access_token,
250 tokenType: obj.token_type,
251 refreshToken: obj.refresh_token
252 }
bd5c83a8 253
ce5496d6 254 this.user = new AuthUser(obj, hashTokens)
df98563e 255 this.user.save()
bd5c83a8 256
df98563e 257 this.setStatus(AuthStatus.LoggedIn)
efc32059 258 this.userInformationLoaded.next(true)
c13e2bf3
RK
259
260 this.hotkeysService.add(this.hotkeys)
bd5c83a8
C
261 }
262
d592e0a9 263 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
264 this.user.refreshTokens(obj.access_token, obj.refresh_token)
265 this.user.save()
bd5c83a8 266 }
629d8d6f 267
df98563e
C
268 private setStatus (status: AuthStatus) {
269 this.loginChanged.next(status)
629d8d6f 270 }
b1794c53 271}