80 lines
1.9 KiB
TypeScript
80 lines
1.9 KiB
TypeScript
import crypto from "crypto";
|
|
import { Session } from "../models/session";
|
|
import { Request, Response } from "express";
|
|
import bcrypt from "bcrypt";
|
|
import { HEADER_X_AUTHORIZATION, MONGODB_IGNORED_FIELDS } from "./constants";
|
|
import { User } from "../models/user";
|
|
|
|
export async function saveSession(
|
|
res: Response,
|
|
userId: string,
|
|
username: string
|
|
) {
|
|
try {
|
|
// Generate a random session ID
|
|
const sessionId = crypto.randomBytes(32).toString("hex");
|
|
|
|
// Create a new session document
|
|
const session = new Session({
|
|
sessionId: sessionId,
|
|
userId: userId,
|
|
});
|
|
|
|
// Save the session to MongoDB
|
|
await session.save();
|
|
|
|
// Respond with the session ID
|
|
res
|
|
.status(200)
|
|
.json({ XAuthorization: sessionId, UserId: userId, Username: username });
|
|
} catch (error) {
|
|
console.error("Error saving session:", error);
|
|
res.status(500).json({ status: "err" });
|
|
}
|
|
}
|
|
|
|
export async function matchPassword(decodedPassword: string, password: string) {
|
|
return await bcrypt.compare(decodedPassword, password);
|
|
}
|
|
|
|
export async function hashPassword(password: string) {
|
|
return await bcrypt.hash(password, 10);
|
|
}
|
|
|
|
export function decodeBase64(value: string) {
|
|
return Buffer.from(value, "base64").toString("utf-8");
|
|
}
|
|
|
|
export async function getUserSession(req: Request, select?: string) {
|
|
// Get the session ID from the request headers
|
|
const sessionId = req.get(HEADER_X_AUTHORIZATION);
|
|
|
|
if (!sessionId) {
|
|
return null;
|
|
}
|
|
|
|
// Find the session in MongoDB
|
|
const session = await Session.findOne({ sessionId })
|
|
.select(`sessionId -_id ${select}`)
|
|
.lean();
|
|
|
|
// Return the session
|
|
if (!session) {
|
|
return null;
|
|
}
|
|
|
|
return session;
|
|
}
|
|
|
|
export async function getUser(userId: string, select?: string) {
|
|
const user = await User.findOne({ userId: userId })
|
|
.select(select ? select : "")
|
|
.lean();
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
return user;
|
|
}
|