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