feat(project): init
This commit is contained in:
95
components/login/libs/cookie.ts
Normal file
95
components/login/libs/cookie.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { ResultData } from "@/api/typing"
|
||||
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: ResultData<Login.ResLogin>
|
||||
}) => {
|
||||
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?.message?.user_info?.user_name,
|
||||
access_token: data.message.access_token,
|
||||
refresh_token: data.message.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,
|
||||
message: {
|
||||
...data.message,
|
||||
access_token: "",
|
||||
refresh_token: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const handleRefreshToken = async (props: {
|
||||
data: ResultData<Login.ResRefreshKey>
|
||||
userData: any
|
||||
}) => {
|
||||
const { userData, data } = props
|
||||
const { redisKey, ...rest } = userData
|
||||
await redis.set(
|
||||
JSON.parse(redisKey),
|
||||
JSON.stringify({
|
||||
...rest,
|
||||
access_token: data?.message?.access,
|
||||
refresh_token: data?.message?.refresh,
|
||||
}),
|
||||
"EX",
|
||||
172800
|
||||
)
|
||||
return {
|
||||
...data,
|
||||
message: {
|
||||
...data.message,
|
||||
// access_token: "",
|
||||
// refresh_token: "",
|
||||
access: "",
|
||||
refresh: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user