Created
July 13, 2022 13:24
-
-
Save Mulperi/c863a35a41905d7667c51dd3510b94a2 to your computer and use it in GitHub Desktop.
simple jwt with mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
import jwt from 'jsonwebtoken'; | |
import bodyParser from 'body-parser'; | |
import bcrypt from 'bcrypt'; | |
import mongoose from 'mongoose'; | |
import 'dotenv/config'; // Import and configure dotenv. | |
import User from './user.js'; | |
const app = express(); | |
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies. | |
app.use(bodyParser.json()); // Parses json bodies. | |
const port = 5000; | |
const posts = [{ id: 1, title: 'title', body: 'body' }]; | |
app.post('/register', async (req, res) => { | |
const newUser = new User({ | |
email: req.body.email, | |
password: await bcrypt.hash(req.body.password, 10), | |
}); | |
await newUser.save(); | |
res.json(newUser); | |
}); | |
app.post('/login', async (req, res) => { | |
const { email, password } = req.body; | |
const user = await User.findOne({ email }); | |
const passwordsMatch = | |
email && password ? await bcrypt.compare(password, user.password) : false; | |
if (passwordsMatch) { | |
const token = jwt.sign( | |
{ | |
data: 'foobar', | |
}, | |
process.env.JWT_SECRET, | |
{ expiresIn: '1h' } | |
); | |
return res.json({ user: user, token: token }); | |
} else { | |
return res | |
.status(501) | |
.json({ message: 'Login error, provide correct email and password.' }); | |
} | |
}); | |
async function main() { | |
await mongoose.connect('mongodb://localhost:27017/blog'); | |
console.log('Connected to db'); | |
app.listen(port, () => { | |
console.log(`Example app listening on port ${port}`); | |
}); | |
} | |
await main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment