webapp/src/stores/auth.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-09-17 18:23:30 +00:00
import { atom } from 'nanostores'
2022-09-09 11:53:35 +00:00
import type { AuthResult } from '../graphql/types.gen'
import { getLogger } from '../utils/logger'
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
const log = getLogger('auth-store')
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-09-09 13:30:25 +00:00
log.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 signUp = async (params) => {
2022-09-30 14:22:33 +00:00
const authResult = await apiClient.authRegister(params)
setSession(authResult)
setToken(authResult.token)
2022-09-09 13:30:25 +00:00
log.debug('signed up')
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-09-30 14:22:33 +00:00
setSession(null)
2022-09-09 13:30:25 +00:00
resetToken()
log.debug('signed out')
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
export const emailChecks = atom<{ [email: string]: boolean }>({})
2022-09-13 09:59:04 +00:00
export const signCheck = async (params) => {
2022-09-17 18:23:30 +00:00
emailChecks.set(await apiClient.authCheckEmail(params))
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
export const resetCode = atom<string>()
2022-09-30 14:22:33 +00:00
export const register = async ({ email, password }: { email: string; password: string }) => {
const authResult = await apiClient.authRegister({
email,
password
})
if (authResult && !authResult.error) {
log.debug('register session update', authResult)
setSession(authResult)
}
}
2022-09-17 18:23:30 +00:00
export const signSendLink = async (params) => {
await apiClient.authSendLink(params) // { email }
2022-09-09 13:30:25 +00:00
resetToken()
2022-09-13 09:59:04 +00:00
}
2022-09-09 13:30:25 +00:00
2022-09-17 18:23:30 +00:00
export const signConfirm = async (params) => {
const auth = await apiClient.authConfirmCode(params) // { code }
2022-09-09 13:30:25 +00:00
setToken(auth.token)
2022-09-30 14:22:33 +00:00
setSession(auth)
2022-09-13 09:59:04 +00:00
}
2022-09-09 14:13:50 +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)
}
export const useAuthStore = () => {
return { session }
2022-09-13 09:59:04 +00:00
}