-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
164 lines (129 loc) · 4.52 KB
/
auth.js
File metadata and controls
164 lines (129 loc) · 4.52 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import { pool } from "./database.js";
import {hashPassword, comparePassword,createToken, decodeToken, authenticateToken} from './encryption.js';
import dotenv from 'dotenv';
import bcrypt from 'bcrypt';
import { createClient } from 'redis';
import jkg from 'jsonwebtoken';
const jwt = jkg;
const JWT_SECRET = process.env.JWT_SECRET ;
export async function register(userData) {
const client = await pool.connect();
try {
const { username, name, surname, tel, sex, birthday, email, password } = userData;
const hashpassword = await hashPassword(password);
const point = 0;
// 🔍 ตรวจสอบว่า username มีอยู่แล้วหรือไม่
const checkUser = await client.query(
"SELECT id FROM users WHERE username = $1",
[username]
);
if (checkUser.rowCount > 0) {
return { success: false, message: "Username already exists" };
}
const insertQuery = `
INSERT INTO users (username, name, surname, tel, sex, birthday, email, password, point)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, username, name, surname, tel, sex, birthday, email, point
`;
const values = [username, name, surname, tel, sex, birthday, email, hashpassword, point];
const result = await client.query(insertQuery, values);
const newUser = result.rows[0];
return {
success: true,
message: "User registered successfully",
user: newUser,
};
} catch (error) {
console.error("Registration error:", error);
throw new Error(`Registration failed: ${error.message}`);
} finally {
client.release();
}
}
export async function login(loginData) {
if (!pool) {
throw new Error('Database pool not initialized');
}
const client = await pool.connect();
try {
const { username, password } = loginData; // username can be username or email
// Input validation
if (!username || !password) {
throw new Error('Username/email and password are required');
}
// Check if username is email or username
const isEmail = username.includes('@');
// Query to find user by either username or email
const findUserQuery = isEmail
? `SELECT id, username, name, surname, tel, sex, birthday, email, password, point
FROM users WHERE email = $1`
: `SELECT id, username, name, surname, tel, sex, birthday, email, password, point
FROM users WHERE username = $1`;
const result = await client.query(findUserQuery, [username]);
// Check if user exists
if (result.rows.length === 0) {
throw new Error('Invalid credentials');
}
const user = result.rows[0];
// Verify password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
throw new Error('Invalid credentials');
}
// Generate JWT token
const token = jwt.sign(
{ id: user.id, username: user.username }, // ต้องมี id!
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Return user data (without password) and token
return {
success: true,
message: 'Login successful',
token,
user: {
id: user.id,
username: user.username,
name: user.name,
surname: user.surname,
tel: user.tel,
sex: user.sex,
birthday: user.birthday,
email: user.email,
point: user.point
}
};
} catch (error) {
console.error('Login error:', error);
throw new Error(`Login failed: ${error.message}`);
} finally {
client.release();
}
}
export async function checkUserExists(req, res) {
const { username, email } = req.body;
if (!username || !email) {
return res.status(400).json({ success: false, message: "Username and email required" });
}
try {
const result = await pool.query(
`SELECT username, email FROM users WHERE username = $1 OR email = $2`,
[username, email]
);
const conflicts = result.rows;
const conflictMessages = {
username: conflicts.find(u => u.username === username) ? 'Username already exists' : null,
email: conflicts.find(u => u.email === email) ? 'Email already exists' : null
};
if (conflictMessages.username || conflictMessages.email) {
return res.status(409).json({
success: false,
conflicts: conflictMessages
});
}
res.json({ success: true });
} catch (err) {
console.error("Check user exists error:", err);
res.status(500).json({ success: false, message: "Server error" });
}
}