Added login route, updated readme
This commit is contained in:
1 parent
4f3bbb2f88
commit
e7a58f2756
6 files changed
+272
-55
No files matched your search
@@ -1,7 +1,7 @@
|
||||
const express = require("express");
|
||||
const UserModel = require("../models/user");
|
||||
const { registerValidation } = require("../validation/joi");
|
||||
const logger = require('../utils/logger')
|
||||
const { registerValidation, loginValidation } = require("../validation/joi");
|
||||
const logger = require("../utils/logger");
|
||||
|
||||
/**
|
||||
* @function
|
||||
@@ -23,28 +23,73 @@ const registerController = async (req, res) => {
|
||||
try {
|
||||
const isUser = await req.db.getUserByEmail(req, res);
|
||||
if (isUser) {
|
||||
logger.warning("User already exists!", { "service": "auth", "userId": isUser._id });
|
||||
logger.error("User already exists!", {
|
||||
service: "auth",
|
||||
userId: isUser._id,
|
||||
});
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, msg: "User already exists!" });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error.message, { "service": "auth" });
|
||||
logger.error(error.message, { service: "auth" });
|
||||
return res.status(500).json({ success: false, msg: error.message });
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
// Create a new user
|
||||
const newUser = await req.db.insertUser(req, res);
|
||||
// TODO: Send an email to user
|
||||
// Will add this later
|
||||
logger.info("New user created!", { "service": "auth", "userId": newUser._id });
|
||||
return res.json({ success: true, msg: "User created}", data: newUser });
|
||||
logger.info("New user created!", { service: "auth", userId: newUser._id });
|
||||
return res
|
||||
.status(200)
|
||||
.json({ success: true, msg: "User created}", data: newUser });
|
||||
} catch (error) {
|
||||
logger.error(error.message, { "service": "auth" });
|
||||
logger.error(error.message, { service: "auth" });
|
||||
return res.status(500).json({ success: false, msg: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { registerController };
|
||||
// **************************
|
||||
// Handles logging in a user
|
||||
// Returns a user at the moment, but will likely return a JWT in the future
|
||||
// **************************
|
||||
const loginController = async (req, res) => {
|
||||
try {
|
||||
// Validate input
|
||||
await loginValidation.validateAsync(req.body);
|
||||
|
||||
// Check if user exists
|
||||
const user = await req.db.getUserByEmail(req, res);
|
||||
|
||||
// If user not found, throw an error
|
||||
if (!user) {
|
||||
throw new Error("User not found!");
|
||||
}
|
||||
// Compare password
|
||||
const match = await user.comparePassword(req.body.password);
|
||||
console.log(user);
|
||||
if (!match) {
|
||||
throw new Error("Password does not match!");
|
||||
}
|
||||
|
||||
// Copy user to remove password. More memory, but better than mutating user?
|
||||
// We can move this to the DB layer if we want
|
||||
// Probably not neccessary at all as we'll likely return a JWT instead of a user
|
||||
const userWithoutPassword = { ...user._doc };
|
||||
delete userWithoutPassword.password;
|
||||
|
||||
// Happy path, return user
|
||||
// In the future we'll probably return a JWT instead of a user
|
||||
return res
|
||||
.status(200)
|
||||
.json({ success: true, msg: "Found user", data: userWithoutPassword });
|
||||
} catch (error) {
|
||||
// Anything else should be an error
|
||||
logger.error(error.message, { service: "auth" });
|
||||
return res.status(500).json({ success: false, msg: error.message });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { registerController, loginController };
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
const Monitor = require("../models/Monitor");
|
||||
const UserModel = require("../models/user");
|
||||
const bcrypt = require("bcrypt");
|
||||
|
||||
const FAKE_MONITOR_DATA = [];
|
||||
const USERS = [];
|
||||
@@ -52,6 +53,8 @@ const connect = async () => {
|
||||
const insertUser = async (req, res) => {
|
||||
try {
|
||||
const newUser = new UserModel({ ...req.body });
|
||||
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
|
||||
newUser.password = await bcrypt.hash(newUser.password, salt); // hash is also async, need to eitehr await or use hashSync
|
||||
USERS.push(newUser);
|
||||
return newUser;
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const Monitor = require("../models/Monitor");
|
||||
const mongoose = require("mongoose");
|
||||
const UserModel = require("../models/user");
|
||||
const user = require("../models/user");
|
||||
|
||||
const connect = async () => {
|
||||
try {
|
||||
@@ -14,18 +15,22 @@ const connect = async () => {
|
||||
|
||||
const insertUser = async (req, res) => {
|
||||
try {
|
||||
const newUser = await UserModel.create({ ...req.body }).select('-password');
|
||||
return newUser;
|
||||
const newUser = new UserModel({ ...req.body });
|
||||
await newUser.save();
|
||||
return await UserModel.findOne({ _id: newUser._id }).select("-password"); // .select() doesn't work with create, need to save then find
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// Gets a user by Email. Not sure if we'll ever need this except for login.
|
||||
// If not needed except for login, we can move password comparison here
|
||||
const getUserByEmail = async (req, res) => {
|
||||
try {
|
||||
// Returns null if no user is found
|
||||
const user = await UserModel.findOne({ email: req.body.email }).select('-password');
|
||||
return user;
|
||||
// Need the password to be able to compare, removed .select()
|
||||
// We can strip the hash before returing the user
|
||||
return await UserModel.findOne({ email: req.body.email });
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,13 @@ UserSchema.pre("save", async function (next) {
|
||||
next();
|
||||
}
|
||||
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
|
||||
this.password = bcrypt.hash(this.password, salt);
|
||||
this.password = await bcrypt.hash(this.password, salt); // hash is also async, need to eitehr await or use hashSync
|
||||
next();
|
||||
});
|
||||
|
||||
UserSchema.methods.comparePassword = function (submittedPassword) {
|
||||
console.log(submittedPassword, this.password);
|
||||
return bcrypt.compare(submittedPassword, this.password);
|
||||
};
|
||||
|
||||
module.exports = mongoose.model("User", UserSchema);
|
||||
@@ -1,6 +1,10 @@
|
||||
const router = require('express').Router();
|
||||
const { registerController } = require('../controllers/authController')
|
||||
const router = require("express").Router();
|
||||
const {
|
||||
registerController,
|
||||
loginController,
|
||||
} = require("../controllers/authController");
|
||||
|
||||
router.post('/register', registerController)
|
||||
router.post("/register", registerController);
|
||||
router.post("/login", loginController);
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
Reference in new issue
Block a user