webapp/src/stores/auth.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-09-09 11:53:35 +00:00
import type { AuthResult } from '../graphql/types.gen'
import { resetToken, setToken } from '../graphql/privateGraphQLClient'
2022-09-09 13:30:25 +00:00
import { apiClient } from '../utils/apiClient'
2022-09-30 14:22:33 +00:00
import { createSignal } from 'solid-js'
2022-09-09 11:53:35 +00:00
2022-09-30 14:22:33 +00:00
const [session, setSession] = createSignal<AuthResult | null>(null)
2022-09-09 13:30:25 +00:00
2022-09-13 09:59:04 +00:00
export const signIn = async (params) => {
2022-09-30 14:22:33 +00:00
const authResult = await apiClient.authLogin(params)
setSession(authResult)
setToken(authResult.token)
2022-10-08 16:40:58 +00:00
console.debug('signed in')
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
2022-09-13 09:59:04 +00:00
export const signOut = () => {
2022-10-21 18:17:04 +00:00
// TODO: call backend to revoke token
2022-09-30 14:22:33 +00:00
setSession(null)
2022-09-09 13:30:25 +00:00
resetToken()
2022-10-08 16:40:58 +00:00
console.debug('signed out')
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
2022-10-21 18:17:04 +00:00
export const [emailChecks, setEmailChecks] = createSignal<{ [email: string]: boolean }>({})
export const checkEmail = async (email: string): Promise<boolean> => {
if (emailChecks()[email]) {
return true
}
2022-09-09 13:30:25 +00:00
2022-10-21 18:17:04 +00:00
const checkResult = await apiClient.authCheckEmail({ email })
if (checkResult) {
setEmailChecks((oldEmailChecks) => ({ ...oldEmailChecks, [email]: true }))
return true
}
2022-09-09 13:30:25 +00:00
2022-10-21 18:17:04 +00:00
return false
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
2022-10-21 18:17:04 +00:00
export const [resetCode, setResetCode] = createSignal('')
2022-09-09 13:30:25 +00:00
2022-10-21 18:17:04 +00:00
export const register = async ({
name,
email,
password
}: {
name: string
email: string
password: string
}) => {
await apiClient.authRegister({
name,
2022-09-30 14:22:33 +00:00
email,
password
})
}
2022-11-01 22:25:18 +00:00
export const signSendLink = async ({ email, lang }: { email: string, lang: string }) => {
await apiClient.authSendLink({ email, lang })
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
2022-09-13 09:59:04 +00:00
export const renewSession = async () => {
2022-09-30 14:22:33 +00:00
const authResult = await apiClient.getSession() // token in header
setToken(authResult.token)
setSession(authResult)
}
2022-10-21 18:17:04 +00:00
export const confirmEmail = async (token: string) => {
const authResult = await apiClient.confirmEmail({ token })
setToken(authResult.token)
setSession(authResult)
}
2022-09-30 14:22:33 +00:00
export const useAuthStore = () => {
2022-10-21 18:17:04 +00:00
return { session, emailChecks }
2022-09-13 09:59:04 +00:00
}