Some checks failed
CI / Test (ubuntu-latest) (push) Has been cancelled
CI / Test (windows-latest) (push) Has been cancelled
CI / Lint (ubuntu-latest) (push) Has been cancelled
CI / Lint (windows-latest) (push) Has been cancelled
CI / Check (ubuntu-latest) (push) Has been cancelled
CI / Check (windows-latest) (push) Has been cancelled
CI / CI OK (push) Has been cancelled
CodeQL / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Website on push / Deploy Push Playground Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Docs Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Antd Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Element Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Naive Ftp (push) Has been cancelled
Deploy Website on push / Rerun on failure (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
Lock Threads / action (push) Has been cancelled
Issue Close Require / close-issues (push) Has been cancelled
Close stale issues / stale (push) Has been cancelled
60 lines
1.5 KiB
TypeScript
60 lines
1.5 KiB
TypeScript
import type { EventHandlerRequest, H3Event } from 'h3'
|
|
|
|
import jwt from 'jsonwebtoken'
|
|
|
|
import { UserInfo } from './mock-data'
|
|
|
|
// TODO: Replace with your own secret key
|
|
const ACCESS_TOKEN_SECRET = 'access_token_secret'
|
|
const REFRESH_TOKEN_SECRET = 'refresh_token_secret'
|
|
|
|
export interface UserPayload extends UserInfo {
|
|
iat: number
|
|
exp: number
|
|
}
|
|
|
|
export function generateAccessToken(user: UserInfo) {
|
|
return jwt.sign(user, ACCESS_TOKEN_SECRET, { expiresIn: '7d' })
|
|
}
|
|
|
|
export function generateRefreshToken(user: UserInfo) {
|
|
return jwt.sign(user, REFRESH_TOKEN_SECRET, {
|
|
expiresIn: '30d',
|
|
})
|
|
}
|
|
|
|
export function verifyAccessToken(
|
|
event: H3Event<EventHandlerRequest>,
|
|
): null | Omit<UserInfo, 'password'> {
|
|
const authHeader = getHeader(event, 'Authorization')
|
|
if (!authHeader?.startsWith('Bearer')) {
|
|
return null
|
|
}
|
|
|
|
const token = authHeader.split(' ')[1]
|
|
try {
|
|
const decoded = jwt.verify(token, ACCESS_TOKEN_SECRET) as UserPayload
|
|
|
|
const username = decoded.username
|
|
const user = MOCK_USERS.find((item) => item.username === username)
|
|
const { password: _pwd, ...userinfo } = user
|
|
return userinfo
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export function verifyRefreshToken(
|
|
token: string,
|
|
): null | Omit<UserInfo, 'password'> {
|
|
try {
|
|
const decoded = jwt.verify(token, REFRESH_TOKEN_SECRET) as UserPayload
|
|
const username = decoded.username
|
|
const user = MOCK_USERS.find((item) => item.username === username)
|
|
const { password: _pwd, ...userinfo } = user
|
|
return userinfo
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|