49
src/actions/auth.ts
Normal file
49
src/actions/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
"use server"
|
||||
import { cookies } from "next/headers"
|
||||
import type { ApiResponse } from "@/lib/api"
|
||||
import { callByDevice } from "./base"
|
||||
|
||||
export async function login(params: LoginReq): Promise<ApiResponse> {
|
||||
const resp = await callByDevice<LoginRes>("/api/auth/token", {
|
||||
grant_type: "password",
|
||||
login_type: "password",
|
||||
login_pool: "admin",
|
||||
...params,
|
||||
})
|
||||
if (!resp.success) {
|
||||
return resp
|
||||
}
|
||||
|
||||
// 保存到 cookies
|
||||
const data = resp.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",
|
||||
maxAge: Number.MAX_SAFE_INTEGER,
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export type LoginReq = {
|
||||
username: string
|
||||
password: string
|
||||
remember: boolean
|
||||
}
|
||||
|
||||
export type LoginRes = {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
expires_in: number
|
||||
token_type: string
|
||||
scope?: string
|
||||
}
|
||||
Reference in New Issue
Block a user