Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Generate new session for mobile handoff
  • Loading branch information
regalijan committed Oct 20, 2023
1 parent fa2f495 commit 98a56f2
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions functions/api/auth/mobile/token.ts
@@ -1,23 +1,49 @@
import { jsonError } from "../../../common.js";
import tokenPrefixes from "../../../../data/token_prefixes.json";

export async function onRequestGet(context: RequestContext) {
const { current_user: currentUser } = context.data;

if (!currentUser) return jsonError("Unauthorized", 401);

const header = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
const tokenStart =
tokenPrefixes[Math.round(Math.random() * (tokenPrefixes.length - 1))] + "_";
const tokenId =
tokenStart +
`${crypto.randomUUID()}${crypto.randomUUID()}${crypto.randomUUID()}${crypto.randomUUID()}`.replaceAll(
"-",
"",
);

const cookies = (context.request.headers.get("cookie") as string).split("; ");
const sessionCookie = cookies.find((c) => c.startsWith("_s=")) as string;
await context.env.DATA.put(
`auth_${btoa(
String.fromCharCode(
...new Uint8Array(
await crypto.subtle.digest(
"SHA-512",
new TextEncoder().encode(tokenId),
),
),
),
)
.replaceAll("+", "-")
.replaceAll("/", "_")
.replaceAll("=", "")}`,
JSON.stringify(currentUser),
{
expirationTtl: currentUser.expires_in + 1209600,
},
);

const claimSet = btoa(
JSON.stringify({
email: currentUser.email,
email_verified: true,
exp: Math.floor(currentUser.refresh_at / 1000),
exp: Math.floor(Date.now() / 1000) + currentUser.expires_in,
iat: Math.floor(Date.now() / 1000),
iss: "https://carcrushers.cc/auth/mobile/token",
jti: sessionCookie.replace("_s=", ""),
jti: tokenId,
name: currentUser.username,
permissions: currentUser.permissions,
picture: currentUser.avatar ?? "https://carcrushers.cc/files/logo192.png",
Expand Down

0 comments on commit 98a56f2

Please sign in to comment.