webapp/src/context/session.tsx

371 lines
11 KiB
TypeScript
Raw Normal View History

import type { AuthModalSource } from '../components/Nav/AuthModal/types'
2024-01-31 12:34:15 +00:00
import type { Author } from '../graphql/schema/core.gen'
import type { Accessor, JSX, Resource } from 'solid-js'
2023-12-14 11:49:55 +00:00
import {
VerifyEmailInput,
LoginInput,
AuthToken,
Authorizer,
ConfigType,
2023-12-24 08:16:41 +00:00
SignupInput,
2024-01-19 15:03:33 +00:00
AuthorizeResponse,
2024-01-31 13:08:25 +00:00
ApiResponse,
GenericResponse,
2024-01-31 13:24:40 +00:00
ForgotPasswordResponse,
ForgotPasswordInput,
2023-12-14 11:49:55 +00:00
} from '@authorizerdev/authorizer-js'
import {
createContext,
createEffect,
createMemo,
createResource,
createSignal,
2023-12-14 13:50:22 +00:00
on,
2023-12-24 21:29:25 +00:00
onCleanup,
2023-12-14 11:49:55 +00:00
onMount,
useContext,
} from 'solid-js'
2023-12-19 09:34:24 +00:00
import { inboxClient } from '../graphql/client/chat'
2023-11-28 13:18:25 +00:00
import { apiClient } from '../graphql/client/core'
2023-12-19 09:34:24 +00:00
import { notifierClient } from '../graphql/client/notifier'
2023-12-25 05:47:11 +00:00
import { useRouter } from '../stores/router'
import { showModal } from '../stores/ui'
2023-12-25 07:32:53 +00:00
import { addAuthors } from '../stores/zine/authors'
2023-12-26 10:05:15 +00:00
import { useLocalize } from './localize'
import { useSnackbar } from './snackbar'
2023-12-24 08:16:41 +00:00
const defaultConfig: ConfigType = {
2023-12-14 11:49:55 +00:00
authorizerURL: 'https://auth.discours.io',
2024-01-19 15:03:33 +00:00
redirectURL: 'https://testing.discours.io',
clientID: 'b9038a34-ca59-41ae-a105-c7fbea603e24', // FIXME: use env?
2023-12-14 11:49:55 +00:00
}
2023-11-28 13:18:25 +00:00
export type SessionContextType = {
2024-01-31 12:34:15 +00:00
config: Accessor<ConfigType>
2023-11-28 13:18:25 +00:00
session: Resource<AuthToken>
2023-12-16 14:13:14 +00:00
author: Resource<Author | null>
2023-12-24 21:12:42 +00:00
authError: Accessor<string>
2022-12-06 16:03:55 +00:00
isSessionLoaded: Accessor<boolean>
2023-12-24 08:16:41 +00:00
isAuthenticated: Accessor<boolean>
actions: {
2023-11-28 13:18:25 +00:00
loadSession: () => AuthToken | Promise<AuthToken>
2023-12-16 14:13:14 +00:00
setSession: (token: AuthToken | null) => void // setSession
loadAuthor: (info?: unknown) => Author | Promise<Author>
2023-12-20 16:54:20 +00:00
setAuthor: (a: Author) => void
requireAuthentication: (
callback: (() => Promise<void>) | (() => void),
modalSource: AuthModalSource,
) => void
2024-02-01 20:34:53 +00:00
signUp: (params: SignupInput) => Promise<{ data: AuthToken; errors: Error[] }>
signIn: (params: LoginInput) => Promise<{ data: AuthToken; errors: Error[] }>
signOut: () => Promise<void>
2024-01-19 18:24:37 +00:00
oauth: (provider: string) => Promise<void>
2024-01-31 13:24:40 +00:00
forgotPassword: (
params: ForgotPasswordInput,
) => Promise<{ data: ForgotPasswordResponse; errors: Error[] }>
2023-12-24 08:16:41 +00:00
changePassword: (password: string, token: string) => void
confirmEmail: (input: VerifyEmailInput) => Promise<AuthToken | void> // email confirm callback is in auth.discours.io
2023-12-14 11:49:55 +00:00
setIsSessionLoaded: (loaded: boolean) => void
authorizer: () => Authorizer
}
}
2024-01-22 22:12:25 +00:00
const noop = () => {}
2022-11-14 10:02:08 +00:00
const SessionContext = createContext<SessionContextType>()
2022-11-14 10:02:08 +00:00
export function useSession() {
return useContext(SessionContext)
}
2023-12-14 11:49:55 +00:00
export const SessionProvider = (props: {
2024-01-23 16:32:57 +00:00
onStateChangeCallback(state: AuthToken): unknown
2023-12-14 11:49:55 +00:00
children: JSX.Element
}) => {
2023-02-17 09:21:02 +00:00
const { t } = useLocalize()
2023-02-10 11:11:24 +00:00
const {
actions: { showSnackbar },
2023-02-10 11:11:24 +00:00
} = useSnackbar()
2023-12-24 08:16:41 +00:00
const { searchParams, changeSearchParams } = useRouter()
2024-01-31 12:34:15 +00:00
const [config, setConfig] = createSignal<ConfigType>(defaultConfig)
const authorizer = createMemo(() => new Authorizer(config()))
2024-01-19 18:24:37 +00:00
const [oauthState, setOauthState] = createSignal<string>()
2024-01-19 22:53:38 +00:00
2023-12-24 08:16:41 +00:00
// handle callback's redirect_uri
2024-01-31 12:34:15 +00:00
createEffect(() => {
2024-01-19 18:24:37 +00:00
// oauth
const state = searchParams()?.state
if (state) {
setOauthState((_s) => state)
const scope = searchParams()?.scope
? searchParams()?.scope?.toString().split(' ')
: ['openid', 'profile', 'email']
if (scope) console.info(`[context.session] scope: ${scope}`)
const url = searchParams()?.redirect_uri || searchParams()?.redirectURL || window.location.href
2024-01-19 22:53:38 +00:00
setConfig((c: ConfigType) => ({ ...c, redirectURL: url.split('?')[0] }))
2024-01-19 18:24:37 +00:00
changeSearchParams({ mode: 'confirm-email', modal: 'auth' }, true)
}
})
// handle email confirm
createEffect(() => {
2023-12-24 08:16:41 +00:00
const token = searchParams()?.token
const access_token = searchParams()?.access_token
2023-12-24 23:37:30 +00:00
if (access_token) changeSearchParams({ mode: 'confirm-email', modal: 'auth', access_token })
else if (token) changeSearchParams({ mode: 'change-password', modal: 'auth', token })
2023-12-16 14:13:14 +00:00
})
2023-12-24 08:16:41 +00:00
// load
2024-01-31 12:34:15 +00:00
let minuteLater: NodeJS.Timeout | null
2024-01-18 08:31:45 +00:00
2023-12-24 08:16:41 +00:00
const [isSessionLoaded, setIsSessionLoaded] = createSignal(false)
2023-12-24 21:12:42 +00:00
const [authError, setAuthError] = createSignal('')
2024-01-18 08:31:45 +00:00
2024-01-31 12:34:15 +00:00
// Function to load session data
const sessionData = async () => {
try {
2024-01-31 13:08:25 +00:00
const s: ApiResponse<AuthToken> = await authorizer().getSession()
if (s?.data) {
console.info('[context.session] loading session', s)
2024-01-18 08:31:45 +00:00
2024-01-31 13:08:25 +00:00
// Set session expiration time in local storage
const expires_at = new Date(Date.now() + s.data.expires_in * 1000)
localStorage.setItem('expires_at', `${expires_at.getTime()}`)
2024-01-18 08:31:45 +00:00
2024-01-31 13:08:25 +00:00
// Set up session expiration check timer
minuteLater = setTimeout(checkSessionIsExpired, 60 * 1000)
console.info(`[context.session] will refresh in ${s.data.expires_in / 60} mins`)
2024-01-18 08:31:45 +00:00
2024-01-31 13:08:25 +00:00
// Set the session loaded flag
setIsSessionLoaded(true)
return s.data
} else {
console.info('[context.session] cannot refresh session', s.errors)
setAuthError(s.errors.pop().message)
2024-01-18 08:31:45 +00:00
2024-01-31 13:08:25 +00:00
// Set the session loaded flag even if there's an error
setIsSessionLoaded(true)
return null
}
2024-01-31 12:34:15 +00:00
} catch (error) {
console.info('[context.session] cannot refresh session', error)
setAuthError(error)
2024-01-18 08:31:45 +00:00
2024-01-31 12:34:15 +00:00
// Set the session loaded flag even if there's an error
setIsSessionLoaded(true)
return null
}
}
const [session, { refetch: loadSession, mutate: setSession }] = createResource<AuthToken>(sessionData, {
ssrLoadFrom: 'initial',
initialValue: null,
})
2023-12-16 14:13:14 +00:00
2024-01-18 08:31:45 +00:00
const checkSessionIsExpired = () => {
const expires_at_data = localStorage.getItem('expires_at')
if (expires_at_data) {
const expires_at = Number.parseFloat(expires_at_data)
const current_time = Date.now()
// Check if the session has expired
if (current_time >= expires_at) {
console.info('[context.session] Session has expired, refreshing.')
loadSession()
} else {
// Schedule the next check
minuteLater = setTimeout(checkSessionIsExpired, 60 * 1000)
}
}
}
onCleanup(() => clearTimeout(minuteLater))
2024-01-31 12:34:15 +00:00
const authorData = async () => {
const u = session()?.user
return u ? (await apiClient.getAuthorId({ user: u.id.trim() })) || null : null
2023-12-24 08:16:41 +00:00
}
2024-01-31 12:34:15 +00:00
const [author, { refetch: loadAuthor, mutate: setAuthor }] = createResource<Author | null>(authorData, {
ssrLoadFrom: 'initial',
initialValue: null,
})
2023-12-24 21:12:42 +00:00
// when session is loaded
2024-01-31 12:34:15 +00:00
createEffect(() => {
2023-12-24 08:16:41 +00:00
if (session()) {
const token = session()?.access_token
if (token) {
2023-12-24 21:29:25 +00:00
// console.log('[context.session] token observer got token', token)
2023-12-24 08:16:41 +00:00
if (!inboxClient.private) {
apiClient.connect(token)
notifierClient.connect(token)
inboxClient.connect(token)
}
2024-01-31 12:34:15 +00:00
if (!author()) loadAuthor()
2023-12-24 21:12:42 +00:00
setIsSessionLoaded(true)
2023-12-24 08:16:41 +00:00
}
2023-12-24 12:56:30 +00:00
}
})
2024-01-31 12:34:15 +00:00
// when author is loaded
createEffect(() => {
if (author()) {
addAuthors([author()])
} else {
reset()
}
})
2023-12-24 21:44:01 +00:00
const reset = () => {
setIsSessionLoaded(true)
setSession(null)
setAuthor(null)
}
2023-12-24 08:16:41 +00:00
// initial effect
onMount(async () => {
const metaRes = await authorizer().getMetaData()
setConfig({ ...defaultConfig, ...metaRes, redirectURL: window.location.origin })
2024-01-18 15:57:10 +00:00
let s: AuthToken
2023-12-24 08:16:41 +00:00
try {
s = await loadSession()
2023-12-25 04:05:04 +00:00
} catch (error) {
console.warn('[context.session] load session failed', error)
2023-12-24 12:56:30 +00:00
}
2023-12-24 21:44:01 +00:00
if (!s) reset()
2023-12-24 08:16:41 +00:00
})
2023-12-14 11:49:55 +00:00
2023-12-24 08:16:41 +00:00
// callback state updater
2023-12-14 13:50:22 +00:00
createEffect(
on(
() => props.onStateChangeCallback,
() => {
2023-12-16 14:13:14 +00:00
props.onStateChangeCallback(session())
2023-12-14 13:50:22 +00:00
},
{ defer: true },
),
)
2023-12-14 11:49:55 +00:00
2024-01-22 22:12:25 +00:00
const [authCallback, setAuthCallback] = createSignal<() => void>(() => {})
2024-01-31 12:34:15 +00:00
const requireAuthentication = (callback: () => void, modalSource: AuthModalSource) => {
2024-01-22 22:12:25 +00:00
setAuthCallback((_cb) => callback)
2023-12-24 08:16:41 +00:00
if (!session()) {
2024-01-31 12:34:15 +00:00
loadSession()
2024-01-22 21:03:57 +00:00
if (!session()) {
showModal('auth', modalSource)
}
}
}
2024-01-22 21:03:57 +00:00
createEffect(() => {
2024-01-22 22:12:25 +00:00
const handler = authCallback()
if (handler !== noop) {
handler()
setAuthCallback((_cb) => noop)
2024-01-22 21:03:57 +00:00
}
})
2023-12-24 08:16:41 +00:00
// authorizer api proxy methods
2024-02-01 20:34:53 +00:00
const authenticate = async (authFunction, params) => {
const resp = await authFunction(params)
console.debug('[context.session] authenticate:', resp)
if (resp?.data && !resp.errors) {
setSession(resp.data)
}
return { data: resp?.data, errors: resp?.errors }
}
2024-01-19 18:24:37 +00:00
const signUp = async (params: SignupInput) => {
2024-02-01 20:34:53 +00:00
return authenticate(authorizer().signup, params)
2023-12-24 08:16:41 +00:00
}
const signIn = async (params: LoginInput) => {
2024-02-01 20:34:53 +00:00
return authenticate(authorizer().login, params)
2023-12-24 08:16:41 +00:00
}
const signOut = async () => {
2024-01-31 13:08:25 +00:00
const authResult: ApiResponse<GenericResponse> = await authorizer().logout()
console.debug(authResult)
2023-12-24 21:44:01 +00:00
reset()
2023-02-10 11:11:24 +00:00
showSnackbar({ body: t("You've successfully logged out") })
}
2023-12-24 08:16:41 +00:00
const changePassword = async (password: string, token: string) => {
const resp = await authorizer().resetPassword({ password, token, confirm_password: password })
console.debug('[context.session] change password response:', resp)
}
2024-01-31 13:24:40 +00:00
const forgotPassword = async (params: ForgotPasswordInput) => {
const resp = await authorizer().forgotPassword(params)
console.debug('[context.session] change password response:', resp)
return { data: resp?.data, errors: resp.errors }
}
2023-11-28 13:18:25 +00:00
const confirmEmail = async (input: VerifyEmailInput) => {
2023-12-17 12:36:47 +00:00
console.debug(`[context.session] calling authorizer's verify email with`, input)
2023-12-24 21:12:42 +00:00
try {
2024-01-31 13:08:25 +00:00
const at: ApiResponse<AuthToken> = await authorizer().verifyEmail(input)
if (at?.data) {
setSession(at.data)
return at.data
} else {
console.warn(at?.errors)
}
2023-12-25 04:05:04 +00:00
} catch (error) {
console.warn(error)
2023-12-24 21:12:42 +00:00
}
}
2024-01-19 18:24:37 +00:00
const oauth = async (oauthProvider: string) => {
2024-01-19 15:03:33 +00:00
console.debug(`[context.session] calling authorizer's oauth for`)
try {
2024-01-19 18:24:37 +00:00
// const data: GraphqlQueryInput = {}
// await authorizer().graphqlQuery(data)
2024-01-19 15:03:33 +00:00
const ar: AuthorizeResponse | void = await authorizer().oauthLogin(
oauthProvider,
[],
window.location.origin,
2024-01-19 18:24:37 +00:00
oauthState(),
2024-01-19 15:03:33 +00:00
)
console.debug(ar)
} catch (error) {
console.warn(error)
}
}
2023-12-24 08:16:41 +00:00
const isAuthenticated = createMemo(() => Boolean(author()))
const actions = {
loadSession,
requireAuthentication,
2023-12-24 08:16:41 +00:00
signUp,
signIn,
signOut,
confirmEmail,
2023-12-14 11:49:55 +00:00
setIsSessionLoaded,
2023-12-20 16:54:20 +00:00
setSession,
setAuthor,
2023-12-14 11:49:55 +00:00
authorizer,
2023-12-16 14:13:14 +00:00
loadAuthor,
2024-01-31 13:24:40 +00:00
forgotPassword,
2023-12-24 08:16:41 +00:00
changePassword,
2024-01-19 18:24:37 +00:00
oauth,
}
const value: SessionContextType = {
2023-12-24 21:12:42 +00:00
authError,
2024-01-31 12:34:15 +00:00
config,
session,
isSessionLoaded,
2023-12-14 11:49:55 +00:00
author,
actions,
2023-12-24 08:16:41 +00:00
isAuthenticated,
}
2022-11-14 10:02:08 +00:00
return <SessionContext.Provider value={value}>{props.children}</SessionContext.Provider>
}