]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Begin support for external auths
[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'
9a39392a 6import { Notifier } from '@app/core/notification/notifier.service'
29128b2f 7import { OAuthClientLocal, MyUser as UserServerModel, UserRefreshToken } from '../../../../../shared'
c5911fd3 8import { User } from '../../../../../shared/models/users'
2295ce6c 9import { UserLogin } from '../../../../../shared/models/users/user-login.model'
63c4db6d 10import { environment } from '../../../environments/environment'
9a39392a 11import { RestExtractor } from '../../shared/rest/rest-extractor.service'
2295ce6c
C
12import { AuthStatus } from './auth-status.model'
13import { AuthUser } from './auth-user.model'
cd4d7a2c 14import { objectToUrlEncoded } from '@app/shared/misc/utils'
88a7f93f 15import { peertubeLocalStorage } from '@app/shared/misc/peertube-web-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
4a8d113b 148 login (username: string, password: string, token?: 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',
50b4dcce 156 username,
cd4d7a2c 157 password
f954b5da 158 }
d592e0a9 159
4a8d113b
C
160 if (token) Object.assign(body, { externalAuthToken: token })
161
d592e0a9 162 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
cd4d7a2c 163 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, objectToUrlEncoded(body), { headers })
db400f44
C
164 .pipe(
165 map(res => Object.assign(res, { username })),
166 mergeMap(res => this.mergeUserInformation(res)),
167 map(res => this.handleLogin(res)),
168 catchError(res => this.restExtractor.handleError(res))
169 )
4fd8aa32
C
170 }
171
df98563e 172 logout () {
bd5c83a8 173 // TODO: make an HTTP request to revoke the tokens
df98563e 174 this.user = null
724fed29 175
df98563e 176 AuthUser.flush()
e62f6ef7 177
df98563e 178 this.setStatus(AuthStatus.LoggedOut)
c13e2bf3
RK
179
180 this.hotkeysService.remove(this.hotkeys)
bd5c83a8
C
181 }
182
df98563e 183 refreshAccessToken () {
47f8de28
C
184 if (this.refreshingTokenObservable) return this.refreshingTokenObservable
185
df98563e 186 console.log('Refreshing token...')
bd5c83a8 187
df98563e 188 const refreshToken = this.getRefreshToken()
bd5c83a8 189
d592e0a9
C
190 // Form url encoded
191 const body = new HttpParams().set('refresh_token', refreshToken)
192 .set('client_id', this.clientId)
193 .set('client_secret', this.clientSecret)
194 .set('response_type', 'code')
195 .set('grant_type', 'refresh_token')
bd5c83a8 196
d592e0a9 197 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 198
47f8de28 199 this.refreshingTokenObservable = this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
db400f44
C
200 .pipe(
201 map(res => this.handleRefreshToken(res)),
202 tap(() => this.refreshingTokenObservable = null),
203 catchError(err => {
204 this.refreshingTokenObservable = null
205
206 console.error(err)
207 console.log('Cannot refresh token -> logout...')
208 this.logout()
209 this.router.navigate([ '/login' ])
210
211 return observableThrowError({
b1d40cff 212 error: this.i18n('You need to reconnect.')
db400f44 213 })
a20776fc
C
214 }),
215 share()
db400f44 216 )
47f8de28
C
217
218 return this.refreshingTokenObservable
4fd8aa32
C
219 }
220
d592e0a9 221 refreshUserInformation () {
c199c427 222 const obj: UserLoginWithUsername = {
33c4972d
C
223 access_token: this.user.getAccessToken(),
224 refresh_token: null,
225 token_type: this.user.getTokenType(),
226 username: this.user.username
df98563e 227 }
af5e743b 228
d592e0a9 229 this.mergeUserInformation(obj)
db400f44
C
230 .subscribe(
231 res => {
232 this.user.patch(res)
233 this.user.save()
cadb46d8 234
db400f44
C
235 this.userInformationLoaded.next(true)
236 }
237 )
af5e743b
C
238 }
239
d592e0a9
C
240 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
241 // User is not loaded yet, set manually auth header
242 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
243
bcd9f81e 244 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
db400f44 245 .pipe(map(res => Object.assign(obj, res)))
b1794c53
C
246 }
247
d592e0a9 248 private handleLogin (obj: UserLoginWithUserInformation) {
7da18e44 249 const hashTokens = {
df98563e
C
250 accessToken: obj.access_token,
251 tokenType: obj.token_type,
252 refreshToken: obj.refresh_token
253 }
bd5c83a8 254
ce5496d6 255 this.user = new AuthUser(obj, hashTokens)
df98563e 256 this.user.save()
bd5c83a8 257
df98563e 258 this.setStatus(AuthStatus.LoggedIn)
efc32059 259 this.userInformationLoaded.next(true)
c13e2bf3
RK
260
261 this.hotkeysService.add(this.hotkeys)
bd5c83a8
C
262 }
263
d592e0a9 264 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
265 this.user.refreshTokens(obj.access_token, obj.refresh_token)
266 this.user.save()
bd5c83a8 267 }
629d8d6f 268
df98563e
C
269 private setStatus (status: AuthStatus) {
270 this.loginChanged.next(status)
629d8d6f 271 }
b1794c53 272}