import {verify} from './passwordAuthentication.js';
import {setJwtCookie} from './middlewareAuthentication.js';

export async function logUserIn(req, res, db) {
    const username = req.body.username;
    const password = req.body.password;

    return new Promise(async (resolve, reject) => {
        try {
            const user = await db.getUserWithPassword(username);

            if (!user) {
                reject('User does not exist');
            }

            if (await verify(password, user.storedPassword)) {
                setJwtCookie({username}, res);
                resolve();
            } else {
                reject('Invalid password');
            }
        } catch (e) {
            reject(e);
        }
    });
}