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