-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathusers-controller.js
68 lines (56 loc) · 1.61 KB
/
users-controller.js
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
import {
createUser,
validateUser,
verifyUserCredentials,
} from "../models/user.js";
import { generateJWT } from "../util/auth.js";
// In-memory storage for users (temporary solution)
const users = [];
export async function signup(req, res) {
try {
const { email, password } = req.body;
// Validate user input
validateUser({ email, password });
// Check if user already exists
const existingUser = users.find((user) => user.email === email);
if (existingUser) {
return res.status(400).json({ message: "User already exists" });
}
// Create new user
const newUser = await createUser({ email, password });
users.push(newUser);
// Generate JWT token
const token = generateJWT(newUser);
res.status(201).json({
message: "User created",
userId: newUser.id,
token: token,
});
} catch (error) {
res.status(400).json({ message: error.message });
}
}
export async function login(req, res) {
try {
const { email, password } = req.body;
if (!email || !email.trim() || !password || !password.trim()) {
return res
.status(400)
.json({ message: "Email and password are required" });
}
// Verify user credentials
const user = await verifyUserCredentials({ email, password });
if (!user) {
return res.status(401).json({ message: "Authentication failed" });
}
// Generate JWT token
const token = generateJWT(user);
res.json({
message: "Login successful",
userId: user.id,
token: token,
});
} catch (error) {
res.status(400).json({ message: error.message });
}
}