]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/auth/auth.service.ts
Client: Auth services cleanup
[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/users/client';
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
112 refreshAccessToken() {
113 console.log('Refreshing token...');
114
115 const refreshToken = this.getRefreshToken();
116
117 let body = new URLSearchParams();
118 body.set('refresh_token', refreshToken);
119 body.set('client_id', this.clientId);
120 body.set('client_secret', this.clientSecret);
121 body.set('response_type', 'code');
122 body.set('grant_type', 'refresh_token');
123
124 let headers = new Headers();
125 headers.append('Content-Type', 'application/x-www-form-urlencoded');
126
127 let options = {
128 headers: headers
129 };
130
131 return this.http.post(AuthService.BASE_TOKEN_URL, body.toString(), options)
132 .map(res => res.json())
133 .map(res => this.handleRefreshToken(res))
134 .catch(this.handleError);
135 }
136
137 private setStatus(status: AuthStatus) {
138 this.loginChanged.next(status);
139 }
140
141 private handleLogin (obj: any) {
142 const username = obj.username;
143 const hash_tokens = {
144 access_token: obj.access_token,
145 token_type: obj.token_type,
146 refresh_token: obj.refresh_token
147 };
148
149 this.user = new User(username, hash_tokens);
150 this.user.save();
151
152 this.setStatus(AuthStatus.LoggedIn);
153 }
154
155 private handleError (error: Response) {
156 console.error(error);
157 return Observable.throw(error.json() || { error: 'Server error' });
158 }
159
160 private handleRefreshToken (obj: any) {
161 this.user.refreshTokens(obj.access_token, obj.refresh_token);
162 this.user.save();
163 }
164 }