Skip to content

Commit

Permalink
Merge pull request #66 from tanish35/master
Browse files Browse the repository at this point in the history
Add google login
  • Loading branch information
tanish35 authored Oct 5, 2024
2 parents 4bd6f59 + d5ecbdd commit 8c1d52e
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 4 deletions.
2 changes: 1 addition & 1 deletion backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ model User {
user_id String @id @default(cuid())
email String @unique
name String?
password String
password String?
createdAt DateTime @default(now())
emailVerified Boolean @default(false)
collegeEmailVerified Boolean @default(false)
Expand Down
44 changes: 44 additions & 0 deletions backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,45 @@ 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({
data: {
email,
name:displayName,
collegeEmailVerified: false,
emailVerified:true,
},
});
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",
});
return res.status(201).json({ message: "User created" });
}
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" });
});


// @ts-ignore
const registerUser = asyncHandler(async (req: Request, res: Response) => {
const { email, name, password, collegeName, courseName, isOnline, location } =
Expand Down Expand Up @@ -166,6 +205,10 @@ const loginUser = asyncHandler(async (req: Request, res: Response) => {
res.status(404).json({ message: "User not found" });
return;
}
if(!user.password){
res.status(401).json({ message: "Logged in with Google Or Github" });
return;
}
const match = await bcrypt.compare(password, user.password);
if (!match) {
res.status(401).json({ message: "Invalid credentials" });
Expand Down Expand Up @@ -310,4 +353,5 @@ export {
getCurrentUserDetails,
getUserDetailsById,
addCourseToUser,
googleSignInOrSignUp,
};
4 changes: 3 additions & 1 deletion backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
verifyUser,
getCurrentUserDetails,
getUserDetailsById,
addCourseToUser
addCourseToUser,
googleSignInOrSignUp
} from "../controllers/userControllers";
import checkAuth from "../middleware/checkAuth";

Expand All @@ -18,5 +19,6 @@ 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("/google", googleSignInOrSignUp); // sign in or sign up using google

export default router;
2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"axios": "^1.7.2",
"dotenv": "^16.4.5",
"firebase": "^10.14.0",
"framer-motion": "^11.3.19",
"react": "^18.3.1",
"react-autosuggest": "^10.1.0",
Expand Down
34 changes: 34 additions & 0 deletions frontend/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
} from "@chakra-ui/react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { auth, googleProvider } from "../firebase.js";
import { signInWithPopup } from "firebase/auth";

const LoginPage = () => {
const [email, setEmail] = useState("");
Expand All @@ -21,6 +23,35 @@ const LoginPage = () => {
const toast = useToast();
const navigate = useNavigate();

const handleGoogleLogin = async () => {
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 });
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("Google 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 @@ -78,6 +109,9 @@ const LoginPage = () => {
<Button colorScheme="teal" isLoading={loading} onClick={handleLogin}>
Login
</Button>
<Button colorScheme="red" onClick={handleGoogleLogin}>
Login with Google
</Button>
</Stack>
</Container>
</Flex>
Expand Down
8 changes: 6 additions & 2 deletions frontend/src/components/Posts.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@ const Posts = () => {
withCredentials: true,
});
setCommunities(response.data.college);
console.log(response.data.college);
setLoading(false);
} catch (err) {
setLoading(false);
alert("Error fetching communities");
console.error("Error fetching communities:", err);
}
};
// const fetchPosts = async () => {
Expand Down Expand Up @@ -113,7 +114,10 @@ const Posts = () => {
return (
<Container centerContent>
<SearchBar />
<CreatePost communities={communities} onSubmit={handleCreatePost} />
{communities.length>0 && (
<CreatePost communities={communities} onSubmit={handleCreatePost} />
)}

<VStack spacing={4} align="stretch" width="100%" mt={4}>
<InfiniteScroll
dataLength={posts.length}
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/firebase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth, GoogleAuthProvider, GithubAuthProvider } from "firebase/auth";

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_FIREBASE_APP_ID,
measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
const githubProvider = new GithubAuthProvider();

export { auth, googleProvider, githubProvider };

0 comments on commit 8c1d52e

Please sign in to comment.