Skip to content

Commit

Permalink
Merge branch 'manual'
Browse files Browse the repository at this point in the history
  • Loading branch information
dilshankarunarathne committed Apr 17, 2024
2 parents c0a8735 + abefb2c commit ff4ab46
Show file tree
Hide file tree
Showing 9 changed files with 1,326 additions and 0 deletions.
8 changes: 8 additions & 0 deletions User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('./db');

const UserSchema = new mongoose.Schema({
username: String,
password: String,
});

module.exports = mongoose.model('User', UserSchema);
31 changes: 31 additions & 0 deletions authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('./User');
const multer = require('multer');
const upload = multer();

router.post('/signup', upload.none(), async (req, res) => {
const { username, password } = req.body;

if (!username || !password) {
return res.status(400).send('Username and password are required');
}

const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, password: hashedPassword });
await user.save();
res.sendStatus(201);
});

router.post('/login', upload.none(), async (req, res) => {
const user = await User.findOne({ username: req.body.username });
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
return res.sendStatus(401);
}
const token = jwt.sign({ _id: user._id }, process.env.SECRET_KEY);
res.send({ token });
});

module.exports = router;
15 changes: 15 additions & 0 deletions authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.sendStatus(401);
}

const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
5 changes: 5 additions & 0 deletions db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const mongoose = require('mongoose');

mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true, useUnifiedTopology: true });

module.exports = mongoose;
Loading

0 comments on commit ff4ab46

Please sign in to comment.