Skip to content

Instantly share code, notes, and snippets.

@brandonsueur
Created September 5, 2019 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonsueur/0c92fc0ca2408371a92388e547524852 to your computer and use it in GitHub Desktop.
Save brandonsueur/0c92fc0ca2408371a92388e547524852 to your computer and use it in GitHub Desktop.
auth react
import decode from 'jwt-decode';
export default class AuthService {
constructor(domain) {
this.domain = domain || 'http://localhost:8080'
this.fetch = this.fetch.bind(this)
this.login = this.login.bind(this)
this.getProfile = this.getProfile.bind(this)
}
login(username, password) {
// Get a token
return this.fetch(`${this.domain}/login`, {
method: 'POST',
body: JSON.stringify({
username,
password
})
}).then(res => {
this.setToken(res.token)
return Promise.resolve(res);
})
}
loggedIn() {
// Checks if there is a saved token and it's still valid
const token = this.getToken()
return !!token && !this.isTokenExpired(token) // handwaiving here
}
isTokenExpired(token) {
try {
const decoded = decode(token);
if (decoded.exp < Date.now() / 1000) {
return true;
}
else
return false;
}
catch (err) {
return false;
}
}
setToken(idToken) {
// Saves user token to localStorage
localStorage.setItem('id_token', idToken)
}
getToken() {
// Retrieves the user token from localStorage
return localStorage.getItem('id_token')
}
logout() {
// Clear user token and profile data from localStorage
localStorage.removeItem('id_token');
}
getProfile() {
return decode(this.getToken());
}
fetch(url, options) {
// performs api calls sending the required authentication headers
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
if (this.loggedIn()) {
headers['Authorization'] = 'Bearer ' + this.getToken()
}
return fetch(url, {
headers,
...options
})
.then(this._checkStatus)
.then(response => response.json())
}
_checkStatus(response) {
// raises an error in case response status is not a success
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment