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