-
Notifications
You must be signed in to change notification settings - Fork 6
/
authentication.js
56 lines (50 loc) · 1.68 KB
/
authentication.js
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
import {Component} from "react";
/**
* Class component that can check if locally stored access token is valid and retrieve the stored access token
*/
class Authentication extends Component {
/**
* Checks if access token exists and if so, checks if it is expired or still valid
* @returns {string} "DOES NOT EXIST", "VALID", or "EXPIRED"
*/
getAccessTokenState = () => {
// Retrieves stored access token
let accessToken = window.localStorage.accessToken;
// If access token does not exist, user will have to log in to Sonos account
if (!accessToken) {
return "DOES NOT EXIST";
} else {
// Checks if access token is expired
let curTime = Math.floor(Date.now() / 1000);
accessToken = JSON.parse(accessToken);
if (!this.checkAccessTokenExpired(curTime, accessToken)) {
// User can continue to households page
return "VALID";
} else {
// Access token needs to be refreshed
return "EXPIRED";
}
}
};
/**
* Checks if current access token is valid
* @return {boolean} True if access token is valid, false otherwise
*/
isAccessTokenValid = () => {
return this.getAccessTokenState() === "VALID";
}
/**
* Retrieves and returns access token from local storage
* @returns {JSON} Access token
*/
getAccessToken = () => {
return JSON.parse(window.localStorage.accessToken).token;
};
/**
* Uses current timestamp, access token's timestamp, and access token time until expiration to check if token is expired
*/
checkAccessTokenExpired(curTime, accessToken) {
return curTime - accessToken.tokenTimestamp >= accessToken.expiry;
}
}
export default Authentication;