aboutsummaryrefslogtreecommitdiff
path: root/app/services/auth.js
blob: 32db32189f00e7cdce5e6456b5caf6ea053b93fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import Axios from 'axios';

const internals = {};

/* global localStorage */

internals.kInitiateLoginRoute = '/api/auth/login';
internals.kHandleCallbackRoute = '/api/auth/callback';

export default internals.AuthService = class AuthService {

  constructor() {

    this.authenticated = false;

    // Bootstrap from local storage.
    if (localStorage.hasOwnProperty('user') && localStorage.hasOwnProperty('token')
        && localStorage.hasOwnProperty('expiresAt')) {

      if (parseInt(localStorage.getItem('expiresAt')) > Date.now()) {
        this.expiresAt = localStorage.getItem('expiresAt');
        this.user = JSON.parse(localStorage.getItem('user'));
        this.token = localStorage.getItem('token');
        this.authenticated = true;
      }
    }
  }

  // Initiates the login process. Resolves to an object that contains the URL
  // to redirect to to continue processing.
  initiateLogin() {

    return Axios.get(internals.kInitiateLoginRoute).then((response) => {

      return response.data;
    });
  }

  // Posts the oAuthToken and verifier to the API to get back a user object
  // and a signed JWT
  getUserObject(oAuthToken, oAuthVerifier) {

    return Axios.post(internals.kHandleCallbackRoute, {
      oAuthToken,
      oAuthVerifier
    }).then((response) => {

      return response.data;
    });
  }

  // Logs in the user by setting the user and token
  login(user, token, expiresAt) {

    localStorage.setItem('user', JSON.stringify(user));
    localStorage.setItem('token', token);
    localStorage.setItem('expiresAt', expiresAt);
    this.user = user;
    this.token = token;
    this.expiresAt = expiresAt;
    this.authenticated = true;
  }

  // Logs a user out by removing the user and token
  logout() {

    localStorage.removeItem('user');
    localStorage.removeItem('token');
    localStorage.removeItem('expiresAt');
    delete this.user;
    delete this.token;
    delete this.expiresAt;
    this.authenticated = false;
  }
};