import { OAuthToken, OrganizationResource, PersonResource } from '../types' export type ENV = 'production' | 'staging' | 'development' export type OauthType = 'OAuth' | 'ChurchCenterOauth' export type PartialToken = Pick & Partial export type SessionMeta = { [key: string]: { person: PersonResource organization: OrganizationResource } } export type SessionProps = { env?: ENV token?: T type?: OauthType meta?: SessionMeta } export const UNAUTHENTICATED_SESSION_ID = 'unauthenticated' as const type SessionId = string | typeof UNAUTHENTICATED_SESSION_ID /** * Session class to track the environment and token * Not intended to make network requests or handle authentication */ export class Session { env: ENV token: T | undefined type: OauthType meta: Record constructor(props?: SessionProps) { const { env = 'production', token, type, meta } = props || {} this.env = env this.token = token this.type = type || 'OAuth' this.meta = meta || {} } get isAuthenticated() { return Boolean(this.token?.access_token) } get isChurchCenterToken() { return this.type === 'ChurchCenterOauth' } get id(): SessionId { if (!this.isAuthenticated || !this.token?.access_token) { return UNAUTHENTICATED_SESSION_ID } const tokenStr = this.token.access_token return tokenStr.slice(-8) } toString() { return JSON.stringify({ env: this.env, token: this.token, meta: this.meta }) } // Convenience methods to set the person and organization setPerson(person: PersonResource) { this.meta.person = person } setOrganization(organization: OrganizationResource) { this.meta.organization = organization } static hydrate(sessionString: string) { try { const props = JSON.parse(sessionString) return new Session(props) } catch (_error) { return new Session() } } }