feat: store authCode in Pinia
This commit is contained in:
parent
3c85206da0
commit
8c21969246
@ -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>
|
||||
|
26
client/src/composables/useAuth.ts
Normal file
26
client/src/composables/useAuth.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
14
client/src/stores/MyselfStore.ts
Normal file
14
client/src/stores/MyselfStore.ts
Normal 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
|
||||
}
|
||||
},
|
||||
})
|
Loading…
Reference in New Issue
Block a user