feat: authenticate via cookie, replace Pinia MyselfStore

This commit is contained in:
Settel 2022-07-29 15:31:36 +02:00
parent 8c21969246
commit 72d61d7811
4 changed files with 24 additions and 34 deletions

View File

@ -13,9 +13,8 @@
import { useRouter } from '#app'
import { ref, Ref } from 'vue'
import useAuth from '@/composables/useAuth';
// import { useMyselfStore } from '~~/src/stores/MyselfStore'
const { validate, setAuthCode } = useAuth()
const { authenticate, isAuthenticated } = useAuth()
const router = useRouter()
const vFocus = { mounted: (el: HTMLElement) => el.focus() }
@ -23,16 +22,14 @@ const vFocus = { mounted: (el: HTMLElement) => el.focus() }
const authCode: Ref<string> = ref('')
const errorMessage: Ref<string> = ref('')
validate()
.then(() => router.push('/play'))
.catch(() => null)
if (await isAuthenticated()) {
router.push('/play')
}
const login = (): void => {
errorMessage.value = ''
setAuthCode(authCode.value)
validate().then(() => {
authenticate(authCode.value).then(() => {
router.push('/play')
}).catch(() => {
errorMessage.value = 'login failed'

View File

@ -1,26 +1,25 @@
import { useMyselfStore } from '~~/src/stores/MyselfStore'
export interface useAuth {
validate(): Promise<void>
setAuthCode(authCode: string): void
authenticate(authCode: string): Promise<void>
isAuthenticated(): Promise<boolean>
}
export default () => {
const MyselfStore = useMyselfStore()
return {
validate: async (): Promise<void> => {
if (MyselfStore.authCode.length != 6) {
isAuthenticated: async (): Promise<boolean> => {
return $fetch('/api/userinfo')
.then(() => true)
.catch(() => false)
},
authenticate: async (authCode: string): Promise<void> => {
if (authCode.length != 6) {
throw Error('login failed')
}
const resp = await $fetch(`/api/login?code=${MyselfStore.authCode}`)
const resp = await $fetch(`/api/login?code=${authCode}`)
if (resp !== 'ok') {
throw Error('login failed')
}
},
setAuthCode: (authCode: string): void => {
MyselfStore.setAuthCode(authCode)
}
}
}

View File

@ -1,14 +0,0 @@
import { defineStore } from 'pinia'
export const useMyselfStore = defineStore('MyselfStore', {
state: () => {
return {
authCode: '',
}
},
actions: {
setAuthCode(authCode: string): void {
this.authCode = authCode
}
},
})

View File

@ -0,0 +1,8 @@
import { defineStore } from 'pinia'
export const useUserinfoStore = defineStore('UserinfoStore', {
state: () => {
return {
}
},
})