Skip to content

Commit

Permalink
Merge pull request #73 from tanish35/master
Browse files Browse the repository at this point in the history
Fix lazyloading,dark mode. Add github login
  • Loading branch information
tanish35 authored Oct 7, 2024
2 parents 4890dbe + f2696d5 commit 2d96a97
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 54 deletions.
2 changes: 1 addition & 1 deletion backend/src/controllers/postController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const fetchPosts = asyncHandler(async (req: Request, res: Response) => {
const { page } = req.body;
const pageNumber = page;

const postsPerPage = 3;
const postsPerPage = 4;
const offset = (pageNumber - 1) * postsPerPage;

const posts = await prisma.post.findMany({
Expand Down
117 changes: 82 additions & 35 deletions backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,51 +7,99 @@ import sendMail from "../mail/sendMail";
import { Verifier } from "academic-email-verifier";
import checkCollegeEmail from "../mail/checkAcademic";


//@ts-ignore
const googleSignInOrSignUp = asyncHandler(async (req: Request, res: Response) => {
const{email,displayName}=req.body;
const user = await prisma.user.findUnique({
where: {
email,
},
});
if (!user) {
const user = await prisma.user.create({
// @ts-ignore
data: {
const googleSignInOrSignUp = asyncHandler(
//@ts-ignore
async (req: Request, res: Response) => {
const { email, displayName } = req.body;
if (!process.env.SECRET) {
throw new Error("Secret not found");
}
const user = await prisma.user.findUnique({
where: {
email,
name:displayName,
collegeEmailVerified: false,
emailVerified:true,
},
});
const exp = Date.now() + 1000 * 60 *60*24*30;
// @ts-ignore
if (!user) {
const user = await prisma.user.create({
data: {
email,
name: displayName,
collegeEmailVerified: false,
emailVerified: true,
},
});
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
secure: false,
sameSite: "lax",
});
return res.status(201).json({ message: "User created" });
}
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
secure: false,
sameSite: "lax",
});
return res.status(201).json({ message: "User created" });
res.status(200).json({ message: "User logged in" });
}
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
// @ts-ignore
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
secure: false,
sameSite: "lax",
});
res.status(200).json({ message: "User logged in" });
});
);

const githubSignInOrSignUp = asyncHandler(
//@ts-ignore
async (req: Request, res: Response) => {
let { email, displayName } = req.body;
if (!process.env.SECRET) {
throw new Error("Secret not found");
}
const user = await prisma.user.findUnique({
where: {
email,
},
});
if (!displayName) {
displayName = email.split("@")[0];
}

if (!user) {
const user = await prisma.user.create({
data: {
email,
name: displayName,
collegeEmailVerified: false,
emailVerified: true,
},
});
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
secure: false,
sameSite: "lax",
});
return res.status(201).json({ message: "User created" });
}
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
secure: false,
sameSite: "lax",
});
res.status(200).json({ message: "User logged in" });
}
);

// @ts-ignore
const registerUser = asyncHandler(async (req: Request, res: Response) => {
const { email, name, password, collegeName, courseName, isOnline, location } =
req.body;
if (!process.env.SECRET) {
throw new Error("Secret not found");
}
const hashedPassword = await bcrypt.hash(password, 8);
if (!email || !name || !password) {
res.status(400).json({ message: "Please provide all fields" });
Expand Down Expand Up @@ -128,11 +176,9 @@ const registerUser = asyncHandler(async (req: Request, res: Response) => {
},
});
const exp = Date.now() + 1000 * 60 * 5;
// @ts-ignore
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
const url = `${process.env.BACKEND_URL}/api/user/verify/${token}`;
const htmlContent = `<a href="${url}">Verify using this link</a>`;
// @ts-ignore
sendMail(htmlContent, email);
res.status(201).json({ message: "User created" });
} else {
Expand All @@ -145,11 +191,9 @@ const registerUser = asyncHandler(async (req: Request, res: Response) => {
},
});
const exp = Date.now() + 1000 * 60 * 5;
// @ts-ignore
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
const url = `${process.env.BACKEND_URL}/api/user/verify/${token}`;
const htmlContent = `<a href="${url}">Verify using this link</a>`;
// @ts-ignore
sendMail(htmlContent, email);
res.status(201).json({ message: "User created" });
}
Expand Down Expand Up @@ -194,6 +238,9 @@ const verifyUser = asyncHandler(async (req: Request, res: Response) => {

const loginUser = asyncHandler(async (req: Request, res: Response) => {
const { email, password } = req.body;
if (!process.env.SECRET) {
throw new Error("Secret not found");
}
if (!email || !password) {
res.status(400).json({ message: "Please provide all fields" });
return;
Expand All @@ -207,7 +254,7 @@ const loginUser = asyncHandler(async (req: Request, res: Response) => {
res.status(404).json({ message: "User not found" });
return;
}
if(!user.password){
if (!user.password) {
res.status(401).json({ message: "Logged in with Google Or Github" });
return;
}
Expand All @@ -217,7 +264,6 @@ const loginUser = asyncHandler(async (req: Request, res: Response) => {
return;
}
const exp = Date.now() + 1000 * 60 * 60 * 24 * 30;
// @ts-ignore
const token = jwt.sign({ sub: user.user_id, exp }, process.env.SECRET);
res.cookie("Authorization", token, {
httpOnly: true,
Expand Down Expand Up @@ -356,4 +402,5 @@ export {
getUserDetailsById,
addCourseToUser,
googleSignInOrSignUp,
githubSignInOrSignUp,
};
4 changes: 3 additions & 1 deletion backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
getCurrentUserDetails,
getUserDetailsById,
addCourseToUser,
googleSignInOrSignUp
googleSignInOrSignUp,
githubSignInOrSignUp,
} from "../controllers/userControllers";
import checkAuth from "../middleware/checkAuth";

Expand All @@ -20,5 +21,6 @@ router.get("/me", checkAuth, getCurrentUserDetails); // get the user details of
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("/google", googleSignInOrSignUp); // sign in or sign up using google
router.post("/github", githubSignInOrSignUp); // sign in or sign up using github

export default router;
92 changes: 81 additions & 11 deletions frontend/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import {
Stack,
useToast,
} from "@chakra-ui/react";
import { FcGoogle } from "react-icons/fc"; // Google icon
import { FaGithub } from "react-icons/fa"; // GitHub icon
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { auth, googleProvider } from "../firebase.js";
import { auth, googleProvider, githubProvider } from "../firebase.js";
import { signInWithPopup } from "firebase/auth";

const LoginPage = () => {
Expand All @@ -27,11 +29,14 @@ const LoginPage = () => {
try {
const result = await signInWithPopup(auth, googleProvider);
const user = result.user;
console.log("Google login result: ");
await axios.post("/user/google", {
email:user.email,
displayName:user.displayName
}, { withCredentials: true });
await axios.post(
"/user/google",
{
email: user.email,
displayName: user.displayName,
},
{ withCredentials: true }
);
toast({
title: "Login successful.",
description: "You are being redirected to the posts page.",
Expand All @@ -52,6 +57,38 @@ const LoginPage = () => {
}
};

const handleGithubLogin = async () => {
try {
const result = await signInWithPopup(auth, githubProvider);
const user = result.user;
await axios.post(
"/user/github",
{
email: user.email,
displayName: user.displayName,
},
{ withCredentials: true }
);
toast({
title: "Login successful.",
description: "You are being redirected to the posts page.",
status: "success",
duration: 3000,
isClosable: true,
});
navigate("/posts");
} catch (error) {
console.error("Github login error: ", error);
toast({
title: "Login failed.",
description: error.message || "An error occurred.",
status: "error",
duration: 3000,
isClosable: true,
});
}
};

const handleLogin = async () => {
setLoading(true);
try {
Expand Down Expand Up @@ -82,10 +119,17 @@ const LoginPage = () => {
};

return (
<Flex minH="100vh" align="center" justify="center" bg="gray.50">
<Container maxW="md" bg="white" boxShadow="md" p={6} rounded="md">
<Flex minH="100vh" align="center" justify="center" bg="black">
<Container
maxW="md"
bg="gray.800"
boxShadow="md"
p={6}
rounded="md"
color="white"
>
<Stack spacing={4}>
<Heading as="h1" size="lg" textAlign="center">
<Heading as="h1" size="lg" textAlign="center" color="white">
Login
</Heading>
<FormControl id="email">
Expand All @@ -95,6 +139,8 @@ const LoginPage = () => {
value={email}
onChange={(e) => setEmail(e.target.value)}
required
bg="gray.700"
color="white"
/>
</FormControl>
<FormControl id="password">
Expand All @@ -104,14 +150,38 @@ const LoginPage = () => {
value={password}
onChange={(e) => setPassword(e.target.value)}
required
bg="gray.700"
color="white"
/>
</FormControl>
<Button colorScheme="teal" isLoading={loading} onClick={handleLogin}>
<Button
colorScheme="teal"
isLoading={loading}
onClick={handleLogin}
_hover={{ bg: "teal.500" }}
>
Login
</Button>
<Button colorScheme="red" onClick={handleGoogleLogin}>
<Button
leftIcon={<FcGoogle />}
colorScheme="gray"
onClick={handleGoogleLogin}
bg="white"
color="black"
_hover={{ bg: "gray.200" }}
>
Login with Google
</Button>
<Button
leftIcon={<FaGithub />}
colorScheme="gray"
onClick={handleGithubLogin}
bg="white"
color="black"
_hover={{ bg: "gray.200" }}
>
Login with Github
</Button>
</Stack>
</Container>
</Flex>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Posts.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ const Posts = () => {
return (
<Container centerContent>
<SearchBar />
{communities.length>0 && (
{communities && (
<CreatePost communities={communities} onSubmit={handleCreatePost} />
)}

<VStack spacing={4} align="stretch" width="100%" mt={4}>
<InfiniteScroll
dataLength={posts.length}
Expand Down
10 changes: 7 additions & 3 deletions frontend/src/components/Register.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,17 @@ const RegisterForm = () => {
<ListItem
p={2}
borderBottom="1px solid"
borderColor="gray.200"
borderColor="gray.600"
cursor="pointer"
_hover={{ backgroundColor: "gray.100" }}
_hover={{ backgroundColor: "gray.700" }}
bg="gray.800"
>
<Flex align="center">
<Box>
<Text fontWeight="bold">{suggestion}</Text>
<Text fontWeight="bold" color="white">
{" "}
{suggestion}
</Text>
</Box>
</Flex>
</ListItem>
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/components/data/collegeNames.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,6 @@ export const collegeNames = [
"Shiv Nadar University",
"Jawaharlal Nehru Technological University",
"IIT Patna",
"Indraprastha Institute of Information Technology",
"Netaji Subhas University of Technology",
];
Loading

0 comments on commit 2d96a97

Please sign in to comment.