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