Skip to content

Commit

Permalink
created the getUserProfile route
Browse files Browse the repository at this point in the history
  • Loading branch information
arogya01 committed Sep 22, 2024
1 parent 37cae1b commit 7d06601
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
64 changes: 63 additions & 1 deletion src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { CreateUserInput, LoginUserInput } from "./user.schema";
import { checkExistingUser, createUser } from "./user.service";
import { checkExistingUser, createUser, fetchUserByUserId } from "./user.service";
import { verifyPassword } from "../../utils/hash";

export const loginHandler = async (
Expand Down Expand Up @@ -61,3 +61,65 @@ export async function signupHandler(
export const getUsersHandler = () => {
console.log("loginHandler");
};




interface DecodedToken {
userId: string;
[key: string]: any;
}

export const getUserProfileHandler = async (
request: FastifyRequest<{
Querystring: {
accessToken: string;
};
}>,
reply: FastifyReply
) => {
console.log("getUserProfileHandler");

try {
// Get the token from the Authorization header
const authHeader = request.headers.authorization;
if (!authHeader) {
reply.code(401).send({ error: 'No authorization header provided' });
return;
}

const token = authHeader.split(' ')[1];
if (!token) {
reply.code(401).send({ error: 'No token provided' });
return;
}

// Decode the token
const decodedToken = request.jwt.decode(token) as DecodedToken;
console.log('decoded', decodedToken);

if (!decodedToken) {
reply.code(401).send({ error: 'Invalid token' });
return;
}

const userId = decodedToken.userId;
if (!userId) {
reply.code(401).send({ error: 'UserId not found in token' });
return;
}

// Find the user in the database
const user = await fetchUserByUserId(Number(userId));
if (!user) {
reply.code(404).send({ error: 'User not found' });
return;
}

// Return the user profile
reply.send(user);
} catch (error) {
console.error('Error in getUserProfileHandler:', error);
reply.code(500).send({ error: 'Internal server error' });
}
};
5 changes: 2 additions & 3 deletions src/modules/user/user.routes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FastifyInstance } from "fastify";
import { loginHandler , signupHandler , getUsersHandler } from "./user.controller";
import { loginHandler , signupHandler , getUsersHandler, getUserProfileHandler } from "./user.controller";
import { $ref } from "./user.schema";


Expand Down Expand Up @@ -27,8 +27,7 @@ async function userRoutes(server: FastifyInstance){
200: $ref("getUserProfileRespSchema")
}
}
}, getUsersHandler);
server.get("/users", getUsersHandler);
}, getUserProfileHandler);
}

export default userRoutes;

0 comments on commit 7d06601

Please sign in to comment.