Skip to content

Commit

Permalink
refactor: Update setHashedUserIdCookie method in analytics controller (
Browse files Browse the repository at this point in the history
…#20229)

* refactor: Update setHashedUserIdCookie method in analytics controller

This commit updates the setHashedUserIdCookie method in the analytics controller. The changes include:
- Adding a server-side implementation to determine the appropriate domain for setting the cookie based on the request hostname

* nit fix :)

Co-authored-by: Filip Troníček <[email protected]>

---------

Co-authored-by: Filip Troníček <[email protected]>
  • Loading branch information
Siddhant-K-code and filiptronicek authored Sep 18, 2024
1 parent 192727f commit d5208cb
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions components/server/src/analytics-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class AnalyticsController {
const clientHeaderFields = toClientHeaderFields(req);
const event = req.body as RemoteIdentifyMessage;
this.identifyUser(req.user.id, event, clientHeaderFields);
this.setHashedUserIdCookie(req.user.id, res);
this.setHashedUserIdCookie(req.user.id, req, res);
res.sendStatus(200);
} catch (e) {
console.error("failed to identify user", e);
Expand Down Expand Up @@ -180,15 +180,33 @@ export class AnalyticsController {
}
}

private setHashedUserIdCookie(userId: string, res: express.Response): void {
private setHashedUserIdCookie(userId: string, req: express.Request, res: express.Response): void {
const hashedUserId = crypto.createHash("md5").update(userId).digest("hex");
const oneYearInSeconds = 365 * 24 * 60 * 60;
res.cookie("gitpod_hashed_user_id", hashedUserId, {
domain: ".gitpod.io",
maxAge: oneYearInSeconds * 1000, // Convert to milliseconds
httpOnly: true,
secure: true,
sameSite: "lax",
});

/**
* This implementation is inspired by isGitpodIo() from /workspace/gitpod/components/dashboard/src/utils.ts
* We're using a server-side equivalent here because:
* 1. The original function is client-side code using window.location
* 2. This is server-side code that needs to use the request object
* 3. We need to determine the appropriate domain for setting the cookie
*/
const hostname = req.hostname;
if (
hostname === "gitpod.io" ||
hostname === "gitpod-staging.com" ||
hostname.endsWith("gitpod-dev.com") ||
hostname.endsWith("gitpod-io-dev.com")
) {
const domain = `.${hostname}`;

res.cookie("gitpod_hashed_user_id", hashedUserId, {
domain: domain,
maxAge: oneYearInSeconds * 1000, // Convert to milliseconds
httpOnly: true,
secure: true,
sameSite: "lax",
});
}
}
}

0 comments on commit d5208cb

Please sign in to comment.