Checkpoint: Migration OAuth Manus vers authentification locale (80% complété) - Pages login/register créées, backend JWT implémenté, guides de déploiement ajoutés. Reste à corriger les doublons dans db.ts et finaliser AdminUsers.
This commit is contained in:
43
server/_core/auth.ts
Normal file
43
server/_core/auth.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import bcrypt from "bcrypt";
|
||||
import { sign, verify } from "jsonwebtoken";
|
||||
import { ENV } from "./env";
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
/**
|
||||
* Hashe un mot de passe avec bcrypt
|
||||
*/
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, SALT_ROUNDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie un mot de passe contre son hash
|
||||
*/
|
||||
export async function verifyPassword(
|
||||
password: string,
|
||||
hash: string
|
||||
): Promise<boolean> {
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Génère un token JWT pour un utilisateur
|
||||
*/
|
||||
export function generateToken(userId: number): string {
|
||||
return sign({ userId }, ENV.jwtSecret, {
|
||||
expiresIn: "30d",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie et décode un token JWT
|
||||
*/
|
||||
export function verifyToken(token: string): { userId: number } | null {
|
||||
try {
|
||||
const decoded = verify(token, ENV.jwtSecret) as { userId: number };
|
||||
return decoded;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express";
|
||||
import type { User } from "../../drizzle/schema";
|
||||
import { sdk } from "./sdk";
|
||||
import { verifyToken } from "./auth";
|
||||
import { getUserById } from "../db";
|
||||
import { COOKIE_NAME } from "@shared/const";
|
||||
|
||||
export type TrpcContext = {
|
||||
req: CreateExpressContextOptions["req"];
|
||||
@@ -14,7 +16,18 @@ export async function createContext(
|
||||
let user: User | null = null;
|
||||
|
||||
try {
|
||||
user = await sdk.authenticateRequest(opts.req);
|
||||
// Récupérer le token JWT depuis le cookie
|
||||
const token = opts.req.cookies[COOKIE_NAME];
|
||||
|
||||
if (token) {
|
||||
// Vérifier et décoder le token
|
||||
const decoded = verifyToken(token);
|
||||
|
||||
if (decoded) {
|
||||
// Récupérer l'utilisateur depuis la base de données
|
||||
user = await getUserById(decoded.userId) || null;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Authentication is optional for public procedures.
|
||||
user = null;
|
||||
|
||||
Reference in New Issue
Block a user