Skip to content

Instantly share code, notes, and snippets.

@nicodevs
Last active August 30, 2022 19:04
Show Gist options
  • Save nicodevs/8ec17620494b814825ba37601aca1b89 to your computer and use it in GitHub Desktop.
Save nicodevs/8ec17620494b814825ba37601aca1b89 to your computer and use it in GitHub Desktop.
// Warning: this is just a non-tested example, take it as an starting point draft :)
import castArray from 'lodash/castArray'
const state = reactive({
data: {},
token: ''
})
const getCookieParams = () => {
const today = new Date()
const tomorrow = new Date()
tomorrow.setDate(today.getDate() + 1)
return {
path: '/',
maxAge: tomorrow,
sameSite: 'strict'
}
}
export default function () {
const { $axios } = useNuxtApp()
let jwt = null
jwt = useCookie('jwt', getCookieParams())
const setToken = (token) => {
$axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
jwt.value = token
}
const removeTokenCookie = () => {
jwt.value = null
}
const login = async ({ email, password }) => {
const { data } = await $axios.post('/api/login', { email, password })
state.data = data.data
state.token = data.token
setToken(data.token)
}
const logout = async () => {
await $axios.post('/api/logout')
setToken(null)
}
const validate = async (token) => {
const { data } = await $axios.get('/api/auth', {
headers: {
Authorization: `Bearer ${token}`
}
})
state.data = data.data
state.token = data.token
setToken(data.token)
}
const updateUser = async (params) => {
const { data } = await $axios.put('/api/user', params)
state.data.name = data.data.name
state.data.email = data.data.email
}
return {
...toRefs(state),
setToken,
removeTokenCookie,
login,
logout,
validate,
updateUser
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment