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

View File

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