94 lines
1.9 KiB
TypeScript
94 lines
1.9 KiB
TypeScript
import crypto from "crypto";
|
|
import bcrypt from "bcrypt";
|
|
import { v4 as uuidv4 } from "uuid";
|
|
import { Request, Response } from "express";
|
|
import Session from "../models/session";
|
|
import {
|
|
DEFAULT_SESSION_EXPIRY,
|
|
HEADER_X_AUTHORIZATION,
|
|
USER_SESSION_LENGTH,
|
|
} from "./constants";
|
|
|
|
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 function newUserId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export function newStoreId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export function newStoreServiceId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export function newStoreServiceActivityId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export function newUserSession() {
|
|
return crypto.randomBytes(USER_SESSION_LENGTH).toString("hex");
|
|
}
|
|
|
|
export function newSessionId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export function newFeedbackId() {
|
|
return uuidv4();
|
|
}
|
|
|
|
export async function saveSession(
|
|
req: Request,
|
|
res: Response,
|
|
userId: string,
|
|
username: string
|
|
) {
|
|
try {
|
|
const userSession = newUserSession();
|
|
|
|
await Session.create({
|
|
user_id: userId,
|
|
session_id: userSession,
|
|
id: newSessionId(),
|
|
browser: req.useragent?.browser as string,
|
|
os: req.useragent?.os as string,
|
|
last_used: new Date(),
|
|
expires: new Date(Date.now() + DEFAULT_SESSION_EXPIRY),
|
|
});
|
|
|
|
res.status(200).json({
|
|
XAuthorization: userSession,
|
|
Username: username,
|
|
});
|
|
} catch (err) {
|
|
console.log(err);
|
|
res.status(500).send({ err: "invalid request" });
|
|
}
|
|
}
|
|
|
|
export async function getUserSession(req: Request) {
|
|
const sessionId = req.get(HEADER_X_AUTHORIZATION);
|
|
|
|
if (!sessionId) {
|
|
return null;
|
|
}
|
|
|
|
return await Session.findOne({
|
|
where: {
|
|
session_id: sessionId,
|
|
},
|
|
});
|
|
}
|