Redis and session timeout added

This commit is contained in:
Torsten Schulz
2024-10-27 14:15:44 +01:00
parent 7f8709516d
commit b78dfe6826
9 changed files with 320 additions and 6 deletions

View File

@@ -6,6 +6,7 @@ import UserParam from '../models/community/user_param.js';
import UserParamType from '../models/type/user_param.js';
import { sendAccountActivationEmail, sendPasswordResetEmail } from './emailService.js';
import { sequelize } from '../utils/sequelize.js';
import { setUserSession, deleteUserSession } from '../utils/redis.js';
const saltRounds = 10;
@@ -31,22 +32,18 @@ export const registerUser = async ({ email, username, password, language }) => {
active: false,
registration_date: new Date()
});
const languageType = await UserParamType.findOne({ where: { description: 'language' } });
if (!languageType) {
throw new Error('languagenotfound');
}
const languageParam = await UserParam.create({
userId: user.id,
paramTypeId: languageType.id,
value: language
});
const activationLink = `${process.env.FRONTEND_URL}/activate?token=${resetToken}`;
await sendAccountActivationEmail(email, activationLink, username, resetToken, language);
const authCode = crypto.randomBytes(20).toString('hex');
return { id: user.hashedId, username: user.username, active: user.active, param: [languageParam], authCode };
};
@@ -62,6 +59,14 @@ export const loginUser = async ({ username, password }) => {
const authCode = crypto.randomBytes(20).toString('hex');
user.authCode = authCode;
await user.save();
const sessionData = {
id: user.hashedId,
username: user.username,
active: user.active,
authCode,
timestamp: Date.now()
};
await setUserSession(user.id, sessionData);
const params = await UserParam.findAll({
where: {
userId: user.id
@@ -86,6 +91,24 @@ export const loginUser = async ({ username, password }) => {
};
};
export const logoutUser = async (hashedUserId) => {
try {
const user = User.findOne({
where: {
hashedId: hashedUserId
}
})
if (!user) {
return;
}
await deleteUserSession(user.id);
console.log('Benutzer erfolgreich aus Redis entfernt:', userId);
} catch (error) {
console.error('Fehler beim Logout:', error);
throw new Error('logoutfailed');
}
};
export const handleForgotPassword = async ({ email }) => {
const user = await User.findOne({ where: { email } });
if (!user) {