Skip to content

Commit

Permalink
Merge pull request #28 from smritidoneria/main
Browse files Browse the repository at this point in the history
fixes
  • Loading branch information
smritidoneria authored Mar 14, 2024
2 parents e444822 + b7481ff commit 9672adb
Show file tree
Hide file tree
Showing 7 changed files with 181 additions and 24 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
3 changes: 2 additions & 1 deletion app/api/event1/getTeamData/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ export async function GET(req) {
}
console.log(user);

const teamId = user.event1TeamId;
const teamId = user.teamId;
const team = await Event1.findById(teamId).populate('members');
if (!team) {
return NextResponse.json({ message: 'Team is not there ' });
}


return NextResponse.json({
message: 'Team Details sent. ',
status: 200,
Expand Down
10 changes: 5 additions & 5 deletions app/api/event1/getTeamViaToken/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ 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({ teamCode: 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
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 });
}

}
103 changes: 103 additions & 0 deletions components/userDetails.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"use client"
import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';

export default function UserDetails() {
const { data: session, status } = useSession();

// use session chl rha h baaki frondend me data kese lena h aap log dekh lo
//console.log("fsdbhbsbvdfwad",data);
// console.log("fgfcgcgfdfdsds",session);
//console.log(data);

const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [regNo, setRegNo] = useState('');
const [mobno, setMobno] = useState('');
// const router = useRouter();

const handleSubmit = async () => {

console.log('button ')

try {
const response = await fetch('http://localhost:3001/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
Authorization:`Bearer ${session.accessTokenBackend}`,
'Access-Control-Allow-Origin':'*',
body: JSON.stringify({
firstName,
lastName,
regNo,
mobno
})
});

if (response.ok) {
console.log('Data saved successfully');

setFirstName('');
setLastName('');
setRegNo('');
setMobno('');

// router.push('/')

} else {
console.error('Failed to save data:', response.statusText);
}
} catch (error) {
console.error('Error saving data:', error);
}
};

return (
<div>
<div>
<label htmlFor="firstName">First Name:</label>
<input
type="text"
id="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
style={{ color: 'black' }}
/>
</div>
<div>
<label htmlFor="lastName">Last Name:</label>
<input
type="text"
id="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
style={{ color: 'black' }}
/>
</div>
<div>
<label htmlFor="regNo">Registration Number:</label>
<input
type="text"
id="regNo"
value={regNo}
onChange={(e) => setRegNo(e.target.value)}
style={{ color: 'black' }}
/>
</div>
<div>
<label htmlFor="mobNo">Mobile Number:</label>
<input
type="text"
id="mobNo"
value={mobno}
onChange={(e) => setMobno(e.target.value)}
style={{ color: 'black' }}
/>
</div>
<button onClick={()=>handleSubmit()}>Submit</button>
</div>
);
}
4 changes: 3 additions & 1 deletion utils/authuser.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ export async function getTokenDetails(token) {
connectMongoDB();
console.log("fsdaghjgdshbfzhjdbvsjhbdfhjcbghjgfd")
const tokenDetails = await jwtVerify(

token,
new TextEncoder().encode(process.env.ACCESS_TOKEN_SECRET)
);
console.log("yha aa rha h")


const userId = tokenDetails.payload._id;
// console.log(userId)
console.log("+++++++",userId)

const user = await Users.findById(userId);

Expand Down

0 comments on commit 9672adb

Please sign in to comment.