]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/app/users/shared/auth.service.ts
b1da94436396670e74471993dac65738fbcd147d
[github/Chocobozzz/PeerTube.git] / client / app / users / shared / auth.service.ts
1 import { Injectable } from '@angular/core';
2 import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http';
3 import { Observable, Subject } from 'rxjs/Rx';
4
5 import { AuthStatus } from './auth-status.model';
6 import { User } from './user.model';
7
8 @Injectable()
9 export class AuthService {
10 private static BASE_LOGIN_URL = '/api/v1/users/token';
11 private static BASE_CLIENT_URL = '/api/v1/users/client';
12
13 loginChangedSource: Observable<AuthStatus>;
14
15 private loginChanged: Subject<AuthStatus>;
16 private clientId: string;
17 private clientSecret: string;
18
19 constructor(private http: Http) {
20 this.loginChanged = new Subject<AuthStatus>();
21 this.loginChangedSource = this.loginChanged.asObservable();
22
23 // Fetch the client_id/client_secret
24 // FIXME: save in local storage?
25 this.http.get(AuthService.BASE_CLIENT_URL)
26 .map(res => res.json())
27 .catch(this.handleError)
28 .subscribe(
29 result => {
30 this.clientId = result.client_id;
31 this.clientSecret = result.client_secret;
32 console.log('Client credentials loaded.');
33 },
34 error => {
35 alert(error);
36 }
37 );
38 }
39
40 login(username: string, password: string) {
41 let body = new URLSearchParams();
42 body.set('client_id', this.clientId);
43 body.set('client_secret', this.clientSecret);
44 body.set('response_type', 'code');
45 body.set('grant_type', 'password');
46 body.set('scope', 'upload');
47 body.set('username', username);
48 body.set('password', password);
49
50 let headers = new Headers();
51 headers.append('Content-Type', 'application/x-www-form-urlencoded');
52
53 let options = {
54 headers: headers
55 };
56
57 return this.http.post(AuthService.BASE_LOGIN_URL, body.toString(), options)
58 .map(res => res.json())
59 .catch(this.handleError);
60 }
61
62 logout() {
63 // TODO make HTTP request
64 }
65
66 getRequestHeader() {
67 return new Headers({ 'Authorization': `${this.getTokenType()} ${this.getToken()}` });
68 }
69
70 getAuthRequestOptions(): RequestOptions {
71 return new RequestOptions({ headers: this.getRequestHeader() });
72 }
73
74 getToken() {
75 return localStorage.getItem('access_token');
76 }
77
78 getTokenType() {
79 return localStorage.getItem('token_type');
80 }
81
82 getUser(): User {
83 if (this.isLoggedIn() === false) {
84 return null;
85 }
86
87 const user = User.load();
88
89 return user;
90 }
91
92 isLoggedIn() {
93 if (this.getToken()) {
94 return true;
95 } else {
96 return false;
97 }
98 }
99
100 setStatus(status: AuthStatus) {
101 this.loginChanged.next(status);
102 }
103
104 private handleError (error: Response) {
105 console.error(error);
106 return Observable.throw(error.json() || { error: 'Server error' });
107 }
108 }