Skip to content

Commit

Permalink
add create user and login routes
Browse files Browse the repository at this point in the history
  • Loading branch information
WillzMu committed Oct 15, 2020
1 parent f60305b commit 3a31e44
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 34 deletions.
105 changes: 105 additions & 0 deletions backend/controllers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const User = require("../models/users");
const jwt = require('jsonwebtoken');
const { errors, hashPassword, comparePasswordHash } = require("../helpers");

/**
* @api {post} /user/create/ user/create
* @apiName trader/create
* @apiGroup Trader
*
* @apiDescription Creates a user.
*
* @apiParam {String} username username of user.
* @apiParam {String} email email of trader.
* @apiParam {String} password password of user.
*
* @apiParamExample {json} Request-Example:
* {
* "name": "test",
* "gender": "test",
* "email": "email@mmo.com",
* "picture": "test",
* "password": "test",
* "phoneNumber": "test",
* "birthDate": "01-01-1990",
* "location": "test",
* "tradingStyle": "test",
* "yearsOfExperience": "test",
* "brokersUsed": "test",
* "isCommittedToEndScams": true
*
* }
*
* @apiSuccess {String} message User created successfully..
*
* @apiSuccessExample {String} Success-Response:
*
* {
* "statusCode": 200,
* "message": "User created successfully."
* }
*
* @apiError (500 Internal server error) message Internal server error.
*
* @apiErrorExample Error-Response:
* {
* "statusCode": 500,
* "message": "Internal server error"
* }
*/

const createUser = async (req, res) => {
const {
username,
email,
password
} = req.body;

const hashedPassword = await hashPassword(password);

const trader = new User({
username,
email,
password: hashedPassword,

});
try {
await trader.save();
return res.json({
statuCode: 200,
message: "User created successfully.",
});
} catch (error) {
console.log(error);
}
return res.json({ statusCode: 500, message: errors.internal_server_error });
};

const login = async (req, res) => {
const { username, password } = req.body

try {
const result = await User.find({ username })
if(result) {
const user = result[0]
const matched = await comparePasswordHash(password, user.password)
if (!matched) return res.json({ statusCode: 412, message: errors.current_password_incorrect })

req.user = { authorized: true }

const accessToken = jwt.sign( { username: user.username, email: user.email }, `${process.env.ACCESS_TOKEN_SECRET}`, { expiresIn : '1h' }) // expires in an hour
return res.json({ statusCode: 200, message: { accessToken: accessToken }})
}

} catch (error) {
console.log(error)
}

return res.json({ statusCode: 500, message: errors.internal_server_error });
}

module.exports = {
createUser,
login
}
1 change: 1 addition & 0 deletions backend/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const bcrypt = require('bcrypt')
const errors = {
missing_mandatory_paramaters: "Missing mandatory parameters",
internal_server_error: "Internal server error",
current_password_incorrect: 'Current password is incorrect',
};

const success = {
Expand Down
3 changes: 1 addition & 2 deletions backend/models/users.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
name: {
username: {
type: String,
required: true,
trim: true,
Expand All @@ -15,7 +15,6 @@ const userSchema = new mongoose.Schema({
type: String,
required: true,
},

created: {
type: Date,
default: Date.now(),
Expand Down
2 changes: 2 additions & 0 deletions backend/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const useInvestors = require("./investors");
const useTraders = require("./traders");
const useUsers = require("./users");

module.exports = (router) => {
useInvestors(router, "/investor");
useTraders(router, "/trader");
useUsers(router, "/user");
};
6 changes: 6 additions & 0 deletions backend/routes/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const { createUser, login } = require("../controllers/users");

module.exports = (router, prefix) => {
router.post(`${prefix}/create`, createUser)
router.post(`${prefix}/login`, login)
};
32 changes: 0 additions & 32 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const express = require("express");
const cowsay = require("cowsay");
const cors = require("cors");
const path = require("path");
const mongoose = require("mongoose");
Expand Down Expand Up @@ -34,44 +33,13 @@ router(app);
// API docs
app.use("/apidoc", express.static("public/docs"));

// Serve our api route /cow that returns a custom talking text cow
app.get("/api/cow/:say", cors(), async (req, res, next) => {
try {
const text = req.params.say;
const moo = cowsay.say({ text });
res.json({ moo });
} catch (err) {
next(err);
}
});

// Serve our base route that returns a Hello World cow
app.get("/api/cow/", cors(), async (req, res, next) => {
try {
const moo = cowsay.say({ text: "Hello World!" });
res.json({ moo });
} catch (err) {
next(err);
}
});

// Anything that doesn't match the above, send back index.html
app.get("*", (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/index.html`));
});

//setup tokens for Authetication using jwt
app.post('/login', (req, res)=>{
//Authenticate User

const username = req.body.username
const user ={name: username}

const accessToken = jwt.sign( user,
process.env.ACCESS_TOKEN_SECRET, {expiresIn : '1h'})

req.json({accessToken: accessToken})
})

function authenticatetoken ( req, res, next) {
const authHeader = req.headers['authorization']
Expand Down

0 comments on commit 3a31e44

Please sign in to comment.