Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/auth jwt #1

Merged
merged 10 commits into from
Jul 31, 2022
Merged
Prev Previous commit
Next Next commit
working on auth and jwt
  • Loading branch information
Daniel-Workman committed Jul 20, 2022
commit a9b79be6b7d7e235c4aafaab22f2cda9af622e2b
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18.3.0
49 changes: 49 additions & 0 deletions server/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";

dotenv.config();

import User from "../models/userModel.js";

export const createUser = async (req, res) => {
//destructure your user info from the request body object
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
//ensure the user doesn't already exist in the db before creating new user
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "User already exists" });
//although there should be client side validation, run on server as well to be sure
if (password !== confirmPassword)
return res.status(400).json({ message: "Passwords don't match" });

//create a hashed password using bcrypt
const hashedPassword = await bcrypt.hash(password, 12);
//create a document with the user data using the User Model
const result = await User.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`
});
//generate a jwt access token
//https://www.npmjs.com/package/jsonwebtoken
const accessToken = jwt.sign(
{ email: result.email, id: result._id },
process.env.ACCESS_TOKEN_SECRET
);
res.status(200).json({ accessToken: accessToken });
} catch (error) {
res.status(500).json({ message: "something went wrong" });
}
};

export const loginUser = async (req, res) => {
// const display = req.body
// .then(data => {
// console.log(data);
// })
// .catch(err => {
// console.log(err);
// });
};
13 changes: 13 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@ import cors from "cors";
import dotenv from "dotenv";
import mongoose from "mongoose";

import userRoutes from "./routes/userRoutes.js";

//get access to env variables
dotenv.config();
//initialise express
const app = express();
//allow the app to use json
app.use(express.json());
//allow the app to work with cors in local env
app.use(cors());
//set json data transfer limits
app.use(express.json({ limit: "30mb", extended: true }));
app.use(express.urlencoded({ limit: "30mb", extended: true }));

//set a port or use a default
const PORT = process.env.PORT || 5001;

//set routes for the app to use
app.use("/user", userRoutes);

//establish a connection to the db and initialise the server
mongoose
.connect(process.env.MONGODB)
.then(() =>
Expand Down
17 changes: 17 additions & 0 deletions server/models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import mongoose from "mongoose";
//destructure what we need from mongoose
const { Schema, model } = mongoose;

//create and define a new schema to use on the model
const userSchema = new Schema({
//https://mongoosejs.com/docs/api.html#schematype_SchemaType-required
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
id: { type: String }
});

//create the model.
//https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model
const User = model("User", userSchema, "users");
export default User;
2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "",
"main": "index.js",
"scripts": {
"devStart": "nodemon index.js",
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
Expand Down
11 changes: 11 additions & 0 deletions server/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import express from "express";
import { createUser, loginUser } from "../controllers/userController.js";

//initialise express router to gain access to all routing methods
const router = express.Router();

//create a get request pathway for the frontend to pull users playlists
router.post("/create-user", createUser);
router.post("/login-user", loginUser);

export default router;