webapp/src/stores/auth.ts

55 lines
1.3 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-09 11:53:35 +00:00
const log = getLogger('auth-store')
2022-09-09 13:30:25 +00:00
export const session = atom<AuthResult>()
2022-09-13 09:59:04 +00:00
export const signIn = async (params) => {
2022-09-17 18:23:30 +00:00
const s = await apiClient.authLogin(params)
2022-09-13 09:59:04 +00:00
session.set(s)
2022-09-09 13:30:25 +00:00
setToken(s.token)
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-17 18:23:30 +00:00
const s = await apiClient.authRegiser(params)
2022-09-13 09:59:04 +00:00
session.set(s)
2022-09-09 13:30:25 +00:00
setToken(s.token)
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 = () => {
session.set(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-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-13 09:59:04 +00:00
session.set(auth)
}
2022-09-09 14:13:50 +00:00
2022-09-13 09:59:04 +00:00
export const renewSession = async () => {
2022-09-09 14:13:50 +00:00
const s = await apiClient.getSession() // token in header
setToken(s.token)
2022-09-13 09:59:04 +00:00
session.set(s)
}