]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/core/auth/auth.service.ts
Handle announces in inbox
[github/Chocobozzz/PeerTube.git] / client / src / app / core / auth / auth.service.ts
CommitLineData
df98563e 1import { Injectable } from '@angular/core'
df98563e
C
2import { Router } from '@angular/router'
3import { Observable } from 'rxjs/Observable'
4import { Subject } from 'rxjs/Subject'
d592e0a9 5import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'
2de96f4d
C
6import { ReplaySubject } from 'rxjs/ReplaySubject'
7import 'rxjs/add/operator/do'
df98563e
C
8import 'rxjs/add/operator/map'
9import 'rxjs/add/operator/mergeMap'
10import 'rxjs/add/observable/throw'
11
12import { NotificationsService } from 'angular2-notifications'
13
14import { AuthStatus } from './auth-status.model'
15import { AuthUser } from './auth-user.model'
bcd9f81e
C
16import {
17 OAuthClientLocal,
18 UserRole,
19 UserRefreshToken,
20 VideoChannel,
21 User as UserServerModel
22} from '../../../../../shared'
693b1aba 23// Do not use the barrel (dependency loop)
df98563e 24import { RestExtractor } from '../../shared/rest'
d592e0a9 25import { UserLogin } from '../../../../../shared/models/users/user-login.model'
954605a8 26import { UserConstructorHash } from '../../shared/users/user.model'
d592e0a9
C
27
28interface UserLoginWithUsername extends UserLogin {
29 access_token: string
30 refresh_token: string
31 token_type: string
32 username: string
33}
34
35interface UserLoginWithUserInformation extends UserLogin {
36 access_token: string
37 refresh_token: string
38 token_type: string
39 username: string
40 id: number
41 role: UserRole
42 displayNSFW: boolean
43 email: string
bcd9f81e 44 videoQuota: number
1e1265b3 45 account: {
bcd9f81e
C
46 id: number
47 uuid: string
48 }
49 videoChannels: VideoChannel[]
d592e0a9 50}
b1794c53
C
51
52@Injectable()
53export class AuthService {
0a381679 54 private static BASE_CLIENT_URL = API_URL + '/api/v1/oauth-clients/local'
df98563e 55 private static BASE_TOKEN_URL = API_URL + '/api/v1/users/token'
d592e0a9 56 private static BASE_USER_INFORMATION_URL = API_URL + '/api/v1/users/me'
b1794c53 57
df98563e 58 loginChangedSource: Observable<AuthStatus>
2de96f4d 59 userInformationLoaded = new ReplaySubject<boolean>(1)
b1794c53 60
df98563e
C
61 private clientId: string
62 private clientSecret: string
63 private loginChanged: Subject<AuthStatus>
64 private user: AuthUser = null
ccf6ed16 65
df98563e 66 constructor (
d592e0a9 67 private http: HttpClient,
7ddd02c9 68 private notificationsService: NotificationsService,
14ad0c27
C
69 private restExtractor: RestExtractor,
70 private router: Router
71 ) {
df98563e
C
72 this.loginChanged = new Subject<AuthStatus>()
73 this.loginChangedSource = this.loginChanged.asObservable()
23a5a916 74
bd5c83a8 75 // Return null if there is nothing to load
df98563e 76 this.user = AuthUser.load()
1553e15d 77 }
b1794c53 78
d592e0a9
C
79 loadClientCredentials () {
80 // Fetch the client_id/client_secret
81 // FIXME: save in local storage?
82 this.http.get<OAuthClientLocal>(AuthService.BASE_CLIENT_URL)
83 .catch(res => this.restExtractor.handleError(res))
84 .subscribe(
85 res => {
86 this.clientId = res.client_id
87 this.clientSecret = res.client_secret
88 console.log('Client credentials loaded.')
89 },
90
91 error => {
92 let errorMessage = `Cannot retrieve OAuth Client credentials: ${error.text}. \n`
93 errorMessage += 'Ensure you have correctly configured PeerTube (config/ directory), in particular the "webserver" section.'
94
95 // We put a bigger timeout
96 // This is an important message
97 this.notificationsService.error('Error', errorMessage, { timeOut: 7000 })
98 }
99 )
100 }
101
df98563e
C
102 getRefreshToken () {
103 if (this.user === null) return null
bd5c83a8 104
df98563e 105 return this.user.getRefreshToken()
bd5c83a8
C
106 }
107
df98563e 108 getRequestHeaderValue () {
d592e0a9
C
109 const accessToken = this.getAccessToken()
110
111 if (accessToken === null) return null
112
113 return `${this.getTokenType()} ${accessToken}`
1553e15d
C
114 }
115
df98563e
C
116 getAccessToken () {
117 if (this.user === null) return null
bd5c83a8 118
df98563e 119 return this.user.getAccessToken()
1553e15d
C
120 }
121
df98563e
C
122 getTokenType () {
123 if (this.user === null) return null
bd5c83a8 124
df98563e 125 return this.user.getTokenType()
1553e15d
C
126 }
127
df98563e
C
128 getUser () {
129 return this.user
1553e15d
C
130 }
131
df98563e 132 isLoggedIn () {
d592e0a9 133 return !!this.getAccessToken()
1553e15d
C
134 }
135
df98563e 136 login (username: string, password: string) {
d592e0a9
C
137 // Form url encoded
138 const body = new HttpParams().set('client_id', this.clientId)
139 .set('client_secret', this.clientSecret)
140 .set('response_type', 'code')
141 .set('grant_type', 'password')
142 .set('scope', 'upload')
143 .set('username', username)
144 .set('password', password)
145
146 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
147
148 return this.http.post<UserLogin>(AuthService.BASE_TOKEN_URL, body, { headers })
149 .map(res => Object.assign(res, { username }))
150 .flatMap(res => this.mergeUserInformation(res))
bd5c83a8 151 .map(res => this.handleLogin(res))
d592e0a9 152 .catch(res => this.restExtractor.handleError(res))
4fd8aa32
C
153 }
154
df98563e 155 logout () {
bd5c83a8 156 // TODO: make an HTTP request to revoke the tokens
df98563e 157 this.user = null
724fed29 158
df98563e 159 AuthUser.flush()
e62f6ef7 160
df98563e 161 this.setStatus(AuthStatus.LoggedOut)
bd5c83a8
C
162 }
163
df98563e
C
164 refreshAccessToken () {
165 console.log('Refreshing token...')
bd5c83a8 166
df98563e 167 const refreshToken = this.getRefreshToken()
bd5c83a8 168
d592e0a9
C
169 // Form url encoded
170 const body = new HttpParams().set('refresh_token', refreshToken)
171 .set('client_id', this.clientId)
172 .set('client_secret', this.clientSecret)
173 .set('response_type', 'code')
174 .set('grant_type', 'refresh_token')
bd5c83a8 175
d592e0a9 176 const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
bd5c83a8 177
d592e0a9 178 return this.http.post<UserRefreshToken>(AuthService.BASE_TOKEN_URL, body, { headers })
bd5c83a8 179 .map(res => this.handleRefreshToken(res))
d592e0a9 180 .catch(res => {
14ad0c27 181 // The refresh token is invalid?
127d96b9 182 if (res.status === 400 && res.error.error === 'invalid_grant') {
df98563e
C
183 console.error('Cannot refresh token -> logout...')
184 this.logout()
185 this.router.navigate(['/login'])
14ad0c27
C
186
187 return Observable.throw({
d592e0a9 188 error: 'You need to reconnect.'
df98563e 189 })
14ad0c27
C
190 }
191
df98563e
C
192 return this.restExtractor.handleError(res)
193 })
4fd8aa32
C
194 }
195
d592e0a9 196 refreshUserInformation () {
af5e743b 197 const obj = {
33c4972d
C
198 access_token: this.user.getAccessToken(),
199 refresh_token: null,
200 token_type: this.user.getTokenType(),
201 username: this.user.username
df98563e 202 }
af5e743b 203
d592e0a9 204 this.mergeUserInformation(obj)
2de96f4d
C
205 .do(() => this.userInformationLoaded.next(true))
206 .subscribe(
207 res => {
208 this.user.displayNSFW = res.displayNSFW
209 this.user.role = res.role
210 this.user.videoChannels = res.videoChannels
1e1265b3 211 this.user.account = res.account
2de96f4d
C
212
213 this.user.save()
214 }
215 )
af5e743b
C
216 }
217
d592e0a9
C
218 private mergeUserInformation (obj: UserLoginWithUsername): Observable<UserLoginWithUserInformation> {
219 // User is not loaded yet, set manually auth header
220 const headers = new HttpHeaders().set('Authorization', `${obj.token_type} ${obj.access_token}`)
221
bcd9f81e 222 return this.http.get<UserServerModel>(AuthService.BASE_USER_INFORMATION_URL, { headers })
d592e0a9
C
223 .map(res => {
224 const newProperties = {
bcd9f81e
C
225 id: res.id,
226 role: res.role,
227 displayNSFW: res.displayNSFW,
228 email: res.email,
229 videoQuota: res.videoQuota,
1e1265b3 230 account: res.account,
bcd9f81e 231 videoChannels: res.videoChannels
d592e0a9 232 }
af5e743b 233
d592e0a9
C
234 return Object.assign(obj, newProperties)
235 }
df98563e 236 )
b1794c53
C
237 }
238
d592e0a9 239 private handleLogin (obj: UserLoginWithUserInformation) {
bcd9f81e
C
240 const hashUser: UserConstructorHash = {
241 id: obj.id,
242 username: obj.username,
243 role: obj.role,
244 email: obj.email,
245 displayNSFW: obj.displayNSFW,
246 videoQuota: obj.videoQuota,
247 videoChannels: obj.videoChannels,
1e1265b3 248 account: obj.account
bcd9f81e 249 }
7da18e44 250 const hashTokens = {
df98563e
C
251 accessToken: obj.access_token,
252 tokenType: obj.token_type,
253 refreshToken: obj.refresh_token
254 }
bd5c83a8 255
bcd9f81e 256 this.user = new AuthUser(hashUser, hashTokens)
df98563e 257 this.user.save()
bd5c83a8 258
df98563e 259 this.setStatus(AuthStatus.LoggedIn)
bd5c83a8
C
260 }
261
d592e0a9 262 private handleRefreshToken (obj: UserRefreshToken) {
df98563e
C
263 this.user.refreshTokens(obj.access_token, obj.refresh_token)
264 this.user.save()
bd5c83a8 265 }
629d8d6f 266
df98563e
C
267 private setStatus (status: AuthStatus) {
268 this.loginChanged.next(status)
629d8d6f 269 }
b1794c53 270}