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