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