Skip to content

Instantly share code, notes, and snippets.

@Stiropor
Last active September 8, 2022 14:38
Show Gist options
  • Save Stiropor/94c125e2a77c1a50977d73ddae064a1e to your computer and use it in GitHub Desktop.
Save Stiropor/94c125e2a77c1a50977d73ddae064a1e to your computer and use it in GitHub Desktop.
Nuxt3 auth demo
import { nextTick } from 'vue'
export const useProperCookie = () => useCookie('proper_token')
export const useAuthFetch = (url, fetchOptions = {}) => {
return $fetch(url, {
baseURL: 'https://l9.test/api/v1',
...fetchOptions,
headers: {
Authorization: `Bearer ${useProperCookie().value}`,
...fetchOptions.headers,
},
})
}
export const useProperUser = async (force = false) => {
const cookie = useProperCookie()
const user = useState('proper_user')
if ((cookie.value && !user.value) || force) {
const userResponse = await useAuthFetch('/auth/user', {
method: 'post',
})
user.value = userResponse.data
}
return user
}
export const properLogin = async (data) => {
if (process.client) {
const user = await $fetch('https://l9.test/api/v1/auth/login', {
method: 'post',
body: data
})
if (user) {
useProperCookie().value = user.access_token
await nextTick()
await useProperUser()
}
}
}
export const properLogout = async () => {
if (process.client) {
await $fetch('https://l9.test/api/v1/auth/logout', {
method: 'post',
headers: {
Authorization: `Bearer ${useProperCookie().value}`,
},
})
}
useProperCookie().value = null
useState('proper_user').value = null
}
export const properIsLoggedIn = computed(() => {
return useState('proper_user').value?.id !== undefined
})
export const properUserData = computed(() => {
return useState('proper_user').value
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment