feat: 新增 Nitro Server API 与 PostgreSQL 后端,接入用户系统/联系表单/资讯订阅
- server/api: 注册/登录/登出/会话恢复(JWT + httpOnly Cookie, bcrypt 密码哈希) - server/api: 联系表单与资讯订阅入库,支持 SMTP 邮件通知(可选) - 应用启动自动建表(幂等),docker-compose 新增 PostgreSQL 16 服务 - 前端移除全部 mock:user store、登录注册弹窗、联系表单、页脚订阅接入真实接口 - i18n 补充服务端错误码中英文案,移除 demoHint - deploy: Deployment 环境变量(Secret 引用)、可选集群内 PostgreSQL(postgres.yaml) - 新增 .env.example 与 README/deploy 文档更新
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 统一 API 错误:抛出的 statusMessage 即前端 i18n 错误码(如 'auth.emailTaken')
|
||||
*/
|
||||
export function apiError(event: any, code: string, statusCode = 400): never {
|
||||
throw createError({
|
||||
statusCode,
|
||||
statusMessage: code,
|
||||
fatal: false,
|
||||
})
|
||||
}
|
||||
|
||||
/** 数据库用户行 -> 对外公开的用户对象 */
|
||||
export function toPublicUser(row: any) {
|
||||
return {
|
||||
id: Number(row.id),
|
||||
username: row.username,
|
||||
email: row.email,
|
||||
phone: row.phone ?? undefined,
|
||||
avatarUrl: row.avatar_url ?? undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 通用邮箱格式校验 */
|
||||
export function isValidEmail(email: string): boolean {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
||||
}
|
||||
|
||||
/** 通用手机号校验(中国大陆 11 位) */
|
||||
export function isValidPhone(phone: string): boolean {
|
||||
return /^1[3-9]\d{9}$/.test(phone)
|
||||
}
|
||||
|
||||
/** 用户名校验:2-50 位,中英文、数字、下划线 */
|
||||
export function isValidUsername(username: string): boolean {
|
||||
return /^[a-zA-Z0-9_\u4e00-\u9fa5]{2,50}$/.test(username)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { SignJWT, jwtVerify } from 'jose'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
export const AUTH_COOKIE_NAME = 'arcticnewone_token'
|
||||
export const JWT_MAX_AGE_SECONDS = 60 * 60 * 24 * 7 // 7 天
|
||||
|
||||
export interface AuthUserPayload {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
avatarUrl?: string | null
|
||||
}
|
||||
|
||||
function getSecretKey(): Uint8Array {
|
||||
const config = useRuntimeConfig()
|
||||
const secret = (config.jwtSecret as string) || 'dev-only-secret-change-in-production'
|
||||
return new TextEncoder().encode(secret)
|
||||
}
|
||||
|
||||
/** 签发 JWT */
|
||||
export async function signToken(user: AuthUserPayload): Promise<string> {
|
||||
return await new SignJWT({
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
avatarUrl: user.avatarUrl ?? null,
|
||||
})
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setSubject(String(user.id))
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${JWT_MAX_AGE_SECONDS}s`)
|
||||
.sign(getSecretKey())
|
||||
}
|
||||
|
||||
/** 校验 JWT,失败返回 null */
|
||||
export async function verifyToken(token: string): Promise<AuthUserPayload | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, getSecretKey())
|
||||
if (!payload.sub) return null
|
||||
return {
|
||||
id: Number(payload.sub),
|
||||
username: String(payload.username || ''),
|
||||
email: String(payload.email || ''),
|
||||
avatarUrl: payload.avatarUrl ? String(payload.avatarUrl) : null,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 从请求 Cookie 解析当前登录用户(未登录返回 null) */
|
||||
export async function getAuthUser(event: any): Promise<AuthUserPayload | null> {
|
||||
const token = getCookie(event, AUTH_COOKIE_NAME)
|
||||
if (!token) return null
|
||||
return await verifyToken(token)
|
||||
}
|
||||
|
||||
/** 写入登录 Cookie(httpOnly,生产环境自动启用 Secure) */
|
||||
export function setAuthCookie(event: any, token: string): void {
|
||||
const isProd = process.env.NODE_ENV === 'production'
|
||||
setCookie(event, AUTH_COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: isProd,
|
||||
path: '/',
|
||||
maxAge: JWT_MAX_AGE_SECONDS,
|
||||
})
|
||||
}
|
||||
|
||||
/** 清除登录 Cookie */
|
||||
export function clearAuthCookie(event: any): void {
|
||||
deleteCookie(event, AUTH_COOKIE_NAME, { path: '/' })
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
interface MailOptions {
|
||||
to?: string
|
||||
subject: string
|
||||
text: string
|
||||
html?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件。SMTP 未配置时仅记录日志(数据已入库,不阻塞业务)。
|
||||
* 环境变量: NUXT_SMTP_HOST / NUXT_SMTP_PORT / NUXT_SMTP_USER / NUXT_SMTP_PASS
|
||||
* NUXT_SMTP_FROM / NUXT_SMTP_CONTACT_TO
|
||||
*/
|
||||
export async function sendMail({ to, subject, text, html }: MailOptions): Promise<void> {
|
||||
const config = useRuntimeConfig()
|
||||
const smtp = config.smtp as { host?: string; port?: number; user?: string; pass?: string; from?: string; contactTo?: string }
|
||||
|
||||
if (!smtp?.host || !smtp?.user || !smtp?.pass) {
|
||||
console.log(`[mail] SMTP 未配置,跳过发送。主题: ${subject},收件人: ${to || smtp?.contactTo || '(未配置)'}`)
|
||||
return
|
||||
}
|
||||
|
||||
const port = Number(smtp.port) || 465
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: smtp.host,
|
||||
port,
|
||||
secure: port === 465,
|
||||
auth: { user: smtp.user, pass: smtp.pass },
|
||||
})
|
||||
|
||||
await transporter.sendMail({
|
||||
from: smtp.from || smtp.user,
|
||||
to: to || smtp.contactTo || smtp.user,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
})
|
||||
console.log(`[mail] 邮件已发送: ${subject} -> ${to || smtp.contactTo}`)
|
||||
}
|
||||
Reference in New Issue
Block a user