Skip to content

Instantly share code, notes, and snippets.

@kianaditya
Last active April 1, 2020 07:19
Show Gist options
  • Save kianaditya/aac04f5676ea642338116eca636160ae to your computer and use it in GitHub Desktop.
Save kianaditya/aac04f5676ea642338116eca636160ae to your computer and use it in GitHub Desktop.
Credentials related functions
import decode from "jwt-decode";
var querystring = require("querystring");
const axios = require("axios");
export default class Credentials {
getCredentials = () => {
const token = this.getToken();
if (!!token && !this.isTokenExpired(token)) {
return token;
} else {
return this.setToken();
}
};
// Makes a token call to API and fetches new token and saves in localstorage
setToken = async () => {
const body = {
grant_type: "client_credentials",
scope: <options>,
client_id: process.env.REACT_APP_CLIENT_ID,
client_secret: process.env.REACT_APP_CLIENT_SECRET,
};
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
const response = await axios.post(
`${process.env.REACT_APP_API_BASE_URL}/auth/oauth/token`, // Whichever endpoint that handles credentials
querystring.stringify(body),
config
);
localStorage.setItem("auth_token", response.data.access_token);
return response.data.access_token;
};
getToken = () => {
return localStorage.getItem("auth_token"); // Fetches token from localstorage
};
//checks for token expiry
isTokenExpired = token => {
try {
const decoded = decode(token);
console.log("decoded", decoded);
if (decoded.exp < Date.now() / 1000) {
// Checking if token is expired.
return true;
} else return false;
} catch (err) {
return false;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment