提交正式官网
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
export function md5(text: string): string {
|
||||
return createHash('md5').update(text).digest('hex')
|
||||
}
|
||||
|
||||
export function generateToken(userId: string | number): string {
|
||||
return `token_${userId}_${Date.now()}_${Math.random().toString(36).slice(2, 15)}`
|
||||
}
|
||||
|
||||
export function getUserIdFromToken(token: string | null): string | null {
|
||||
if (!token?.startsWith('token_')) return null
|
||||
const rest = token.slice('token_'.length)
|
||||
const timestampIndex = rest.search(/_\d+_/)
|
||||
if (timestampIndex <= 0) return null
|
||||
return rest.slice(0, timestampIndex)
|
||||
}
|
||||
|
||||
export function extractToken(event: H3Event): string | null {
|
||||
const authHeader = getHeader(event, 'authorization')
|
||||
if (!authHeader) return null
|
||||
if (authHeader.startsWith('Bearer ')) return authHeader.slice(7)
|
||||
return authHeader
|
||||
}
|
||||
|
||||
export function requireAuth(event: H3Event): { userId: string } | null {
|
||||
const token = extractToken(event)
|
||||
if (!token || !token.startsWith('token_')) return null
|
||||
const userId = getUserIdFromToken(token)
|
||||
if (!userId) return null
|
||||
return { userId }
|
||||
}
|
||||
|
||||
/** 当前时间字符串(固定东八区,与官网用户/后台展示一致) */
|
||||
export function nowStr(): string {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).formatToParts(new Date())
|
||||
|
||||
const get = (type: Intl.DateTimeFormatPartTypes) =>
|
||||
parts.find((part) => part.type === type)?.value ?? '00'
|
||||
|
||||
return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}:${get('second')}`
|
||||
}
|
||||
Reference in New Issue
Block a user