Skip to content

Instantly share code, notes, and snippets.

@lunfel
Created March 9, 2018 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunfel/4b973f51026ffd7195087e8131093640 to your computer and use it in GitHub Desktop.
Save lunfel/4b973f51026ffd7195087e8131093640 to your computer and use it in GitHub Desktop.
Login class based on tymondesigns/jwt-auth
import http from '@/services/http'
import store from '@/store'
import router from '@/router'
import moment from 'moment'
import User from '@/entities/user'
export default class Auth {
static async login ({email, password}) {
try {
const response = await http.post(`/api/auth/login`, {email, password})
window.localStorage.setItem('token', response.data.token)
const expiresAt = moment().add(response.data.expires_in, 'seconds')
window.localStorage.setItem('expires_at', expiresAt.toISOString())
this.refreshUser()
return true
} catch (error) {
return false
}
}
static async logout () {
await http.post('/api/auth/logout')
window.localStorage.removeItem('token')
window.localStorage.removeItem('expires_at')
this.refreshUser()
router.push({name: 'login'})
return true
}
static isAuthenticated () {
return typeof window.localStorage.token !== 'undefined'
}
static async refreshToken () {
if (!this.isAboutToExpire() || this.isSessionExpired()) {
return false
}
const response = await http.post('/api/auth/refresh')
window.localStorage.setItem('token', response.data.token)
const expiresAt = moment().add(response.data.expires_in, 'seconds')
window.localStorage.setItem('expires_at', expiresAt.toISOString())
this.refreshUser()
return true
}
static async refreshUser () {
if (!this.getToken()) {
store.dispatch('user/clear')
return
}
if (!store.getters['user/isAuthenticated']) {
const user = await this.getUser()
store.dispatch('user/setUser', user)
}
}
static async getUser () {
if (!this.isAuthenticated()) {
return null
}
const {data} = await http.get('/api/auth/me')
return User.single(data)
}
static getToken () {
const expiresAt = moment(window.localStorage.getItem('expires_at'))
if (moment().isAfter(expiresAt)) {
return null
}
return window.localStorage.getItem('token')
}
static expiresIn () {
return moment().diff(moment(window.localStorage.getItem('expires_at')), 'seconds')
}
static isSessionExpired () {
const expiresAt = window.localStorage.getItem('expires_at')
if (!expiresAt) {
return true
}
return moment().isAfter(moment(expiresAt))
}
static isAboutToExpire () {
const expiresAt = window.localStorage.getItem('expires_at')
if (!expiresAt) {
return false
}
return moment().isAfter(moment(expiresAt).subtract(process.env.REFRESH_THRESHOLD, 'seconds'))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment