Repository navigation
Expand file tree
/
Copy pathauthController.js
More file actions
47 lines (37 loc) · 1.55 KB
/
Copy pathauthController.js
File metadata and controls
47 lines (37 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const User = require('../models/User');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// Sign Up
exports.signup = async (req, res) => {
const { username, email, password, birthday } = req.body;
try {
// Check if the user already exists
const existingUser = await User.findOne({ email });
if (existingUser) return res.status(400).json({ error: 'User already exists' });
// Hash the password
const hashedPassword = await bcrypt.hash(password, 12);
// Create a new user
const user = new User({ username, email, password: hashedPassword, birthday });
await user.save();
res.status(201).json({ message: 'User created successfully' });
} catch (err) {
res.status(500).json({ error: 'Server error' });
}
};
// Sign In
exports.signin = async (req, res) => {
const { username, password } = req.body;
try {
// Check if the user exists
const user = await User.findOne({ username });
if (!user) return res.status(400).json({ error: 'Invalid credentials' });
// Validate password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ error: 'Invalid credentials' });
// Generate JWT token
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
} catch (err) {
res.status(500).json({ error: 'Server error' });
}
};