HotTRDealsBackend/services/auth.service.js
2026-01-23 17:28:21 +00:00

86 lines
1.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const bcrypt = require("bcryptjs");
const generateToken = require("../utils/generateToken");
const authDb = require("../db/auth.db");
async function login({ email, password }) {
const user = await authDb.findUserByEmail(email);
if (!user) {
const err = new Error("Kullanıcı bulunamadı.");
err.statusCode = 400;
throw err;
}
const isMatch = await bcrypt.compare(password, user.passwordHash);
if (!isMatch) {
const err = new Error("Şifre hatalı.");
err.statusCode = 401;
throw err;
}
const token = generateToken(user.id);
return {
token,
user: {
id: user.id,
username: user.username,
email: user.email,
avatarUrl: user.avatarUrl,
},
};
}
async function register({ username, email, password }) {
const existingUser = await authDb.findUserByEmail(email);
if (existingUser) {
const err = new Error("Bu e-posta zaten kayıtlı.");
err.statusCode = 400;
throw err;
}
const passwordHash = await bcrypt.hash(password, 10);
const user = await authDb.createUser({
username,
email,
passwordHash,
});
const token = generateToken(user.id);
return {
token,
user: {
id: user.id,
username: user.username,
email: user.email,
avatarUrl: user.avatarUrl ?? null,
},
};
}
async function getMe(userId) {
const user = await authDb.findUserById(userId, {
select: {
id: true,
username: true,
email: true,
avatarUrl: true,
},
});
if (!user) {
const err = new Error("Kullanıcı bulunamadı");
err.statusCode = 404;
throw err;
}
return user;
}
module.exports = {
login,
register,
getMe,
};