完善路由导航与鉴权功能

Signed-off-by: luorijun <luorijun@outlook.com>
This commit is contained in:
2025-12-29 14:37:03 +08:00
parent bb8aec8ce5
commit f950906f00
8 changed files with 601 additions and 264 deletions

View File

@@ -3,8 +3,20 @@ 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", {
export type TokenResp = {
access_token: string
refresh_token: string
expires_in: number
token_type: string
scope?: string
}
export async function login(params: {
username: string
password: string
remember: boolean
}): Promise<ApiResponse> {
const resp = await callByDevice<TokenResp>("/api/auth/token", {
grant_type: "password",
login_type: "password",
login_pool: "admin",
@@ -34,16 +46,49 @@ export async function login(params: LoginReq): Promise<ApiResponse> {
}
}
export type LoginReq = {
username: string
password: string
remember: boolean
}
export async function refreshAuth() {
const cookie = await cookies()
export type LoginRes = {
access_token: string
refresh_token: string
expires_in: number
token_type: string
scope?: string
const userRefresh = cookie.get("auth_refresh")?.value
if (!userRefresh) {
throw new Error("未授权访问")
}
// 请求刷新访问令牌
const resp = await callByDevice<TokenResp>(`/api/auth/token`, {
grant_type: "refresh_token",
refresh_token: userRefresh,
})
// 处理请求
if (!resp.success) {
if (resp.status === 401) {
cookie.delete("auth_refresh")
}
throw new Error("未授权访问")
}
// 解析响应
const data = resp.data
const nextAccessToken = data.access_token
const nextRefreshToken = data.refresh_token
const expiresIn = data.expires_in
// 保存令牌到 cookies
cookie.set("auth_token", nextAccessToken, {
httpOnly: true,
sameSite: "strict",
maxAge: Math.max(expiresIn, 0),
})
cookie.set("auth_refresh", nextRefreshToken, {
httpOnly: true,
sameSite: "strict",
maxAge: Number.MAX_SAFE_INTEGER,
})
// 返回新的访问令牌
return {
access_token: nextAccessToken,
refresh_token: nextRefreshToken,
}
}