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

Create API endpoints and tests for the entities #2

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
added signup, login and logout for the user
  • Loading branch information
Fahdkassim committed Oct 30, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 5a62dbfe868ad7521f834df9e66a0bb58de0a7af
Empty file.
61 changes: 61 additions & 0 deletions backend/modules/user/UserService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// UserService.js
import { AppDataSource } from "../../database/dbConnect";
import { User } from "../../entities/user";
const bcrypt = require("bcrypt");

export class UserService {
private userRepository = AppDataSource.getRepository(User);

async create(
email: string,
password: string,
name: string,
status: string,
is_admin: boolean,
res: any
) {
try {
const existingUser = await this.userRepository.findOne({
where: [{ email: email }, { name: name }],
});

if (existingUser) {
if (existingUser.email === email) {
res.send({
status: 400,
message: "User with this email already exists.",
});
} else if (existingUser.name === name) {
res.send({
status: 400,
message: "User with this name already exists.",
});
}
} else {
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User();
user.name = name;
user.email = email;
user.password = hashedPassword;
user.status = status;
user.is_admin = is_admin;

const result = await this.userRepository.save(user);
return result;
}
} catch (error: any) {
throw new Error(error.message);
}
}

async findByEmail(email: string) {
try {
const user = await this.userRepository.findOne({
where: { email: email },
});
return user;
} catch (error) {
throw new Error("Error while finding user by email: " + error);
}
}
}
125 changes: 96 additions & 29 deletions backend/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,121 @@
import { User } from "../../entities/user";
import { AppDataSource } from "../../database/dbConnect";
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
import { UserService } from "./UserService";
import { config } from "dotenv";

const userRepo = AppDataSource.getRepository(User);

export const createUser = async (req: any, res: any) => {
const userService = new UserService();

export const signup = async (req: any, res: any) => {
try {
const { name, email, password, status, is_admin } = req.body;

if (!name || !email || !password || !status || !is_admin) {
if (!name || !email || !password || !status || is_admin === undefined) {
return res.status(400).json({
message:
"Missing required fields. Please provide all necessary user details.",
});
}

const existingUser = await userRepo.findOne({
where: [{ email: email }, { name: name }],
});

const existingUser = await userService.findByEmail(email);
if (existingUser) {
if (existingUser.email === email) {
return res.status(400).json({
message: "User with this email already exists.",
});
} else if (existingUser.name === name) {
return res.status(400).json({
message: "User with this name already exists.",
});
return res.status(400).json({ message: "User already exists" });
}

const result = await userService.create(
email,
password,
name,
status,
is_admin,
res
);

if (!result) {
return res
.status(500)
.json({ message: "User creation failed. Please try again later." });
}

const token = jwt.sign(
{ email: result.email, id: result.id },
process.env.JWT_SECRET_KEY,
{
expiresIn: "1h",
}
);

return res
.status(200)
.json({ message: "User created successfully", user: result, token });
} catch (error) {
return error;
}
};

export const login = async (req: any, res: any) => {
try {
const { email, password } = req.body;
const user = await userService.findByEmail(email);
if (!user) {
return res.status(404).json({ message: "User not found" });
}

const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid password" });
}

// Generate JWT token
const token = jwt.sign(
{ email: user.email, id: user.id },
process.env.JWT_SECRET_KEY,
{
expiresIn: "1h",
}
);

return res.status(200).json({ message: "Login successful", token });
} catch (error) {
return res
.status(500)
.json({ message: "Login failed. Please try again later." });
}
};

export const logout = (req: any, res: any) => {
res.clearCookie("jwtToken");
return res.status(200).json({ message: "Logout successful" });
};

export const createUser = async (req: any, res: any) => {
try {
const { name, email, password, status, is_admin } = req.body;

if (!name || !email || !password || !status || is_admin === undefined) {
return res.status(400).json({
message:
"Missing required fields. Please provide all necessary user details.",
});
}
const hashedPassword = await bcrypt.hash(password, 10);
const user: User = new User();
user.name = name;
user.email = email;
user.password = hashedPassword;
user.status = status;
user.is_admin = is_admin;

const result = await userRepo.save(user);

const result = await userService.create(
email,
password,
name,
status,
is_admin,
res
);
return res.status(200).json({
message: "User created successfully!",
user: result,
});
} catch (error) {
console.log(error);
return res.status(400).json({
message: "User creation failed!",
error: error,
});
} catch (error: any) {
return error;
}
};

6 changes: 6 additions & 0 deletions backend/modules/user/user.routes.ts
Original file line number Diff line number Diff line change
@@ -7,12 +7,18 @@ import {
getUserById,
updateUser,
deleteUser,
signup,
login,
logout,
} from "./user.controller";

router.post("/", createUser);
router.get("/", getAllUsers);
router.get("/:id", getUserById);
router.put("/:id", updateUser);
router.delete("/:id", deleteUser);
router.post("/signup", signup);
router.post("/login", login);
router.post("/logout", logout);

export default router;
1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
@@ -41,6 +41,7 @@
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"morgan": "^1.10.0",
"pg": "^8.11.3",
"reflect-metadata": "^0.1.13",