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