]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/auth/auth.service.ts
8eea0c4bfed4f812c9cc97e85618243c0e06d610
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / auth / auth.service.ts
1 import { Injectable } from '@angular/core';
2 import { Headers, Http, Response, URLSearchParams } from '@angular/http';
3 import { Observable } from 'rxjs/Observable';
4 import { Subject } from 'rxjs/Subject';
5
6 import { AuthStatus } from './auth-status.model';
7 import { AuthUser } from './auth-user.model';
8
9 @Injectable()
10 export class AuthService {
11 private static BASE_CLIENT_URL = '/api/v1/clients/local';
12 private static BASE_TOKEN_URL = '/api/v1/users/token';
13 private static BASE_USER_INFORMATIONS_URL = '/api/v1/users/me';
14
15 loginChangedSource: Observable<AuthStatus>;
16
17 private clientId: string;
18 private clientSecret: string;
19 private loginChanged: Subject<AuthStatus>;
20 private user: AuthUser = null;
21
22 constructor(private http: Http) {
23 this.loginChanged = new Subject<AuthStatus>();
24 this.loginChangedSource = this.loginChanged.asObservable();
25
26 // Fetch the client_id/client_secret
27 // FIXME: save in local storage?
28 this.http.get(AuthService.BASE_CLIENT_URL)
29 .map(res => res.json())
30 .catch(this.handleError)
31 .subscribe(
32 result => {
33 this.clientId = result.client_id;
34 this.clientSecret = result.client_secret;
35 console.log('Client credentials loaded.');
36 },
37 error => {
38 alert(error);
39 }
40 );
41
42 // Return null if there is nothing to load
43 this.user = AuthUser.load();
44 }
45
46 getRefreshToken() {
47 if (this.user === null) return null;
48
49 return this.user.getRefreshToken();
50 }
51
52 getRequestHeaderValue() {
53 return `${this.getTokenType()} ${this.getAccessToken()}`;
54 }
55
56 getAccessToken() {
57 if (this.user === null) return null;
58
59 return this.user.getAccessToken();
60 }
61
62 getTokenType() {
63 if (this.user === null) return null;
64
65 return this.user.getTokenType();
66 }
67
68 getUser(): AuthUser {
69 return this.user;
70 }
71
72 isAdmin() {
73 if (this.user === null) return false;
74
75 return this.user.isAdmin();
76 }
77
78 isLoggedIn() {
79 if (this.getAccessToken()) {
80 return true;
81 } else {
82 return false;
83 }
84 }
85
86 login(username: string, password: string) {
87 let body = new URLSearchParams();
88 body.set('client_id', this.clientId);
89 body.set('client_secret', this.clientSecret);
90 body.set('response_type', 'code');
91 body.set('grant_type', 'password');
92 body.set('scope', 'upload');
93 body.set('username', username);
94 body.set('password', password);
95
96 let headers = new Headers();
97 headers.append('Content-Type', 'application/x-www-form-urlencoded');
98
99 let options = {
100 headers: headers
101 };
102
103 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
104 .map(res => res.json())
105 .map(res => {
106 res.username = username;
107 return res;
108 })
109 .flatMap(res => this.fetchUserInformations(res))
110 .map(res => this.handleLogin(res))
111 .catch(this.handleError);
112 }
113
114 logout() {
115 // TODO: make an HTTP request to revoke the tokens
116 this.user = null;
117 AuthUser.flush();
118
119 this.setStatus(AuthStatus.LoggedOut);
120 }
121
122 refreshAccessToken() {
123 console.log('Refreshing token...');
124
125 const refreshToken = this.getRefreshToken();
126
127 let body = new URLSearchParams();
128 body.set('refresh_token', refreshToken);
129 body.set('client_id', this.clientId);
130 body.set('client_secret', this.clientSecret);
131 body.set('response_type', 'code');
132 body.set('grant_type', 'refresh_token');
133
134 let headers = new Headers();
135 headers.append('Content-Type', 'application/x-www-form-urlencoded');
136
137 let options = {
138 headers: headers
139 };
140
141 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
142 .map(res => res.json())
143 .map(res => this.handleRefreshToken(res))
144 .catch(this.handleError);
145 }
146
147 private fetchUserInformations (obj: any) {
148 // Do not call authHttp here to avoid circular dependencies headaches
149
150 const headers = new Headers();
151 headers.set('Authorization', `Bearer ${obj.access_token}`);
152
153 return this.http.get(AuthService.BASE_USER_INFORMATIONS_URL, { headers })
154 .map(res => res.json())
155 .map(res => {
156 obj.id = res.id;
157 obj.role = res.role;
158 return obj;
159 }
160 );
161 }
162
163 private handleError (error: Response) {
164 console.error(error);
165 return Observable.throw(error.json() || { error: 'Server error' });
166 }
167
168 private handleLogin (obj: any) {
169 const id = obj.id;
170 const username = obj.username;
171 const role = obj.role;
172 const hashTokens = {
173 access_token: obj.access_token,
174 token_type: obj.token_type,
175 refresh_token: obj.refresh_token
176 };
177
178 this.user = new AuthUser({ id, username, role }, hashTokens);
179 this.user.save();
180
181 this.setStatus(AuthStatus.LoggedIn);
182 }
183
184 private handleRefreshToken (obj: any) {
185 this.user.refreshTokens(obj.access_token, obj.refresh_token);
186 this.user.save();
187 }
188
189 private setStatus(status: AuthStatus) {
190 this.loginChanged.next(status);
191 }
192
193 }