diff options
author | Biswakalyan Bhuyan <biswa@surgot.in> | 2024-07-18 14:56:39 +0530 |
---|---|---|
committer | Biswakalyan Bhuyan <biswa@surgot.in> | 2024-07-18 14:56:39 +0530 |
commit | 2f613682b733f8f03634df08270469830cad1800 (patch) | |
tree | bab1e0c7b19aa9538bbcb099d7e5b36c1f264528 /server/routes | |
parent | 05faaf231620ce8d4ee67585bd86f1e97fd32eeb (diff) | |
download | admin-panel-2f613682b733f8f03634df08270469830cad1800.tar.gz admin-panel-2f613682b733f8f03634df08270469830cad1800.tar.bz2 admin-panel-2f613682b733f8f03634df08270469830cad1800.zip |
added the config and setup the basic auth
Diffstat (limited to 'server/routes')
-rw-r--r-- | server/routes/auth.js | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/server/routes/auth.js b/server/routes/auth.js new file mode 100644 index 0000000..3fb0986 --- /dev/null +++ b/server/routes/auth.js @@ -0,0 +1,61 @@ +const express = require('express'); +const bcrypt = require('bcryptjs'); +const jwt = require('jsonwebtoken'); +const User = require('../models/User'); +const router = express.Router(); + +// Register +router.post('/register', async (req, res) => { + const { username, password } = req.body; + try { + let user = await User.findOne({ username }); + if (user) { + return res.status(400).json({ msg: 'User already exists' }); + } + user = new User({ + username, + password, + }); + const salt = await bcrypt.genSalt(10); + user.password = await bcrypt.hash(password, salt); + await user.save(); + res.status(200).send('User registered'); + } catch (err) { + console.error(err.message); + res.status(500).send('Server error'); + } +}); + +// Login +router.post('/login', async (req, res) => { + const { username, password } = req.body; + try { + const user = await User.findOne({ username }); + if (!user) { + return res.status(400).json({ msg: 'Invalid credentials' }); + } + const isMatch = await bcrypt.compare(password, user.password); + if (!isMatch) { + return res.status(400).json({ msg: 'Invalid credentials' }); + } + const payload = { + user: { + id: user.id, + }, + }; + jwt.sign( + payload, + process.env.JWT_SECRET, + { expiresIn: '1h' }, + (err, token) => { + if (err) throw err; + res.json({ token }); + } + ); + } catch (err) { + console.error(err.message); + res.status(500).send('Server error'); + } +}); + +module.exports = router; |