import { Db } from "mongodb";

import { IUserDBModel } from "../models/user";

export async function userFromSession(token: string, db: Db): Promise<IUserDBModel> {
    // Get the username
    const session = await db.collection("sessions").findOne({ token, });
    if (session) {
        const user = await db.collection("users").findOne({ username: session.username });
        if (user) {
            return user;
        } else {
            throw new Error("Failed to find user");
        }
    } else {
        throw new Error("Failed to find session");
    }
}
