Skip to content

Commit

Permalink
user data
Browse files Browse the repository at this point in the history
  • Loading branch information
suraj-tekdi committed Jan 8, 2025
1 parent 043bf23 commit 300d305
Showing 1 changed file with 131 additions and 132 deletions.
263 changes: 131 additions & 132 deletions src/adapters/hasura/altUser.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { ALTUserUpdateDto } from "src/altUser/dto/alt-user-update.dto";
export class ALTHasuraUserService {
axios = require("axios");

constructor(private httpService: HttpService) {}
constructor(private httpService: HttpService) { }

public async getUser(userId: string, request: any) {
const decoded: any = jwt_decode(request.headers.authorization);
Expand Down Expand Up @@ -892,9 +892,8 @@ export class ALTHasuraUserService {
const [firstName, lastName] = obj.name.split(" ");

// Step 1: Extract initials
const initials = `${firstName[0].toLowerCase()}${
lastName ? lastName[0].toLowerCase() : ""
}`;
const initials = `${firstName[0].toLowerCase()}${lastName ? lastName[0].toLowerCase() : ""
}`;

const dob = obj.dateOfBirth
.trim()
Expand Down Expand Up @@ -987,7 +986,7 @@ export class ALTHasuraUserService {
// Authorization: `Bearer ${token}`,
// },
// });

// // If the token is valid, process the response
// const userInfo = keycloakResponse.data;
// console.log("userInfo", userInfo)
Expand All @@ -1000,7 +999,7 @@ export class ALTHasuraUserService {
// data: null,
// });
// }

// // Extract roles and username from the Keycloak response
// // const altUserRoles = userInfo["https://hasura.io/jwt/claims"]["x-hasura-allowed-roles"];
// // const username = userInfo.preferred_username;
Expand Down Expand Up @@ -1108,87 +1107,87 @@ export class ALTHasuraUserService {
// }
// }



async validateToken(request: any, res: any) {
try {
// Extract the Authorization header
const authToken = request.headers.authorization;
if (!authToken) {
return this.sendErrorResponse(res, 400, "Authorization header is missing");
}

// Ensure token starts with "Bearer "
if (!authToken.startsWith("Bearer ")) {
return this.sendErrorResponse(
res,
400,
"Authorization token must be in the form of 'Bearer <token>'"
);
}
async validateToken(request: any, res: any) {
try {
// Extract the Authorization header
const authToken = request.headers.authorization;
if (!authToken) {
return this.sendErrorResponse(res, 400, "Authorization header is missing");
}

// Extract token
const token = authToken.split(" ")[1];
// Ensure token starts with "Bearer "
if (!authToken.startsWith("Bearer ")) {
return this.sendErrorResponse(
res,
400,
"Authorization token must be in the form of 'Bearer <token>'"
);
}

// Validate token using Keycloak
const userInfo = await this.validateWithKeycloak(token);
if (!userInfo) {
return this.sendErrorResponse(res, 401, "Invalid token");
}
// Extract token
const token = authToken.split(" ")[1];

// Decode the token
const decoded: any = jwt_decode(token);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (decoded.exp && decoded.exp < currentTimestamp) {
return this.sendErrorResponse(res, 401, "Token has expired");
}
// Validate token using Keycloak
const userInfo = await this.validateWithKeycloak(token);
if (!userInfo) {
return this.sendErrorResponse(res, 401, "Invalid token");
}

// Extract user roles and username
const roles = decoded["https://hasura.io/jwt/claims"]["x-hasura-allowed-roles"];
const username = decoded.preferred_username;
// Decode the token
const decoded: any = jwt_decode(token);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (decoded.exp && decoded.exp < currentTimestamp) {
return this.sendErrorResponse(res, 401, "Token has expired");
}

// Fetch user details from GraphQL
const userData = await this.fetchUserData(username, token, roles);
if (!userData) {
return this.sendErrorResponse(res, 404, "User not found or inactive");
}
// Extract user roles and username
const roles = decoded["https://hasura.io/jwt/claims"]["x-hasura-allowed-roles"];
const username = decoded.preferred_username;

// Fetch user points
const userPoints = await this.getUserPoints(request, token);
// Fetch user details from GraphQL
const userData = await this.fetchUserData(username, token, roles);
if (!userData) {
return this.sendErrorResponse(res, 404, "User not found or inactive");
}

// Append points to user data if available
if (userPoints?.length > 0) {
userData[0].points = userPoints;
}
// Fetch user points
const userPoints = await this.getUserPoints(request, token);

// Append points to user data if available
if (userPoints?.length > 0) {
userData[0].points = userPoints;
}

// Send success response
return this.sendSuccessResponse(res, 200, "Authenticated", userData);
// Send success response
return this.sendSuccessResponse(res, 200, "Authenticated", userData);

} catch (error) {
console.error("Error validating token:", error.message);
return this.sendErrorResponse(res, 400, "Invalid token");
} catch (error) {
console.error("Error validating token:", error.message);
return this.sendErrorResponse(res, 400, "Invalid token");
}
}
}

async validateWithKeycloak(token: string) {
try {
const response = await this.axios({
method: "GET",
url: `${process.env.URL}/auth/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/userinfo`,
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.data;
} catch (error) {
console.error("Keycloak validation error:", error.message);
return null;
async validateWithKeycloak(token: string) {
try {
const response = await this.axios({
method: "GET",
url: `${process.env.URL}/auth/realms/hasura-app/protocol/openid-connect/userinfo`,
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.data;
} catch (error) {
console.error("Keycloak validation error:", error.message);
return null;
}
}
}

async fetchUserData(username: string, token: string, roles: string[]) {
const query = {
query: `
async fetchUserData(username: string, token: string, roles: string[]) {
const query = {
query: `
query searchUser($username: String!) {
Users(where: {username: {_eq: $username}, status: {_eq: true}}) {
userId
Expand Down Expand Up @@ -1219,35 +1218,35 @@ async fetchUserData(username: string, token: string, roles: string[]) {
}
}
`,
variables: { username },
};

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

try {
const response = await this.axios(config);
return response.data.data.Users || null;
} catch (error) {
console.error("GraphQL fetch error:", error.message);
return null;
const config = {
method: "post",
url: process.env.ALTHASURA,
headers: {
Authorization: `Bearer ${token}`,
"x-hasura-role": getUserRole(roles),
"Content-Type": "application/json",
},
data: query,
};

try {
const response = await this.axios(config);
return response.data.data.Users || null;
} catch (error) {
console.error("GraphQL fetch error:", error.message);
return null;
}
}
}

async getUserPoints(request: any, token: string) {
const decoded: any = jwt_decode(token);
const userId = decoded["https://hasura.io/jwt/claims"]["x-hasura-user-id"];
async getUserPoints(request: any, token: string) {
const decoded: any = jwt_decode(token);
const userId = decoded["https://hasura.io/jwt/claims"]["x-hasura-user-id"];

const query = {
query: `
const query = {
query: `
query MyQuery($userId: String!) {
UserPoints(
where: { user_id: { _eq: $userId } }
Expand All @@ -1264,45 +1263,45 @@ async getUserPoints(request: any, token: string) {
}
}
`,
variables: { userId },
};

const config = {
method: "post",
url: process.env.ALTHASURA,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: query,
};
variables: { userId },
};

try {
const response = await this.axios(config);
return response.data.data.UserPoints || [];
} catch (error) {
console.error("Error fetching user points:", error.message);
return [];
const config = {
method: "post",
url: process.env.ALTHASURA,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
data: query,
};

try {
const response = await this.axios(config);
return response.data.data.UserPoints || [];
} catch (error) {
console.error("Error fetching user points:", error.message);
return [];
}
}
}

sendErrorResponse(res: any, statusCode: number, message: string) {
return res.status(statusCode).send({
success: false,
status: "Unauthorized",

data: null,
});
}
sendErrorResponse(res: any, statusCode: number, message: string) {
return res.status(statusCode).send({
success: false,
status: "Unauthorized",
message,
data: null,
});
}

sendSuccessResponse(res: any, statusCode: number, message: string, data: any) {
return res.status(statusCode).send({
success: true,
status: "Authenticated",

data,
});
}
sendSuccessResponse(res: any, statusCode: number, message: string, data: any) {
return res.status(statusCode).send({
success: true,
status: "Authenticated",
message,
data,
});
}



Expand Down

0 comments on commit 300d305

Please sign in to comment.