feat: store authCode in Pinia

This commit is contained in:
Settel 2022-07-29 15:08:12 +02:00
parent 3c85206da0
commit 8c21969246
3 changed files with 58 additions and 12 deletions

View File

@ -10,26 +10,32 @@
</template>
<script setup lang="ts">
import { useFetch, useRouter } from '#app'
import { watch, ref, Ref } from 'vue'
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 router = useRouter()
const vFocus = { mounted: (el: HTMLElement) => el.focus() }
const authCode: Ref<string> = ref('')
const errorMessage: Ref<string> = ref('')
const vFocus = { mounted: (el: HTMLElement) => el.focus() }
validate()
.then(() => router.push('/play'))
.catch(() => null)
const login = (): void => {
errorMessage.value = ''
setAuthCode(authCode.value)
const { data, pending } = useFetch(`/api/login?code=${authCode.value}`)
watch(pending, (newVal) => {
if (!newVal && data.value === 'ok') {
const router = useRouter()
router.push('/play')
} else if (!newVal) {
errorMessage.value = 'login failed'
}
validate().then(() => {
router.push('/play')
}).catch(() => {
errorMessage.value = 'login failed'
})
}
</script>

View File

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

View File

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