Capital/src/services/user.tsx

98 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-01-01 23:05:19 +08:00
import { create } from 'zustand'
import { sni } from './network'
import { hasCookie } from 'cookies-next/client'
2025-01-02 22:57:06 +08:00
import { JSX } from 'react'
import ConstructionIcon from '@mui/icons-material/Construction'
import FlagIcon from '@mui/icons-material/Flag'
2025-01-01 23:05:19 +08:00
2025-01-02 22:40:56 +08:00
export interface SnAccount {
2025-01-01 23:05:19 +08:00
id: number
createdAt: Date
updatedAt: Date
deletedAt?: Date | null
confirmedAt?: Date | null
contacts?: SnAccountContact[] | null
avatar: string
banner: string
description: string
name: string
nick: string
permNodes: Record<string, any>
profile?: SnAccountProfile | null
badges: SnAccountBadge[]
suspendedAt?: Date | null
affiliatedId?: number | null
affiliatedTo?: number | null
automatedBy?: number | null
automatedId?: number | null
}
2025-01-02 22:40:56 +08:00
export interface SnAccountContact {
2025-01-01 23:05:19 +08:00
accountId: number
content: string
createdAt: Date
deletedAt?: Date | null
id: number
isPrimary: boolean
isPublic: boolean
type: number
updatedAt: Date
verifiedAt?: Date | null
}
2025-01-02 22:40:56 +08:00
export interface SnAccountProfile {
2025-01-01 23:05:19 +08:00
id: number
accountId: number
birthday?: Date | null
createdAt: Date
deletedAt?: Date | null
experience: number
firstName: string
lastName: string
lastSeenAt?: Date | null
updatedAt: Date
}
2025-01-02 22:40:56 +08:00
export interface SnAccountBadge {
2025-01-01 23:05:19 +08:00
id: number
createdAt: Date
updatedAt: Date
deletedAt?: Date | null
type: string
accountId: number
metadata: Record<string, any>
}
2025-01-02 22:57:06 +08:00
export const SnAccountBadgeMapping: Record<string, { icon: JSX.Element; name: string }> = {
'company.staff': {
icon: <ConstructionIcon />,
name: 'Solsynth Staff',
},
'site.migration': {
icon: <FlagIcon />,
name: 'Solar Network Natives',
},
}
2025-01-01 23:05:19 +08:00
export interface UserStore {
account: SnAccount | undefined
fetchUser: () => Promise<SnAccount | undefined>
}
export const useUserStore = create<UserStore>((set) => ({
account: undefined,
fetchUser: async (): Promise<SnAccount | undefined> => {
if (!hasCookie('nex_user_atk')) return
try {
const resp = await sni.get<SnAccount>('/cgi/id/users/me')
set({ account: resp.data })
console.log('[Authenticator] Logged in as @' + resp.data.name)
return resp.data
} catch (err) {
console.error('[Authenticator] Unable to get user profile: ', err)
return
}
},
}))