Skip to content

Commit

Permalink
Refactor authentication controller to use Express.js middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Sowri19 committed Apr 9, 2024
1 parent d7e313f commit 2039291
Showing 1 changed file with 95 additions and 112 deletions.
207 changes: 95 additions & 112 deletions controller/authController.mjs
Original file line number Diff line number Diff line change
@@ -1,166 +1,149 @@
// Import the User model (adjust the path as necessary)
import User from "../model/authModel.mjs";

// Helper function to generate a standard API Gateway response
const generateResponse = (statusCode, message, data = {}, cookies = []) => ({
statusCode,
headers: {
"Content-Type": "application/json",
...(cookies.length > 0 && { "Set-Cookie": cookies }),
},
body: JSON.stringify({
success: statusCode >= 200 && statusCode < 300,
message,
...data,
}),
});

export const signup = async (event) => {
const { email, password } = JSON.parse(event.body);
export const signup = async (req, res) => {
const { email, password } = req.body;
const user = new User(email, password);

try {
const cognitoUser = await user.signup();
return {
statusCode: 200,
body: JSON.stringify({
success: true,
message: "User signed up successfully",
user: cognitoUser,
}),
};
res.status(200).json({
success: true,
message: "User signed up successfully",
user: cognitoUser,
});
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: "Signup failed",
error: error.message,
}),
};
console.error(error);
res.status(400).json({
success: false,
message: "Signup failed",
error: error.message,
});
}
};

export const confirmSignup = async (event) => {
const { email, verificationCode, password } = JSON.parse(event.body);
export const confirmSignup = async (req, res) => {
const { email, verificationCode, password } = req.body;
const user = new User(email, password);

try {
await user.confirmSignup(verificationCode);
const tokens = await user.authenticate();
const cookie = `token=${tokens.idToken}; HttpOnly; Max-Age=${
30 * 24 * 60 * 60
}; Secure; Path=/`;
return generateResponse(
200,
"Signup confirmed and user logged in",
{ tokens },
[cookie]
);

// Set the JWT token as a cookie in the response
res
.status(200)
.cookie("token", tokens.idToken, {
httpOnly: true,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
secure: true,
path: "/",
})
.json({
success: true,
message: "Signup confirmed and user logged in",
tokens,
});
} catch (error) {
return generateResponse(400, "Failed to confirm signup", {
console.error(error);
res.status(400).json({
success: false,
message: "Failed to confirm signup",
error: error.message,
});
}
};

export const login = async (event) => {
const { email, password } = JSON.parse(event.body);
export const login = async (req, res) => {
const { email, password } = req.body;
const user = new User(email, password);

try {
const tokens = await user.authenticate();
const cookie = `token=${tokens.idToken}; HttpOnly; Max-Age=${
30 * 24 * 60 * 60
}; Secure; Path=/`;
return generateResponse(200, "Authentication successful", { tokens }, [
cookie,
]);

// Set the JWT token as a cookie in the response
res
.status(200)
.cookie("token", tokens.idToken, {
httpOnly: true,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
secure: true,
path: "/",
})
.json({
success: true,
message: "Authentication successful",
tokens,
});
} catch (error) {
return generateResponse(401, "Authentication failed", {
console.error(error);
res.status(401).json({
success: false,
message: "Authentication failed",
error: error.message,
});
}
};

export const changePassword = async (event) => {
const { email, oldPassword, newPassword } = JSON.parse(event.body);
export const changePassword = async (req, res) => {
const { email, oldPassword, newPassword } = req.body;
const user = new User(email, oldPassword);

try {
const result = await user.changePassword(oldPassword, newPassword);
return {
statusCode: 200,
body: JSON.stringify({
success: true,
message: "Password changed successfully",
result,
}),
};
res.status(200).json({
success: true,
message: "Password changed successfully",
result,
});
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: "Failed to change password",
error: error.message,
}),
};
console.error(error);
res.status(400).json({
success: false,
message: "Failed to change password",
error: error.message,
});
}
};

export const updateEmail = async (event) => {
const { email, newEmail, password } = JSON.parse(event.body);
export const updateEmail = async (req, res) => {
const { email, newEmail, password } = req.body;
const user = new User(email, password);

try {
const result = await user.updateEmail(newEmail);
return {
statusCode: 200,
body: JSON.stringify({
success: true,
message: "Email updated successfully",
result,
}),
};
res.status(200).json({
success: true,
message: "Email updated successfully",
result,
});
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: "Failed to update email",
error: error.message,
}),
};
console.error(error);
res.status(400).json({
success: false,
message: "Failed to update email",
error: error.message,
});
}
};

export const logout = async (event) => {
const { email } = JSON.parse(event.body);
export const logout = async (req, res) => {
const { email } = req.body;
const user = new User(email, "");

try {
user.logout();
const cookie = "token=; HttpOnly; Max-Age=0; Secure; Path=/";
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Set-Cookie": cookie,
},
body: JSON.stringify({
success: true,
message: "Logged out successfully",
}),
};

// Clear the JWT token cookie in the response
res.status(200).clearCookie("token").json({
success: true,
message: "Logged out successfully",
});
} catch (error) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: "Failed to log out",
error: error.message,
}),
};
console.error(error);
res.status(400).json({
success: false,
message: "Failed to log out",
error: error.message,
});
}
};

0 comments on commit 2039291

Please sign in to comment.