91 lines
2.1 KiB
TypeScript
91 lines
2.1 KiB
TypeScript
import { Login } from "@/components/login/api/types"
|
|
import redis from "@/components/login/libs/redis"
|
|
import { encrypt, generateKeyFromEnv } from "@/components/login/libs/session"
|
|
import { cookies } from "next/headers"
|
|
|
|
export const handleLoginData = async (props: {
|
|
clientIP: string
|
|
fingerprint: string
|
|
data: Login.ResLabelLogin
|
|
}) => {
|
|
const { clientIP, fingerprint, data } = props
|
|
|
|
const sessionKey = {
|
|
clientIP,
|
|
fingerprint: fingerprint,
|
|
}
|
|
const cookieStore = await cookies()
|
|
|
|
const oldSession = cookieStore.get("session")?.value || ""
|
|
if (oldSession) {
|
|
redis.del(JSON.parse(oldSession) as any)
|
|
}
|
|
|
|
const key = await generateKeyFromEnv(process.env.ENCRYPTION_KEY || "")
|
|
const encryptedSessionData = await encrypt(JSON.stringify(sessionKey), key)
|
|
|
|
// save redis
|
|
await redis.set(
|
|
encryptedSessionData,
|
|
JSON.stringify({
|
|
clientIP,
|
|
fingerprint: fingerprint,
|
|
user_name: data?.name,
|
|
access_token: data.token,
|
|
refresh_token: data.refresh_token,
|
|
}),
|
|
"EX",
|
|
172800
|
|
)
|
|
|
|
// set cookie
|
|
cookieStore.set("session", JSON.stringify(encryptedSessionData), {
|
|
httpOnly: true,
|
|
secure: process.env.NEXT_PUBLIC_COOKIE_ENV === "production",
|
|
maxAge: 60 * 60 * 24 * 30, // 30天
|
|
path: "/",
|
|
})
|
|
return {
|
|
...data,
|
|
token: "",
|
|
access_token: "",
|
|
refresh_token: "",
|
|
}
|
|
}
|
|
|
|
export const handleRefreshToken = async (props: {
|
|
data: Login.ResLabelLogin
|
|
userData: any
|
|
}) => {
|
|
const { userData, data } = props
|
|
const { redisKey, ...rest } = userData
|
|
await redis.set(
|
|
JSON.parse(redisKey),
|
|
JSON.stringify({
|
|
...rest,
|
|
user_name: data?.name,
|
|
access_token: data.token,
|
|
refresh_token: data.refresh_token,
|
|
}),
|
|
"EX",
|
|
172800
|
|
)
|
|
return {
|
|
...data,
|
|
token: "",
|
|
access_token: "",
|
|
refresh_token: "",
|
|
}
|
|
}
|
|
|
|
export const handleDeleteCookie = async () => {
|
|
const cookieStore = await cookies()
|
|
const sessionData = cookieStore.get("session")?.value || ""
|
|
|
|
// 删cookie和redis中用户
|
|
if (sessionData) {
|
|
await redis.del(JSON.parse(sessionData) as any)
|
|
cookieStore.delete("session")
|
|
}
|
|
}
|