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