Skip to content

Commit

Permalink
Merge pull request #88 from YoginiTayade/getUser
Browse files Browse the repository at this point in the history
validateToken api
  • Loading branch information
suraj-tekdi authored Dec 16, 2024
2 parents fa3d979 + a6e675c commit d6dfc26
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
118 changes: 118 additions & 0 deletions src/adapters/hasura/altUser.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -950,4 +950,122 @@ export class ALTHasuraUserService {
const response = await this.axios(config);
return response.data.data.Users.length > 0; // Returns true if username is taken
}
public async validateToken(request: any, res: any) {
// Check if Authorization header exists
const authToken = request.headers.authorization;
if (!authToken) {
return res.status(400).send({
success: false,
status: "Unauthorized",
message: "Authorization header is missing",
data: null,
});
}

// Check if token starts with 'Bearer' and has a token
if (!authToken.startsWith("Bearer ")) {
return res.status(400).send({
success: false,
status: "Unauthorized",
message:
"Authorization token must be in the form of 'Bearer <token>' in the headers",
data: null,
});
}

const token = authToken.split(" ")[1]; // Extract the token part

try {
// Decode the token
const decoded: any = jwt_decode(token);
//Check if token has expired
const currentTimestamp = Math.floor(Date.now() / 1000); // Get current timestamp in seconds
if (decoded.exp && decoded.exp < currentTimestamp) {
return res.status(401).send({
success: false,
status: "Unauthorized",
message: "Token has expired",
data: null,
});
}

// Extract roles and username
const altUserRoles =
decoded["https://hasura.io/jwt/claims"]["x-hasura-allowed-roles"];
const username = decoded.preferred_username;

// Prepare GraphQL request data
const data = {
query: `query searchUser($username:String) {
Users(where: {username: {_eq: $username}, status: {_eq: true}}) {
userId
name
username
email
mobile
gender
dateOfBirth
role
status
createdAt
updatedAt
createdBy
updatedBy
GroupMemberships(where: {status: {_eq: true}}) {
Group {
board
medium
grade
groupId
}
}
}
}`,
variables: { username: username },
};

const config = {
method: "post",
url: process.env.ALTHASURA,
headers: {
Authorization: `Bearer ${token}`,
"x-hasura-role": getUserRole(altUserRoles),
"Content-Type": "application/json",
},
data: data,
};

console.log(altUserRoles);

// Send GraphQL request
const response = await this.axios(config);

// Handle errors in the response
if (response?.data?.errors) {
return res.status(401).send({
success: false,
status: "Unauthorized",
message: "INVALID",
data: response.data.errors.data[0].message,
});
} else {
// Return successful response
const result = response.data.data.Users;
return res.status(200).send({
success: true,
status: "Authenticated",
message: "SUCCESS",
data: result,
});
}
} catch (error) {
// Handle any errors, including invalid token
return res.status(400).send({
success: false,
status: "Unauthorized",
message: "Invalid token",
data: null,
});
}
}
}
5 changes: 5 additions & 0 deletions src/altUser/altUser.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,9 @@ export class ALTUserController {
response.status(HttpStatus.CREATED).send(deactivateUserResponse);
}
}
@Post("/validateToken")
@ApiBasicAuth("access-token")
public async getUserByToken(@Req() req: Request, @Res() response: Response) {
return await this.hasuraUserService.validateToken(req, response);
}
}

0 comments on commit d6dfc26

Please sign in to comment.