Repository navigation
Expand file tree
/
Copy pathauthController.js
More file actions
97 lines (76 loc) · 1.96 KB
/
Copy pathauthController.js
File metadata and controls
97 lines (76 loc) · 1.96 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// controllers/authController.js
const pool = require('../config/db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
// REGISTER USER
const registerUser = async (req, res, next) => {
try {
const { email, password } = req.body;
// Check if user already exists
const existingUser = await pool.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
if (existingUser.rows.length > 0) {
return res.status(400).json({
status: 'error',
message: 'Email already registered'
});
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Insert user into database
const newUser = await pool.query(
'INSERT INTO users (email, password) VALUES ($1, $2) RETURNING id, email, created_at',
[email, hashedPassword]
);
res.status(201).json({
status: 'success',
data: newUser.rows[0]
});
} catch (error) {
next(error);
}
};
// LOGIN USER
const loginUser = async (req, res, next) => {
try {
const { email, password } = req.body;
// Check if user exists
const user = await pool.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
if (user.rows.length === 0) {
return res.status(401).json({
status: 'error',
message: 'Invalid email or password'
});
}
const existingUser = user.rows[0];
// Compare password with hashed password
const isMatch = await bcrypt.compare(password, existingUser.password);
if (!isMatch) {
return res.status(401).json({
status: 'error',
message: 'Invalid email or password'
});
}
// Generate JWT token
const token = jwt.sign(
{ userId: existingUser.id },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
res.json({
status: 'success',
token
});
} catch (error) {
next(error);
}
};
module.exports = {
registerUser,
loginUser
};