first commit
This commit is contained in:
54
app/lib/jwt.ts
Normal file
54
app/lib/jwt.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import jwt, { SignOptions } from "jsonwebtoken";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || process.env.BETTER_AUTH_SECRET || "fallback-secret-key";
|
||||
const API_KEY_PREFIX = "img_";
|
||||
|
||||
export interface JWTPayload {
|
||||
userId: string;
|
||||
email: string;
|
||||
type: "access" | "refresh";
|
||||
}
|
||||
|
||||
/**
|
||||
* JWT token oluştur
|
||||
* @param payload - Token içeriği
|
||||
* @param expiresIn - Geçerlilik süresi (örn: "7d", "1h")
|
||||
*/
|
||||
export function signJWT(payload: JWTPayload, expiresIn: string | number = "7d"): string {
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn } as SignOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* JWT token doğrula
|
||||
* @param token - Doğrulanacak token
|
||||
*/
|
||||
export function verifyJWT(token: string): JWTPayload | null {
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload;
|
||||
return decoded;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* API key oluştur
|
||||
* Formad: img_xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
*/
|
||||
export function generateAPIKey(): string {
|
||||
return `${API_KEY_PREFIX}${nanoid(32)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* API key validasyonu
|
||||
*/
|
||||
export function isValidAPIKeyFormat(key: string): boolean {
|
||||
return key.startsWith(API_KEY_PREFIX) && key.length === 36; // img_ + 32 chars
|
||||
}
|
||||
|
||||
/** Liste/detay için tam anahtarı göstermez (img_xxxx…yyyy) */
|
||||
export function maskApiKey(key: string): string {
|
||||
if (key.length < 12) return "img_••••";
|
||||
return `${key.slice(0, 7)}…${key.slice(-4)}`;
|
||||
}
|
||||
Reference in New Issue
Block a user