Skip to content

Instantly share code, notes, and snippets.

@lucasdu4rte
Created August 8, 2018 15:37
Show Gist options
  • Save lucasdu4rte/22a251d53dd77f1ececae486732f552d to your computer and use it in GitHub Desktop.
Save lucasdu4rte/22a251d53dd77f1ececae486732f552d to your computer and use it in GitHub Desktop.
AuthService
import store from 'store'
import decode from 'jwt-decode'
import axiosClient from '@/helpers/axiosClient.js'
export default class AuthService {
// Initializing important variables
constructor() {
this.fetch = this.fetch.bind(this)
this.login = this.login.bind(this)
this.getTokenData = this.getTokenData.bind(this)
this.getProfile = this.getProfile.bind(this)
if (this.loggedIn()) {
axiosClient.defaults.headers.common[
'Authorization'
] = `Bearer ${this.getToken()}`
}
}
login(email, password) {
// Get a token from api server using the fetch api
return new Promise((resolve, reject) => {
this.fetch('v1/account/login', {
email,
password
})
.then(response => {
this.setToken(response.data.token) // Setting the token in localStorage
this.setProfile(response.data.user) // Setting the user in localStorage
return resolve(response)
})
.catch(error => {
return reject(error)
})
})
}
loggedIn() {
// Checks if there is a saved token and it's still valid
const token = this.getToken() // Getting token from localstorage
return !!token && !this.isTokenExpired(token) // handwaiving here
}
isTokenExpired(token) {
try {
const decoded = decode(token)
if (decoded.exp < Date.now() / 1000) {
// Checking if token is expired. N
return true
} else return false
} catch (err) {
return false
}
}
setToken(token) {
// Saves user token to localStorage and Authorization header in axios instance
store.set('token', token)
axiosClient.defaults.headers.common['Authorization'] = `Bearer ${token}`
}
getToken() {
// Retrieves the user token from localStorage
return store.get('token')
}
logout() {
// Clear user token and profile data from localStorage
store.remove('token')
store.remove('profile')
}
getTokenData() {
// Using jwt-decode npm package to decode the token
return decode(this.getToken())
}
setProfile(data) {
// Saves user data to localStorage
store.set('profile', data)
}
getProfile() {
// Retrieves the user data from localStorage
return store.get('profile')
}
fetch(url, data) {
// performs api calls sending the required authentication headers
// Setting Authorization header
// Authorization: Bearer xxxxxxx
if (this.loggedIn()) {
axiosClient.defaults.headers.common[
'Authorization'
] = `Bearer ${this.getToken()}`
}
return new Promise((resolve, reject) => {
axiosClient
.post(url, data)
.then(response => resolve(response))
.catch(error => reject(error))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment