Skip to content

Commit

Permalink
Fix zod,add update details,change pic
Browse files Browse the repository at this point in the history
  • Loading branch information
tanish35 committed Oct 10, 2024
1 parent 1171b9a commit b80e26d
Show file tree
Hide file tree
Showing 12 changed files with 359 additions and 71 deletions.
1 change: 1 addition & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ model User {
email String @unique
username String? @unique
password String?
pic String? @default("https://i1.sndcdn.com/artworks-000338788569-fxot50-t500x500.jpg")
createdAt DateTime @default(now())
emailVerified Boolean @default(false)
collegeEmailVerified Boolean @default(false)
Expand Down
1 change: 1 addition & 0 deletions backend/src/controllers/postController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ const fetchPosts = asyncHandler(async (req: Request, res: Response) => {
User: {
select: {
username: true,
pic: true,
},
},
},
Expand Down
84 changes: 83 additions & 1 deletion backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,21 @@ const addUsername = asyncHandler(async (req: Request, res: Response) => {
},
});

const user1 = await prisma.user.findUnique({
where: {
user_id: id,
},
});

if (!user1) {
return res.status(404).json({ message: "User not found" });
}
if (user1.username) {
return res
.status(409)
.json({ message: "You are not authorized to change the username" });
}

if (response) {
return res.status(409).json({ message: "Username already exists" });
}
Expand All @@ -458,7 +473,13 @@ const addUsername = asyncHandler(async (req: Request, res: Response) => {
const addDetailsToUser = asyncHandler(async (req: Request, res: Response) => {
const { username, collegeName, courseName, isOnline, location, id } =
req.body;
if (!collegeName || !courseName || !location || isOnline === undefined) {
if (
!collegeName ||
!courseName ||
!location ||
isOnline === undefined ||
!username
) {
return res.status(400).json({ message: "Please provide all fields" });
}
const user = await prisma.user.findFirst({
Expand All @@ -467,6 +488,20 @@ const addDetailsToUser = asyncHandler(async (req: Request, res: Response) => {
},
});

const user1 = await prisma.user.findUnique({
where: {
user_id: id,
},
});
if (!user1) {
return res.status(404).json({ message: "User not found" });
}
if (user1.username) {
return res
.status(409)
.json({ message: "You are not authorized to change the username" });
}

if (user) {
return res.status(409).json({ message: "Username already exists" });
}
Expand Down Expand Up @@ -530,6 +565,51 @@ const getAllUser = asyncHandler(async (req: Request, res: Response) => {
res.status(200).json(users);
});

const logOut = asyncHandler(async (req: Request, res: Response) => {
res.clearCookie("Authorization");
res.status(200).json({ message: "Logged out" });
});

// @ts-ignore
const updateDetails = asyncHandler(async (req: Request, res: Response) => {
// @ts-ignore
const userId = req.user.user_id;
let { username, pic } = req.body;
if (!username) {
// @ts-ignore
username = req.user.username;
}
if (!pic) {
// @ts-ignore
pic = req.user.pic;
}
// @ts-ignore
if (username !== req.user.username) {
const response = await prisma.user.findFirst({
where: {
OR: [{ username: username }],
},
});
if (response) {
return res.status(409).json({ message: "Username already exists" });
}
}
if (!pic) {
// @ts-ignore
pic = req.user.pic;
}
await prisma.user.update({
where: {
user_id: userId,
},
data: {
username,
pic,
},
});
return res.status(200).json({ message: "Details updated" });
});

export {
registerUser,
loginUser,
Expand All @@ -542,4 +622,6 @@ export {
addDetailsToUser,
addUsername,
getAllUser,
logOut,
updateDetails,
};
8 changes: 6 additions & 2 deletions backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
addDetailsToUser,
addUsername,
getAllUser,
logOut,
updateDetails,
} from "../controllers/userControllers";
import checkAuth from "../middleware/checkAuth";

Expand All @@ -22,11 +24,13 @@ router.route("/login").post(loginUser);
router.route("/verify/:token").get(verifyUser);
router.get("/me", checkAuth, getCurrentUserDetails); // get the user details of the current user
// router.get("/get/:userId", checkAuth, getUserDetailsById); // get the user details of a specific user
router.post("/addcourse", checkAuth, addCourseToUser); // add a course to the current user
// router.post("/addcourse", checkAuth, addCourseToUser); // add a course to the current user
router.post("/google", googleSignInOrSignUp); // sign in or sign up using google
router.post("/github", githubSignInOrSignUp); // sign in or sign up using github
router.post("/addDetails", addDetailsToUser); // add details to the current user
router.post("/addusername", addUsername); // change the username of the current user
router.get('/all', getAllUser);
router.get("/all", getAllUser);
router.get("/logout", logOut);
router.post("/update", checkAuth, updateDetails);

export default router;
40 changes: 20 additions & 20 deletions backend/src/validation/registerSchema.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import z from "zod";
import { z } from "zod";
export const registerSchema = z.object({
email: z.string().email({ message: "Invalid email address " }),
username: z
.string()
.min(3, { message: "Username must be at least 3 characters long " }),
password: z
.string()
.min(6, { message: "Password must be at least 6 characters long. " })
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/,
{
message:
"Password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character ",
}
),
collegeName: z.string().optional(),
courseName: z.string().optional(),
isOnline: z.boolean(),
location: z.string().optional(),
});
email: z.string().email({ message: "Invalid email address " }),
username: z
.string()
.min(3, { message: "Username must be at least 3 characters long " }),
password: z
.string()
.min(6, { message: "Password must be at least 6 characters long. " })
.regex(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/,
{
message:
"Password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character ",
}
),
collegeName: z.string().optional(),
courseName: z.string().optional(),
isOnline: z.boolean(),
location: z.string().optional(),
});
21 changes: 20 additions & 1 deletion frontend/src/components/AddDetails.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
Text,
useToast,
} from "@chakra-ui/react";
import { z } from "zod";

import axios from "axios";
import { useNavigate } from "react-router-dom";
Expand All @@ -26,12 +27,23 @@ import { location } from "./data/location";

import Autosuggest from "react-autosuggest";

const AddDetailsSchema = z.object({
username: z
.string()
.min(3, { message: "Username must be at least 3 characters long" }),
collegeName: z.string(),
courseName: z.string(),
isOnline: z.boolean(),
location: z.string(),
id: z.string(),
});

const AddDetails = () => {
const [formData, setFormData] = useState({
username: "",
collegeName: "",
courseName: "",
isOnline: false, // Default value as boolean
isOnline: false,
location: "",
id: "",
});
Expand All @@ -42,6 +54,7 @@ const AddDetails = () => {
}, [id]);

const navigate = useNavigate();
const [error, setError] = useState({});

const [suggestionsCollege, setSuggestionsCollege] = useState([]);
const [suggestionsCourse, setSuggestionsCourse] = useState([]);
Expand Down Expand Up @@ -138,6 +151,8 @@ const AddDetails = () => {
e.preventDefault();
setLoading(true);
try {
AddDetailsSchema.parse(formData);
setError({});
const response = await axios.post("/api/user/addDetails", formData, {
withCredentials: true,
});
Expand All @@ -152,6 +167,9 @@ const AddDetails = () => {

navigate("/login");
} catch (e) {
if (e instanceof z.ZodError) {
setError(e.formErrors.fieldErrors);
}
console.log(e);
setLoading(false);
}
Expand All @@ -178,6 +196,7 @@ const AddDetails = () => {
boxShadow: "0 0 0 1px #3182CE",
}}
/>
{error.username && <Box color="red.500">{error.username}</Box>}
</FormControl>

<FormControl id="collegeName" isRequired>
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/components/AddUsername.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,21 @@ import {

import axios from "axios";
import { useNavigate } from "react-router-dom";
import { z } from "zod";

const AddUsernameSchema = z.object({
username: z
.string()
.min(3, { message: "Username must be at least 3 characters long" }),
id: z.string(),
});

const AddUsername = () => {
const [formData, setFormData] = useState({
username: "",
id: "",
});
const [error, setError] = useState({});
const navigate = useNavigate();
const toast = useToast();
const { id } = useParams();
Expand All @@ -41,6 +50,8 @@ const AddUsername = () => {
e.preventDefault();
setLoading(true);
try {
AddUsernameSchema.parse(formData);
setError({});
const response = await axios.post("/api/user/addusername", formData, {
withCredentials: true,
});
Expand All @@ -54,6 +65,9 @@ const AddUsername = () => {
});
navigate("/login");
} catch (err) {
if (err instanceof z.ZodError) {
setError(err.formErrors.fieldErrors);
}
setLoading(false);
toast({
title: "Error",
Expand Down Expand Up @@ -86,6 +100,7 @@ const AddUsername = () => {
boxShadow: "0 0 0 1px #3182CE",
}}
/>
{error.username && <Box color="red.500">{error.username}</Box>}
</FormControl>
<Button
type="submit"
Expand Down
Loading

0 comments on commit b80e26d

Please sign in to comment.