Skip to content

Commit ff4ab46

Browse files
Merge branch 'manual'
2 parents c0a8735 + abefb2c commit ff4ab46

9 files changed

Lines changed: 1326 additions & 0 deletions

File tree

User.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const mongoose = require('./db');
2+
3+
const UserSchema = new mongoose.Schema({
4+
username: String,
5+
password: String,
6+
});
7+
8+
module.exports = mongoose.model('User', UserSchema);

authController.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const express = require('express');
2+
const router = express.Router();
3+
const bcrypt = require('bcryptjs');
4+
const jwt = require('jsonwebtoken');
5+
const User = require('./User');
6+
const multer = require('multer');
7+
const upload = multer();
8+
9+
router.post('/signup', upload.none(), async (req, res) => {
10+
const { username, password } = req.body;
11+
12+
if (!username || !password) {
13+
return res.status(400).send('Username and password are required');
14+
}
15+
16+
const hashedPassword = await bcrypt.hash(password, 10);
17+
const user = new User({ username, password: hashedPassword });
18+
await user.save();
19+
res.sendStatus(201);
20+
});
21+
22+
router.post('/login', upload.none(), async (req, res) => {
23+
const user = await User.findOne({ username: req.body.username });
24+
if (!user || !await bcrypt.compare(req.body.password, user.password)) {
25+
return res.sendStatus(401);
26+
}
27+
const token = jwt.sign({ _id: user._id }, process.env.SECRET_KEY);
28+
res.send({ token });
29+
});
30+
31+
module.exports = router;

authMiddleware.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const jwt = require('jsonwebtoken');
2+
3+
module.exports = (req, res, next) => {
4+
const authHeader = req.headers['authorization'];
5+
if (!authHeader || !authHeader.startsWith('Bearer ')) {
6+
return res.sendStatus(401);
7+
}
8+
9+
const token = authHeader.split(' ')[1];
10+
jwt.verify(token, process.env.SECRET_KEY, (err, user) => {
11+
if (err) return res.sendStatus(403);
12+
req.user = user;
13+
next();
14+
});
15+
};

db.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const mongoose = require('mongoose');
2+
3+
mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true, useUnifiedTopology: true });
4+
5+
module.exports = mongoose;

0 commit comments

Comments
 (0)