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

login and signup api with jwt authentication #124

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions server/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGODB_URL=mongodb://localhost:27017/contribute # This is the URL to connect to the MongoDB database
JWT_SECRET=secret # This is the secret key used to sign the JWT tokens
PORT=3000 # This is the port the server will run on
2 changes: 2 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
.env
87 changes: 87 additions & 0 deletions server/controller/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
import dotenv from "dotenv";
dotenv.config();

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

try {
const userexist = await User.findOne({
email,
});

if (!userexist) {
return res.status(422).json({
message: "User does not exist",
});
}

const isPasswordCorrect = await bcrypt.compare(
password,
userexist.password
);
if (!isPasswordCorrect) {
return res.status(422).json({
message: "Invalid Password",
});
}

const token = jwt.sign(
{ email: userexist.email, id: userexist._id },
process.env.JWT_SECRET,
{ expiresIn: "7d" }
);
return res.status(200).json({
message: "Login Successfull",
token,
user: {
email: userexist.email,
id: userexist._id,
},
});
} catch (error) {
console.log(error);

return res.status(500).json({
message: "internal Server Error",
});
}
};

export const signupUser = async (req, res) => {
const { email, password, firstName, lastName } = req.body;

try {
const userexist = await User.findOne({
email,
});

if (userexist) {
return res.status(422).json({
message: "User already exist",
});
}

console.log(req.body);

const hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
const user = await User.create({
email,
password: hashedPassword,
firstName,
lastName,
});
res.status(200).json({
message: "User Created Successfully",
user,
});
} catch (error) {
console.log(error);
return res.status(500).json({
message: "Signup Failed",
});
}
};
2 changes: 2 additions & 0 deletions server/dbConfig/dbConnection.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();

const dbConnection = async () => {
try {
Expand Down
32 changes: 32 additions & 0 deletions server/middleware/jwtverfiy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import jwt from "jsonwebtoken";


const jwtVerfy = async (req,res,next) => {
const token = req.headers.authorization;

if(!token){
return res.status(401).json({
message: "token not found"
})
}

const authToken = token.split(" ")[1];

try {
const decoded = jwt.verify(authToken, process.env.JWT_SECRET);
if(decoded){
req.user = decoded;
next();
}
else
{
throw new Error("invalid token or expired token");
}
} catch (error) {
console.error("jwt error", error.message);
return res.status(401).json({
message: "invalid token or expired token"
})
}
}
export default jwtVerfy;
22 changes: 11 additions & 11 deletions server/models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
import mongoose from "mongoose";
import validator from "validator";
import bcrypt from "bcryptjs";
import JWT from "jsonwebtoken"

const userSchema = new mongoose.Schema({
firstName:{
type:String,
required :[true, "First Name is required"]
required :true
},
lastName:{
type:String,
required :[true, "Last Name is required"]
required :true
},
email:{
type:String,
required :[true, "Email Name is required"],
required :true,
unique: true, //checks if the email already exists in database or not
validate: validator.isEmail
},
password:{
type:String,
required :[true, "Password is required"],
minlength: [6, "Password must be at least"],
required :true,
minlength: 6,
select: true,
},

accountType:{
type: String,
default:"seeker"
}
});
});


const User = mongoose.model("User", userSchema);

export default User;
Loading