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

Implemented JWT Authentication for User login and registration #69

Closed
Closed
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
41 changes: 41 additions & 0 deletions backend/middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import jwt from 'jsonwebtoken';
import User from '../models/userModel.js';

const authRoute = async (req, res, next) => {
try {
const token = req.cookies.jwt;

if (!token) {
return res
.status(401)
.json({ error: 'Unauthorized - No Token Provided' });
}

const decoded = jwt.verify(token, process.env.JWT_SECRET);

Check failure on line 14 in backend/middlewares/authMiddleware.js

View workflow job for this annotation

GitHub Actions / eslint-backend

'process' is not defined

if (!decoded) {
return res
.status(401)
.json({ error: 'Unauthorized - Invalid Token' });
}

const user = await User.findById(decoded.userId).select('-password');

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

req.user = user;

next();
} catch (error) {
console.log(
'Error in middleware: ',
//@ts-expect-error error?.message is giving error due to ts configuration
error?.message || 'Invalid access token'
);
res.status(500).json({ error: 'Internal server error' });
}
};

export default authRoute;
21 changes: 21 additions & 0 deletions backend/models/userModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import mongoose from 'mongoose';

const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
},
{ timestamps: true }
);

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

export default User;
90 changes: 89 additions & 1 deletion backend/package-lock.json

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

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.4.0",
"ts-node": "^10.9.2",
"uuid": "^9.0.1"
Expand Down
10 changes: 10 additions & 0 deletions backend/routes/userRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express from 'express';
import authRoute from '../middlewares/authMiddleware';

const router = express.Router();

router.post('/register', authRoute);

router.post('/login', authRoute);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you using the authRoute function for the login route? Authentication will be done after the login (and token generation) of the user.

Copy link
Contributor Author

@ritwik-69 ritwik-69 Jun 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AadityanshuSingh sorry about that , I just kept it that way because the login controller was not yet made


export default router;
6 changes: 6 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ app.get('/', (req, res) => {
res.send('Hello from the backend!');
});

//routes

import userRoute from '../routes/userRoute.js';

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better if you wrote all the import statements in one place. You can then segregate those imports there by mentioning their use case (in this case routes) in the comments.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AadityanshuSingh true i just thought that keeping all the routes import together would make it look more organized

app.use('/api/v1/auth', userRoute);

app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Loading