Refactor database configuration and enhance error handling in authentication services
Updated the database configuration to centralize settings and improve maintainability. Enhanced error handling in the authentication service to provide clearer and more specific error messages for various failure scenarios, including registration, activation, and login processes. Additionally, added new dependencies for testing and SQLite support in the package.json file.
This commit is contained in:
@@ -13,13 +13,24 @@ const register = async (email, password) => {
|
||||
return user;
|
||||
} catch (error) {
|
||||
devLog(error);
|
||||
return null;
|
||||
if (error.name === 'SequelizeUniqueConstraintError') {
|
||||
const err = new Error('E-Mail-Adresse wird bereits verwendet');
|
||||
err.status = 409;
|
||||
throw err;
|
||||
}
|
||||
const err = new Error('Registrierung fehlgeschlagen');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
const activateUser = async (activationCode) => {
|
||||
const user = await User.findOne({ where: { activationCode } });
|
||||
if (!user) throw new Error('Invalid activation code');
|
||||
if (!user) {
|
||||
const err = new Error('Aktivierungscode ungültig');
|
||||
err.status = 404;
|
||||
throw err;
|
||||
}
|
||||
user.isActive = true;
|
||||
user.activationCode = null;
|
||||
await user.save();
|
||||
@@ -28,11 +39,21 @@ const activateUser = async (activationCode) => {
|
||||
|
||||
const login = async (email, password) => {
|
||||
if (!email || !password) {
|
||||
throw { status: 400, message: 'Email und Passwort sind erforderlich.' };
|
||||
const err = new Error('Email und Passwort sind erforderlich.');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
const user = await User.findOne({ where: { email } });
|
||||
if (!user || !(await bcrypt.compare(password, user.password))) {
|
||||
throw { status: 401, message: 'Ungültige Anmeldedaten' };
|
||||
const validPassword = user && await bcrypt.compare(password, user.password);
|
||||
if (!validPassword) {
|
||||
const err = new Error('Ungültige Anmeldedaten');
|
||||
err.status = 401;
|
||||
throw err;
|
||||
}
|
||||
if (!user.isActive) {
|
||||
const err = new Error('Account wurde noch nicht aktiviert');
|
||||
err.status = 403;
|
||||
throw err;
|
||||
}
|
||||
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '3h' });
|
||||
await UserToken.create({
|
||||
@@ -45,7 +66,9 @@ const login = async (email, password) => {
|
||||
|
||||
const logout = async (token) => {
|
||||
if (!token) {
|
||||
throw { status: 400, message: 'Token fehlt' };
|
||||
const err = new Error('Token fehlt');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
await UserToken.destroy({ where: { token } });
|
||||
return { message: 'Logout erfolgreich' };
|
||||
|
||||
Reference in New Issue
Block a user