Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Marvellousz committed Mar 15, 2024
2 parents de6bccf + 49ccef5 commit e09e9d1
Show file tree
Hide file tree
Showing 13 changed files with 362 additions and 104 deletions.
2 changes: 1 addition & 1 deletion app/api/event1/getTeamCode/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export async function GET(req, { params }) {
const token = await getToken({req})
const auth = token ? token.accessTokenFromBackend : null
let userId = await getTokenDetails(auth);

console.log("rrrrrrfrrrrrr",userId);
// console.log(userId);
const team = await Event1.findOne({ teamLeaderId: userId });
if (!team) {
Expand Down
2 changes: 1 addition & 1 deletion app/api/event1/getTeamData/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function GET(req) {
if (!team) {
return NextResponse.json({ message: 'Team is not there ' });
}

return NextResponse.json({
message: 'Team Details sent. ',
status: 200,
Expand Down
9 changes: 4 additions & 5 deletions app/api/event1/getTeamViaToken/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ import { NextResponse } from "next/server";
export async function POST(req) {
try {
await connectMongoDB();
const { code } = await req.json();
console.log(code);
const team = await event1TeamToken.findOne({ teamCode: code });
const teamDetails = await Event1.findById(team.teamId);

const { teamCode } = await req.json();
console.log(teamCode);
const team = await event1TeamToken.findOne({ token: teamCode });
if (!team) {
return NextResponse.json({ error: "Team not found" });
}
const teamDetails = await Event1.findById(team.teamId);

return NextResponse.json({
message: "Team Details sent. ",
Expand Down
41 changes: 25 additions & 16 deletions app/api/event1/joinTeam/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import { NextResponse } from 'next/server';

export async function POST(req, { params }) {
try {
console.log("++++++++++++++++++++++++++++++++++++++++11111122334");
await connectMongoDB();

const token = await getToken({ req });
console.log("@@@@@@@@@@@",token)
const auth = token ? token.accessTokenFromBackend : null;
let userId = await getTokenDetails(auth);

console.log(userId);

const user = await Users.findById({ _id: userId });
console.log(user);

Expand All @@ -24,9 +26,12 @@ export async function POST(req, { params }) {
});
}

const { code } = await req.json();
console.log(code);
const team = await Event1.findOne({ teamCode: code });
console.log("$$$$$$$$$$$$$$$$$$")

const { teamCode } = await req.json();
console.log('==========',teamCode);
const team = await Event1.findOne({ teamCode: teamCode });
console.log("+++++",team);
//check if user is not a part of any team
if (!team) {
return NextResponse.json({ error: 'Team not found' });
Expand All @@ -36,31 +41,35 @@ export async function POST(req, { params }) {
}
// console.log(team)
const Event1TeamToken = await event1TeamToken.findOne({ teamId: team._id });

console.log("&&&&&&&",Event1TeamToken)
if (!Event1TeamToken) {
return res.status(404).json({ error: 'Token not found' });
}

const currentTime = new Date();
const tokenCreationTime = token.createdAt;
console.log("*******")
// const currentTime = new Date();
// const tokenCreationTime = token.createdAt;

const timeDifference =
(currentTime - tokenCreationTime) / (1000 * 60); // Difference in minutes
// const timeDifference =
// (currentTime - tokenCreationTime) / (1000 * 60); // Difference in minutes
//have to change this
if (timeDifference > 1000000000) {
// Token expired, prompt for a new token
return NextResponse.json({
error: 'Token expired. Ask leader to generate a new token.',
});
}
if (code !== token.token) {

// if (timeDifference > 1000000000) {
// // Token expired, prompt for a new token
// return NextResponse.json({
// error: 'Token expired. Ask leader to generate a new token.',
// });
// }
if (teamCode !== Event1TeamToken.token) {
return NextResponse.json({ error: 'Incorrect token' });
}

console.log("workss")
await Users.findOneAndUpdate(
{ _id: userId },
{ $set: { event1TeamId: team.id, event1TeamRole: 1 } }
);
console.log("---------",team._id)

await Event1.findOneAndUpdate(
{
Expand Down
61 changes: 31 additions & 30 deletions app/api/event1/leaveTeam/route.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,58 @@
import { connectMongoDB } from "@/lib/mongodb";
import { TeamModel } from "@/models/TeamDetails";
import { Users } from "@/models/user.model";
import { NextResponse } from "next/server";
import { connectMongoDB } from '@/lib/mongodb';
import { Event1 } from '@/models/event1.model';
import { Users } from '@/models/user.model';
import { NextResponse } from 'next/server';

import { getToken } from "next-auth/jwt";
import { getTokenDetails } from "../../../../utils/authuser";
import { getToken } from 'next-auth/jwt';
import { getTokenDetails } from '../../../../utils/authuser';


export async function POST(req){
try{
export async function POST(req) {
try {
await connectMongoDB();

const token = await getToken({req})
const auth = token ? token.accessTokenFromBackend : null
const token = await getToken({ req });
const auth = token ? token.accessTokenFromBackend : null;
let userId = await getTokenDetails(auth);

console.log(userId);
const user = await Users.findById(userId);

if (user.event1TeamRole != "1") {
if (user.event1TeamRole != 1) {
return NextResponse.json({
message: "Leader cant leave the team",
message: 'Leader cant leave the team',
});
}

if (!user.event1TeamId) {
return NextResponse.json({
message: "User is not part of any team",
message: 'User is not part of any team',
});
}

const team = await TeamModel.findById(user.event1TeamId);
const team = await Event1.findById(user.event1TeamId);
if (!team) {
return NextResponse.json({
message: "Team not found",
message: 'Team not found',
});
}

team.members.pull(userId);
await team.save();

await Users.findByIdAndUpdate(userId, { $set: { teamId: null, teamRole:-1 } });




return NextResponse.json({ message: "User has left the team successfully ", status: 200, teamDetails: team });




}catch(error) {
console.error("An error occurred:", error);
return NextResponse.json({ message: "Error occurred ", status: 500 });
await Users.findByIdAndUpdate(userId, {
$set: { event1TeamId: null, event1TeamRole: -1 },
});

return NextResponse.json({
message: 'User has left the team successfully ',
status: 200,
teamDetails: team,
});
} catch (error) {
console.error('An error occurred:', error);
return NextResponse.json({
message: 'Error occurred ',
status: 500,
});
}
}
}
42 changes: 42 additions & 0 deletions app/api/login/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { connectMongoDB } from "@/lib/mongodb";
import { Users } from "@/models/user.js";
import { getTokenDetails } from "@/utils/authuser.js";
import { getToken } from "next-auth/jwt";
import { headers } from 'next/headers';
import { NextResponse } from "next/server";


export async function POST(req){
try{
await connectMongoDB();
const headersList = headers()
// const authorization = headersList.get('authorization')
const token = await getToken({req})
//console.log('ff', token)
console.log(token.accessTokenFromBackend);
// const auth = req.headers.get("authorization").split(' ')[1];

let userId = await getTokenDetails(token.accessTokenFromBackend);
console.log(userId);
const user=await Users.findById(userId);
console.log(user);

const {regNo,mobno}=await req.json();

await Users.findByIdAndUpdate(userId,{$set:{regNo:regNo,mobno:mobno}})
// console.log(newUserDetail);
// const { accessToken, refreshToken } = await generateTokens(newUserDetail);
// console.log(accessToken);
// console.log(refreshToken);

//console.log(accessToken);

return NextResponse.json({ message: "User Details entered ", status: 200 });


}catch(error) {
console.error("An error occurred:", error);
return NextResponse.json({ message: "Error occurred ", status: 500 });
}

}
4 changes: 1 addition & 3 deletions app/events/event1/joinTeam/page.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use client'

import Navbar from '@/Components/Navbar';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
Expand Down Expand Up @@ -49,7 +48,7 @@ const JoinTeam = ({ teamCode: propTeamCode }) => {
if (user.hasFilledDetails == false) {
router.push('/');
} else {
if (user.teamId !== null) {
if (user.event1TeamId !== null) {
const redirect = user.teamRole=='1' ? '/events/event1/memberDash' : '/events/event1/leaderDash';
router.push(redirect);
}
Expand Down Expand Up @@ -158,7 +157,6 @@ const JoinTeam = ({ teamCode: propTeamCode }) => {
return (
// tailwind
<div className=" bg-cover bg-no-repeat bg-center" style={{ backgroundImage: 'url(/assets/bg/spceBg.svg)', minHeight: '100vh' }}>
<Navbar />
<div className='flex flex-col justify-center items-center h-screen'>
<div className="w-[90%] sm:w-[55vw] bg-[#141B2B] flex flex-col items-center justify-evenly text-white rounded-lg p-2 min-w-fit min-h-[70vh] m-12">
<h1 className="text-[2.8rem] font-bold m-2 mb-4 text-center">
Expand Down
2 changes: 1 addition & 1 deletion app/events/event1/leaderDash/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export default function LeaderDashboard() {
name={el.name}
Role={el.event1TeamRole === 0 ? 'Leader' : 'Member'}
regNo={el.regNo}
phone={el.mobno}
phone={el.mobNo}
leader={true}
removeMember={() => {
removeMember(el._id);
Expand Down
24 changes: 12 additions & 12 deletions app/events/event1/memberDash/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,12 @@ const TeamPage = () => {
const router = useRouter();

useEffect(() => {
if (router.isReady) {

if (status === "unauthenticated") {
router.push("/")
} else if(status === "authenticated"){
getData()
fetchDataFromBackend();
}
if (status === "unauthenticated") {
router.push("/")
} else if(status === "authenticated"){
console.log('asdf')
getData()
fetchDataFromBackend();
}
}, [status, router])

Expand All @@ -52,9 +50,10 @@ const TeamPage = () => {
.then((data) => {

const user = data.user;
console.log('user;;', user)
if (user.hasFilledDetails == true) {
if (user.event1TeamId !== null) {
// router.push("/");
router.push("/");
if (user.event1TeamRole === '0') {
router.push('/leaderDashboard')
} else {
Expand All @@ -72,7 +71,7 @@ const TeamPage = () => {

const fetchDataFromBackend = () => {
setIsLoading(true);
fetch('/team/getTeamData', {
fetch('/api/event1/getTeamData', {
content: "application/json",
method: "GET",
headers: {
Expand All @@ -98,7 +97,7 @@ const TeamPage = () => {

const leaveTeam = () => {
setIsLoading(true);
fetch( '/user/leaveTeam/'+teamId, {
fetch( '/api/event1/leaveTeam/', {
content: "application/json",
method: "POST",
headers: {
Expand All @@ -108,6 +107,7 @@ const TeamPage = () => {
},
}).then(data=>data.json())
.then(data=>{
console.log('data', data)
if(data.error == false) {
setIsLoading(true);
router.push('/makeTeam')
Expand Down Expand Up @@ -138,7 +138,7 @@ const TeamPage = () => {
<div className="flex flex-wrap justify-center">
{
teamMembersData.map(el=>{
return <Card name={el.firstName} key={el.firstName} regNo={el.regNo} Role={el.event1TeamRole==='0'?'Leader':'Member'} leader={false} phone={el.mobno} imageSrc={boardImg} />
return <Card name={el.name} key={el.name} regNo={el.regNo} Role={el.event1TeamRole===0?'Leader':'Member'} leader={false} phone={el.mobNo} imageSrc={boardImg} />
})
}
</div>
Expand Down
Loading

0 comments on commit e09e9d1

Please sign in to comment.