]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/auth/auth.service.ts
6a5b19ffeed4ddd5766388ba26f8f5f5c8efc2e7
[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 { User } from './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
14 loginChangedSource: Observable<AuthStatus>;
15
16 private clientId: string;
17 private clientSecret: string;
18 private loginChanged: Subject<AuthStatus>;
19 private user: User = null;
20
21 constructor(private http: Http) {
22 this.loginChanged = new Subject<AuthStatus>();
23 this.loginChangedSource = this.loginChanged.asObservable();
24
25 // Fetch the client_id/client_secret
26 // FIXME: save in local storage?
27 this.http.get(AuthService.BASE_CLIENT_URL)
28 .map(res => res.json())
29 .catch(this.handleError)
30 .subscribe(
31 result => {
32 this.clientId = result.client_id;
33 this.clientSecret = result.client_secret;
34 console.log('Client credentials loaded.');
35 },
36 error => {
37 alert(error);
38 }
39 );
40
41 // Return null if there is nothing to load
42 this.user = User.load();
43 }
44
45 getRefreshToken() {
46 if (this.user === null) return null;
47
48 return this.user.getRefreshToken();
49 }
50
51 getRequestHeaderValue() {
52 return `${this.getTokenType()} ${this.getAccessToken()}`;
53 }
54
55 getAccessToken() {
56 if (this.user === null) return null;
57
58 return this.user.getAccessToken();
59 }
60
61 getTokenType() {
62 if (this.user === null) return null;
63
64 return this.user.getTokenType();
65 }
66
67 getUser(): User {
68 return this.user;
69 }
70
71 isLoggedIn() {
72 if (this.getAccessToken()) {
73 return true;
74 } else {
75 return false;
76 }
77 }
78
79 login(username: string, password: string) {
80 let body = new URLSearchParams();
81 body.set('client_id', this.clientId);
82 body.set('client_secret', this.clientSecret);
83 body.set('response_type', 'code');
84 body.set('grant_type', 'password');
85 body.set('scope', 'upload');
86 body.set('username', username);
87 body.set('password', password);
88
89 let headers = new Headers();
90 headers.append('Content-Type', 'application/x-www-form-urlencoded');
91
92 let options = {
93 headers: headers
94 };
95
96 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
97 .map(res => res.json())
98 .map(res => {
99 res.username = username;
100 return res;
101 })
102 .map(res => this.handleLogin(res))
103 .catch(this.handleError);
104 }
105
106 logout() {
107 // TODO: make an HTTP request to revoke the tokens
108 this.user = null;
109 User.flush();
110
111 this.setStatus(AuthStatus.LoggedOut);
112 }
113
114 refreshAccessToken() {
115 console.log('Refreshing token...');
116
117 const refreshToken = this.getRefreshToken();
118
119 let body = new URLSearchParams();
120 body.set('refresh_token', refreshToken);
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', 'refresh_token');
125
126 let headers = new Headers();
127 headers.append('Content-Type', 'application/x-www-form-urlencoded');
128
129 let options = {
130 headers: headers
131 };
132
133 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
134 .map(res => res.json())
135 .map(res => this.handleRefreshToken(res))
136 .catch(this.handleError);
137 }
138
139 private setStatus(status: AuthStatus) {
140 this.loginChanged.next(status);
141 }
142
143 private handleLogin (obj: any) {
144 const username = obj.username;
145 const hash_tokens = {
146 access_token: obj.access_token,
147 token_type: obj.token_type,
148 refresh_token: obj.refresh_token
149 };
150
151 this.user = new User(username, hash_tokens);
152 this.user.save();
153
154 this.setStatus(AuthStatus.LoggedIn);
155 }
156
157 private handleError (error: Response) {
158 console.error(error);
159 return Observable.throw(error.json() || { error: 'Server error' });
160 }
161
162 private handleRefreshToken (obj: any) {
163 this.user.refreshTokens(obj.access_token, obj.refresh_token);
164 this.user.save();
165 }
166 }