]> git.r.bdr.sh - rbdr/dasein/blame - app/services/auth.js
Merge branch 'release/1.0.0'
[rbdr/dasein] / app / services / auth.js
CommitLineData
a6ccda0f
RBR
1import Axios from 'axios';
2
3const internals = {};
4
5/* global localStorage */
6
7internals.kInitiateLoginRoute = '/api/auth/login';
8internals.kHandleCallbackRoute = '/api/auth/callback';
9
10export default internals.AuthService = class AuthService {
11
12 constructor() {
13
14 this.authenticated = false;
15
16 // Bootstrap from local storage.
17 if (localStorage.hasOwnProperty('user') && localStorage.hasOwnProperty('token')
18 && localStorage.hasOwnProperty('expiresAt')) {
19
20 if (parseInt(localStorage.getItem('expiresAt')) > Date.now()) {
21 this.expiresAt = localStorage.getItem('expiresAt');
22 this.user = JSON.parse(localStorage.getItem('user'));
23 this.token = localStorage.getItem('token');
24 this.authenticated = true;
25 }
26 }
27 }
28
29 // Initiates the login process. Resolves to an object that contains the URL
30 // to redirect to to continue processing.
31 initiateLogin() {
32
33 return Axios.get(internals.kInitiateLoginRoute).then((response) => {
34
35 return response.data;
36 });
37 }
38
39 // Posts the oAuthToken and verifier to the API to get back a user object
40 // and a signed JWT
41 getUserObject(oAuthToken, oAuthVerifier) {
42
43 return Axios.post(internals.kHandleCallbackRoute, {
44 oAuthToken,
45 oAuthVerifier
46 }).then((response) => {
47
48 return response.data;
49 });
50 }
51
52 // Logs in the user by setting the user and token
53 login(user, token, expiresAt) {
54
55 localStorage.setItem('user', JSON.stringify(user));
56 localStorage.setItem('token', token);
57 localStorage.setItem('expiresAt', expiresAt);
58 this.user = user;
59 this.token = token;
60 this.expiresAt = expiresAt;
61 this.authenticated = true;
62 }
63
64 // Logs a user out by removing the user and token
65 logout() {
66
67 localStorage.removeItem('user');
68 localStorage.removeItem('token');
69 localStorage.removeItem('expiresAt');
70 delete this.user;
71 delete this.token;
72 delete this.expiresAt;
73 this.authenticated = false;
74 }
75};