-
Notifications
You must be signed in to change notification settings - Fork 0
add token based authantication #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
17627e1
add token based authantication
cobraprojects 8e7c350
fix issues
cobraprojects ad08425
make login and register helpers work on token driver as well
cobraprojects 338d02f
fix token abilities
cobraprojects a468e18
fix user id type
cobraprojects File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import { TokenPostsClient } from './token-posts-client' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| export default function ApiTokenPostsPage() { | ||
| return <TokenPostsClient /> | ||
| } |
129 changes: 129 additions & 0 deletions
129
apps/blog-next/app/api-token-posts/token-posts-client.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| 'use client' | ||
|
|
||
| import { type FormEvent, useState } from 'react' | ||
|
|
||
| type JsonResult = { | ||
| readonly status: number | ||
| readonly payload: unknown | ||
| } | ||
|
|
||
| function isRecord(value: unknown): value is Readonly<Record<string, unknown>> { | ||
| return !!value && typeof value === 'object' && !Array.isArray(value) | ||
| } | ||
|
|
||
| function getStringField(value: unknown, field: string): string { | ||
| if (!isRecord(value)) { | ||
| return '' | ||
| } | ||
|
|
||
| const fieldValue = value[field] | ||
| return typeof fieldValue === 'string' ? fieldValue : '' | ||
| } | ||
|
|
||
| async function readJson(response: Response): Promise<unknown> { | ||
| try { | ||
| return await response.json() | ||
| } catch { | ||
| return { | ||
| ok: false, | ||
| message: 'Response was not valid JSON.', | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export function TokenPostsClient() { | ||
| const [tokenResult, setTokenResult] = useState<JsonResult | null>(null) | ||
| const [postsResult, setPostsResult] = useState<JsonResult | null>(null) | ||
| const [creatingToken, setCreatingToken] = useState(false) | ||
| const [fetchingPosts, setFetchingPosts] = useState(false) | ||
| const generatedToken = getStringField(tokenResult?.payload, 'token') | ||
|
|
||
| async function createToken(event: FormEvent<HTMLFormElement>) { | ||
| event.preventDefault() | ||
| setCreatingToken(true) | ||
| setPostsResult(null) | ||
|
|
||
| try { | ||
| const response = await fetch('/api/v1/tokens', { | ||
| method: 'POST', | ||
| body: new FormData(event.currentTarget), | ||
| }) | ||
|
|
||
| setTokenResult({ | ||
| status: response.status, | ||
| payload: await readJson(response), | ||
| }) | ||
| } finally { | ||
| setCreatingToken(false) | ||
| } | ||
| } | ||
|
|
||
| async function fetchPosts(event: FormEvent<HTMLFormElement>) { | ||
| event.preventDefault() | ||
| setFetchingPosts(true) | ||
|
|
||
| const formData = new FormData(event.currentTarget) | ||
| const token = String(formData.get('token') ?? '').trim() | ||
|
|
||
| try { | ||
| const response = await fetch('/api/v1/posts', { | ||
| headers: token ? { authorization: `Bearer ${token}` } : undefined, | ||
| }) | ||
|
|
||
| setPostsResult({ | ||
| status: response.status, | ||
| payload: await readJson(response), | ||
| }) | ||
| } finally { | ||
| setFetchingPosts(false) | ||
| } | ||
| } | ||
|
|
||
| return ( | ||
| <section style={{ display: 'grid', gap: '1rem', maxWidth: '44rem' }}> | ||
| <div> | ||
| <h1 style={{ margin: '0 0 0.5rem 0' }}>API token posts</h1> | ||
| <p style={{ margin: 0, color: '#94a3b8' }}>Generate a bearer token from credentials, then use it to fetch protected posts.</p> | ||
| </div> | ||
|
|
||
| <form onSubmit={createToken} style={{ display: 'grid', gap: '0.9rem', padding: '1.25rem', borderRadius: '1rem', background: '#111827', border: '1px solid rgba(148, 163, 184, 0.16)' }}> | ||
| <h2 style={{ margin: 0, fontSize: '1.1rem' }}>Create token</h2> | ||
| <label style={{ display: 'grid', gap: '0.35rem' }}> | ||
| <span>Email</span> | ||
| <input name="email" type="email" placeholder="editor@example.com" required /> | ||
| </label> | ||
| <label style={{ display: 'grid', gap: '0.35rem' }}> | ||
| <span>Password</span> | ||
| <input name="password" type="password" placeholder="secret" required /> | ||
| </label> | ||
| <button type="submit" disabled={creatingToken}>{creatingToken ? 'Creating...' : 'Create token'}</button> | ||
| </form> | ||
|
|
||
| {tokenResult ? ( | ||
| <section style={{ display: 'grid', gap: '0.65rem', padding: '1.25rem', borderRadius: '1rem', background: '#111827', border: '1px solid rgba(148, 163, 184, 0.16)' }}> | ||
| <h2 style={{ margin: 0, fontSize: '1.1rem' }}>Token response ({tokenResult.status})</h2> | ||
| {generatedToken ? ( | ||
| <textarea readOnly value={generatedToken} rows={3} style={{ width: '100%', boxSizing: 'border-box' }} /> | ||
| ) : null} | ||
| <pre style={{ margin: 0, overflowX: 'auto' }}>{JSON.stringify(tokenResult.payload, null, 2)}</pre> | ||
| </section> | ||
| ) : null} | ||
|
|
||
| <form onSubmit={fetchPosts} style={{ display: 'grid', gap: '0.9rem', padding: '1.25rem', borderRadius: '1rem', background: '#111827', border: '1px solid rgba(148, 163, 184, 0.16)' }}> | ||
| <h2 style={{ margin: 0, fontSize: '1.1rem' }}>Fetch posts</h2> | ||
| <label style={{ display: 'grid', gap: '0.35rem' }}> | ||
| <span>Bearer token</span> | ||
| <textarea name="token" rows={3} required /> | ||
| </label> | ||
| <button type="submit" disabled={fetchingPosts}>{fetchingPosts ? 'Fetching...' : 'Fetch posts'}</button> | ||
| </form> | ||
|
|
||
| {postsResult ? ( | ||
| <section style={{ display: 'grid', gap: '0.65rem', padding: '1.25rem', borderRadius: '1rem', background: '#111827', border: '1px solid rgba(148, 163, 184, 0.16)' }}> | ||
| <h2 style={{ margin: 0, fontSize: '1.1rem' }}>Posts response ({postsResult.status})</h2> | ||
| <pre style={{ margin: 0, overflowX: 'auto' }}>{JSON.stringify(postsResult.payload, null, 2)}</pre> | ||
| </section> | ||
| ) : null} | ||
| </section> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import auth from '@holo-js/auth' | ||
|
|
||
| import Post from '@/server/models/Post' | ||
|
|
||
| export async function GET() { | ||
| const currentUser = await auth.guard('api').user() | ||
| const userId = currentUser?.id | ||
|
|
||
| if (typeof userId === 'undefined') { | ||
| return Response.json({ | ||
| ok: false, | ||
| message: 'Unauthenticated.', | ||
| }, { status: 401 }) | ||
| } | ||
|
|
||
| const posts = await Post | ||
| .with('category', 'tags') | ||
| .where('user_id', Number(userId)) | ||
| .orderBy('published_at', 'desc') | ||
| .get() | ||
|
|
||
| return Response.json({ | ||
| ok: true, | ||
| posts, | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import auth, { verifyPassword } from '@holo-js/auth' | ||
|
|
||
| import User from '@/server/models/User' | ||
|
|
||
| export async function POST(request: Request) { | ||
| const formData = await request.formData() | ||
| const email = String(formData.get('email') ?? '').trim() | ||
| const password = String(formData.get('password') ?? '') | ||
|
|
||
| if (!email || !password) { | ||
| return Response.json({ | ||
| ok: false, | ||
| message: 'Email and password are required.', | ||
| }, { status: 422 }) | ||
| } | ||
|
|
||
| const currentUser = await User.where('email', email).first() | ||
| const passwordHash = currentUser?.get('password') | ||
| const passwordMatches = typeof passwordHash === 'string' | ||
| ? await verifyPassword(password, passwordHash) | ||
| : false | ||
|
|
||
| if (!currentUser || !passwordMatches) { | ||
| return Response.json({ | ||
| ok: false, | ||
| message: 'Invalid credentials.', | ||
| }, { status: 401 }) | ||
| } | ||
|
|
||
| const token = await auth.tokens.create(currentUser, { | ||
| guard: 'api', | ||
| name: 'browser-posts-api', | ||
| abilities: ['posts.read'], | ||
| }) | ||
|
|
||
| return Response.json({ | ||
| ok: true, | ||
| token: token.plainTextToken, | ||
| tokenId: token.id, | ||
| abilities: token.abilities, | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
User enumeration via timing side-channel.
When the email doesn't match a user,
verifyPasswordis skipped and the response returns almost immediately, whereas a valid email with a wrong password incurs the full hash-verification cost (typically 100–500ms for argon2/bcrypt). Although the error message is intentionally generic, the timing delta lets an attacker enumerate valid accounts. The same pattern appears in the Nuxt and SvelteKit token endpoints.Recommend always invoking
verifyPasswordagainst a stable dummy hash when the user is not found so the response time is independent of account existence.🛡️ Proposed fix to equalize response timing
DUMMY_PASSWORD_HASHshould be a precomputed argon2/bcrypt hash of an arbitrary string, generated once and stored as a module-level constant (not regenerated per request).🤖 Prompt for AI Agents