Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

365 replace he package and hedecodeuserpicture #454

Merged
merged 6 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"express": "^4.19.2",
"express-validator": "^7.1.0",
"handlebars": "^4.7.8",
"he": "^1.2.0",
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"nodemailer": "^6.9.15",
Expand Down
104 changes: 44 additions & 60 deletions backend/src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
const bcrypt = require("bcryptjs");
const db = require("../models");
const bcrypt = require('bcryptjs');
const db = require('../models');
const User = db.User;
const Token = db.Token;
const Invite = db.Invite;
const sequelize = db.sequelize;
const { generateToken, verifyToken } = require("../utils/jwt.helper");
const crypto = require("crypto");
const { TOKEN_LIFESPAN } = require("../utils/constants.helper");
const {
sendSignupEmail,
sendPasswordResetEmail,
findUserByEmail,
} = require("../service/email.service");
const settings = require("../../config/settings");
const he = require("he");
const { create } = require("domain");
const { generateToken, verifyToken } = require('../utils/jwt.helper');
const crypto = require('crypto');
const { TOKEN_LIFESPAN } = require('../utils/constants.helper');
const { sendSignupEmail, sendPasswordResetEmail, findUserByEmail } = require('../service/email.service');
const settings = require('../../config/settings');
const { decode } = require('../utils/auth.helper');

const register = async (req, res) => {
const isTestingEnv = process.env.NODE_ENV === "test";
const isTestingEnv = process.env.NODE_ENV === 'test';
try {
const { name, surname, email, password } = req.body;
const existingUser = await findUserByEmail(email);
if (existingUser)
return res.status(400).json({ error: "Email already exists" });
if (existingUser) return res.status(400).json({ error: 'Email already exists' });

const userCount = await User.count();
const hashedPassword = await bcrypt.hash(password, 10);
Expand All @@ -37,9 +31,7 @@ const register = async (req, res) => {
});

if (!invite) {
return res
.status(404)
.json({ error: "Invitation not found or expired" });
return res.status(404).json({ error: 'Invitation not found or expired' });
}
}

Expand Down Expand Up @@ -71,11 +63,9 @@ const register = async (req, res) => {
}

await transaction.commit();
} catch (err) {
} catch {
await transaction.rollback();
return res
.status(400)
.json({ error: "Error registering user by invite" });
return res.status(400).json({ error: 'Error registering user by invite' });
}
} else {
newUser = await User.create({
Expand All @@ -89,7 +79,7 @@ const register = async (req, res) => {

const token = generateToken({ id: newUser.id, email: newUser.email });

await Token.create({ token, userId: newUser.id, type: "auth" });
await Token.create({ token, userId: newUser.id, type: 'auth' });

await sendSignupEmail(newUser.email, newUser.name);

Expand All @@ -104,8 +94,8 @@ const register = async (req, res) => {
token,
});
} catch (error) {
console.error("Error registering user:", error);
res.status(500).json({ error: "Internal Server Error" });
console.error('Error registering user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

Expand All @@ -114,13 +104,13 @@ const login = async (req, res) => {
const { email, password } = req.body;
const user = await findUserByEmail(email);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ error: "Invalid credentials" });
return res.status(401).json({ error: 'Invalid credentials' });
}

await Token.destroy({ where: { userId: user.id, type: "auth" } });
await Token.destroy({ where: { userId: user.id, type: 'auth' } });

const token = generateToken({ id: user.id, email: user.email });
await Token.create({ token, userId: user.id, type: "auth" });
await Token.create({ token, userId: user.id, type: 'auth' });

res.status(200).json({
user: {
Expand All @@ -129,92 +119,86 @@ const login = async (req, res) => {
surname: user.surname,
email: user.email,
role: settings.user.roleName[user.role],
picture: user.picture ? he.decode(user.picture) : "",
picture: user.picture ? decode(user.picture) : '',
},
token,
});
} catch (error) {
console.error("Error logging in user:", error);
res.status(500).json({ error: "Internal Server Error" });
console.error('Error logging in user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

const logout = async (req, res) => {
try {
const token = req.headers.authorization.split(" ")[1];
const token = req.headers.authorization.split(' ')[1];
const decoded = verifyToken(token);

if (!decoded) {
return res.status(401).json({ error: "Invalid token" });
return res.status(401).json({ error: 'Invalid token' });
}

const dbToken = await Token.findOne({
where: { token, userId: decoded.id, type: "auth" },
where: { token, userId: decoded.id, type: 'auth' },
});
if (!dbToken) {
return res.status(401).json({ error: "Invalid token" });
return res.status(401).json({ error: 'Invalid token' });
}

await dbToken.destroy();
res.status(200).json({ message: "Successfully logged out" });
res.status(200).json({ message: 'Successfully logged out' });
} catch (error) {
console.error("Error logging out user:", error);
res.status(500).json({ error: "Internal Server Error" });
console.error('Error logging out user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

const forgetPassword = async (req, res) => {
const isTestingEnv = process.env.NODE_ENV === "test";
const isTestingEnv = process.env.NODE_ENV === 'test';
try {
const { email } = req.body;
const user = await findUserByEmail(email);
if (!user) return res.status(400).json({ error: "User not found" });
if (!user) return res.status(400).json({ error: 'User not found' });

const resetToken = crypto.randomBytes(32).toString("hex");
const resetToken = crypto.randomBytes(32).toString('hex');
const hash = await bcrypt.hash(resetToken, 10);
const expiresAt = new Date(Date.now() + TOKEN_LIFESPAN);
await Token.create({
token: hash,
userId: user.id,
type: "reset",
type: 'reset',
expiresAt,
});

await sendPasswordResetEmail(user.email, user.name, resetToken);
if (isTestingEnv) {
return res
.status(200)
.json({ message: "Password reset token sent", resetToken });
return res.status(200).json({ message: 'Password reset token sent', resetToken });
}
res.status(200).json({ message: "Password reset token sent" });
res.status(200).json({ message: 'Password reset token sent' });
} catch (error) {
console.error("Error in forget password:", error);
res.status(500).json({ error: "Internal Server Error" });
console.error('Error in forget password:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

const resetPassword = async (req, res) => {
try {
const { token, newPassword } = req.body;
const dbToken = await Token.findOne({ where: { type: "reset" } });

if (
!dbToken ||
new Date(dbToken.expiresAt) < new Date() ||
!(await bcrypt.compare(token, dbToken.token))
) {
return res.status(400).json({ error: "Invalid or expired token" });
const dbToken = await Token.findOne({ where: { type: 'reset' } });

if (!dbToken || new Date(dbToken.expiresAt) < new Date() || !(await bcrypt.compare(token, dbToken.token))) {
return res.status(400).json({ error: 'Invalid or expired token' });
}

const user = await User.findOne({ where: { id: dbToken.userId } });
user.password = await bcrypt.hash(newPassword, 10);
await user.save();
await dbToken.destroy();

res.status(200).json({ message: "Password reset successful" });
res.status(200).json({ message: 'Password reset successful' });
} catch (error) {
console.error("Error resetting password:", error);
res.status(500).json({ error: "Internal Server Error" });
console.error('Error resetting password:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

Expand Down
Loading
Loading