All files / daos users.ts

80% Statements 16/20
50% Branches 3/6
83.33% Functions 5/6
80% Lines 16/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67  1x   1x 1x   1x 1x                     1x   1x                     1x                 3x     3x         3x 3x 3x         3x 1x   2x                
import { MyModels } from "../models";
import { literal, Transaction, UniqueConstraintError } from "sequelize";
import { UserAttributes } from "../models/Users";
import { ConflictError, InvalidKeyError, NotFoundError } from "../types/errors";
import { generateSalt, hashPassword } from "../utils/hashing";
 
export default function({ Users, sequelize }: MyModels) {
    return {
        /**
         * Posts a new user
         *
         * @param salt
         * @param passwordHash
         * @return the created userID
         */
        postOne: async (
            salt: string,
            passwordHash: string,
        ) => {
            // Perform transaction
            const user = await Users.create({
                passwordHash,
                salt,
            }).catch(e => {
                if (e instanceof UniqueConstraintError)
                    throw new ConflictError(
                        "A user with this hash already exists",
                    );
                else throw e;
            });
            //this is probably redundant, but it's here now
            return user.userID;
        },
        /**
         * validates the user input to see if it's accurate
         *
         * @param userWords
         * @param userID
         * @return if the user exists
         */
        getOne: async (userWords: string, userID: number) => {
            // Does't Perform transaction, since nothing is getting written
            // Check that the userHash and the salted hash are both nice
            const match = await Users.findOne({
                where: {
                    userID,
                },
            });
            Eif (match != null) {
                const passwordHash = await hashPassword(match.salt, userWords);
                const validate = await Users.findOne({
                    where: {
                        passwordHash,
                    },
                });
                if (validate !== null) {
                    return validate.userID;
                } else {
                    throw new NotFoundError("No such user exists");
                }
            } else {
                throw new NotFoundError("No such user exists");
            }
        },
    };
}