Skip to content

Commit

Permalink
Add iat check on API request
Browse files Browse the repository at this point in the history
  • Loading branch information
mzyy94 committed Feb 23, 2024
1 parent 276058a commit 325ac47
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
14 changes: 9 additions & 5 deletions src/api/bookmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export const postBookmarkHandlers = factory.createHandlers(
const form = c.req.valid('form');
const url = new URL(form.url);

const { sub: user } = c.get('jwtPayload');
const { sub: user, iat } = c.get('jwtPayload');
const { DB } = env<{ DB: D1Database }>(c);
const db = drizzle(DB);

Expand All @@ -85,12 +85,16 @@ export const postBookmarkHandlers = factory.createHandlers(
}
const { repo, rkey, uri, cid } = record;

const count = await db
.select({ value: users.bookmarkCount })
const userdata = await db
.select({ count: users.bookmarkCount, iat: users.issuedAt })
.from(users)
.where(eq(users.user, user))
.get();
if (!count || count.value > 200) {

if (!userdata || (userdata.iat !== 0 && iat !== userdata.iat)) {
return c.text('unauthorized', 401);
}
if (userdata.count > 200) {
// bookmark limit reached. only DELETE request is allowed for this user at this momen.
return c.json({ error: 'bookmark limit reached', params: { url } }, 405);
}
Expand All @@ -111,7 +115,7 @@ export const postBookmarkHandlers = factory.createHandlers(
db.insert(operations).values({ opcode: 'add', ...result }),
db
.update(users)
.set({ bookmarkCount: count.value + 1 })
.set({ bookmarkCount: userdata.count + 1 })
.where(eq(users.user, user)),
]);
return c.json({ status: 'created', params: { url } }, 201);
Expand Down
9 changes: 6 additions & 3 deletions src/api/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,19 @@ export const registerAccount = factory.createHandlers(
}
}

const now = Math.floor(Date.now() / 1000);

const db = drizzle(DB);
await db
.insert(users)
.values({ handle: handleName, user: did })
.onConflictDoNothing();

.onConflictDoUpdate({
target: users.user,
set: { handle: handleName, issuedAt: now },
});
await savePubkey(c, didDoc.id, findPubkey(didDoc) ?? '');

const { JWT_SECRET } = env<{ JWT_SECRET: string }>(c);
const now = Math.floor(Date.now() / 1000);
const token = await sign(
{ sub: did, iat: now, exp: now + 30 * 24 * 60 * 60 },
JWT_SECRET,
Expand Down

0 comments on commit 325ac47

Please sign in to comment.