'use server' import {cookies} from 'next/headers' import {ApiResponse, UnauthorizedError} from '@/lib/api' import {AuthContext} from '@/lib/auth' import {User} from '@/lib/models' import {callByDevice, callByUser, callPublic, getUserToken} from '@/actions/base' import {redirect} from 'next/navigation' import {cache} from 'react' export interface LoginParams { username: string password: string remember: boolean } type LoginResp = { access_token: string refresh_token: string expires_in: number token_type: string scope?: string } export async function login(props: LoginParams): Promise { // 尝试登录 const result = await callByDevice('/api/auth/token', { ...props, grant_type: 'password', login_type: 'phone_code', }) if (!result.success) { return result } // 保存到 cookies const data = result.data const cookieStore = await cookies() cookieStore.set('auth_token', data.access_token, { httpOnly: true, sameSite: 'strict', maxAge: Math.max(data.expires_in, 0), }) cookieStore.set('auth_refresh', data.refresh_token, { httpOnly: true, sameSite: 'strict', }) // cookieStore.set('auth_info', JSON.stringify(data.auth), { // httpOnly: true, // sameSite: 'strict', // }) // cookieStore.set('auth_profile', JSON.stringify(data.profile), { // httpOnly: true, // sameSite: 'strict', // }) return { success: true, data: undefined, } } export async function logout() { const cookieStore = await cookies() // 尝试删除后台会话 const access_token = cookieStore.get('auth_token')?.value const refresh_token = cookieStore.get('auth_refresh')?.value if (access_token && refresh_token) { await callByDevice('/api/auth/revoke', { access_token, refresh_token, }) } // 删除 cookies cookieStore.set('auth_token', '', { httpOnly: true, sameSite: 'strict', maxAge: -1, }) cookieStore.set('auth_refresh', '', { httpOnly: true, sameSite: 'strict', maxAge: -1, }) return { success: true, data: undefined, } } export async function getProfile() { try { const token = await getUserToken() const result = await callPublic('/api/user/get/token', {token}) if (!result.success) { throw new Error('获取用户信息失败') } return result.data } catch (e) { if (e === UnauthorizedError) { return null } throw e } }