Skip to content

Commit

Permalink
Create auth.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Dec 3, 2024
1 parent 15e5f2f commit 7b869ed
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/security/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// src/security/auth.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/User'); // Assuming you have a User model
require('dotenv').config();

const SALT_ROUNDS = 10;

async function registerUser (username, password) {
const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
const newUser = new User({ username, password: hashedPassword });
await newUser .save();
return newUser ;
}

async function authenticateUser (username, password) {
const user = await User.findOne({ username });
if (!user) throw new Error('User not found');

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) throw new Error('Invalid password');

const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
return { token, user };
}

function verifyToken(token) {
return jwt.verify(token, process.env.JWT_SECRET);
}

module.exports = { registerUser , authenticateUser , verifyToken };

0 comments on commit 7b869ed

Please sign in to comment.