-
Notifications
You must be signed in to change notification settings - Fork 0
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
set up basic auth with username & password #13
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
a26928e
set up basic auth with username & password
mrkarimoff 2074878
set up shadcn UI
mrkarimoff 4cc0e0b
polish up the ui for sign in and sign up pages with shadcn
mrkarimoff ffafd09
refactor sign in and sign up functionalities to use validate fields a…
mrkarimoff 8753cf4
implement requirePageAuth with validateRequest
mrkarimoff b309354
handle redirection after sign in and sign up via validateRequest
mrkarimoff 9f7eb59
refactor sign out functionality
mrkarimoff 70c82d3
refactor next.config.mjs to remove experimental serverComponentsExter…
mrkarimoff 48c0c51
update pnpm-lock.yaml file to install packages with pnpm 9.1.1 to res…
mrkarimoff 5715ae3
merge main into feat/basic-auth-setup and resolve conflicts except th…
mrkarimoff b033169
fix linting errors (some are left for later to figure out)
mrkarimoff e6128f7
adjust code based on knip errors
mrkarimoff 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 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,178 @@ | ||
'use server'; | ||
|
||
import { hash, verify } from '@node-rs/argon2'; | ||
import { eq } from 'drizzle-orm'; | ||
import { generateIdFromEntropySize } from 'lucia'; | ||
import { revalidatePath } from 'next/cache'; | ||
import { cookies } from 'next/headers'; | ||
import { db } from '~/drizzle/db'; | ||
import { user } from '~/drizzle/schema'; | ||
import { lucia, validateRequest } from '~/utils/auth'; | ||
import { | ||
createUserFormDataSchema, | ||
getUserFormDataSchema, | ||
} from '~/utils/authSchema'; | ||
|
||
export async function signup( | ||
currentState: { | ||
success: boolean; | ||
error: null | string; | ||
}, | ||
formData: FormData, | ||
) { | ||
const parsedFormData = createUserFormDataSchema.safeParse(formData); | ||
|
||
if (!parsedFormData.success) { | ||
return { | ||
success: false, | ||
error: parsedFormData.error.message, | ||
}; | ||
} | ||
|
||
try { | ||
const { username, password } = parsedFormData.data; | ||
|
||
const passwordHash = await hash(password, { | ||
// recommended minimum parameters | ||
memoryCost: 19456, | ||
timeCost: 2, | ||
outputLen: 32, | ||
parallelism: 1, | ||
}); | ||
|
||
const userId = generateIdFromEntropySize(10); | ||
|
||
// check if username is taken | ||
const [existingUser] = await db | ||
.select() | ||
.from(user) | ||
.where(eq(user.username, username)) | ||
.limit(1); | ||
|
||
if (existingUser) throw new Error('Username already taken!'); | ||
|
||
// create user | ||
await db.insert(user).values({ | ||
id: userId, | ||
username, | ||
passwordHash, | ||
}); | ||
|
||
const session = await lucia.createSession(userId, {}); | ||
const sessionCookie = lucia.createSessionCookie(session.id); | ||
cookies().set( | ||
sessionCookie.name, | ||
sessionCookie.value, | ||
sessionCookie.attributes, | ||
); | ||
return { error: null, success: true }; | ||
} catch (error) { | ||
return { | ||
success: false, | ||
error: 'Username already taken!', | ||
}; | ||
} | ||
} | ||
|
||
export async function signin( | ||
currentState: { | ||
success: boolean; | ||
error: null | string; | ||
}, | ||
formData: FormData, | ||
) { | ||
const parsedFormData = getUserFormDataSchema.safeParse(formData); | ||
|
||
if (!parsedFormData.success) { | ||
return { | ||
success: false, | ||
error: parsedFormData.error.message, | ||
}; | ||
} | ||
|
||
try { | ||
const { username, password } = parsedFormData.data; | ||
|
||
const [existingUser] = await db | ||
.select() | ||
.from(user) | ||
.where(eq(user.username, username)) | ||
.limit(1); | ||
|
||
if (!existingUser) { | ||
// NOTE: | ||
// Returning immediately allows malicious actors to figure out valid usernames from response times, | ||
// allowing them to only focus on guessing passwords in brute-force attacks. | ||
// As a preventive measure, you may want to hash passwords even for invalid usernames. | ||
// However, valid usernames can be already be revealed with the signup page among other methods. | ||
// It will also be much more resource intensive. | ||
// Since protecting against this is non-trivial, | ||
// it is crucial your implementation is protected against brute-force attacks with login throttling etc. | ||
// If usernames are public, you may outright tell the user that the username is invalid. | ||
// eslint-disable-next-line no-console | ||
console.log('invalid username'); | ||
return { | ||
success: false, | ||
error: 'Incorrect username or password!', | ||
}; | ||
} | ||
|
||
const validPassword = await verify(existingUser.passwordHash, password, { | ||
memoryCost: 19456, | ||
timeCost: 2, | ||
outputLen: 32, | ||
parallelism: 1, | ||
}); | ||
if (!validPassword) { | ||
return { | ||
success: false, | ||
error: 'Incorrect username or password!', | ||
}; | ||
} | ||
|
||
const session = await lucia.createSession(existingUser.id, {}); | ||
const sessionCookie = lucia.createSessionCookie(session.id); | ||
cookies().set( | ||
sessionCookie.name, | ||
sessionCookie.value, | ||
sessionCookie.attributes, | ||
); | ||
|
||
return { | ||
success: true, | ||
error: null, | ||
}; | ||
} catch (error) { | ||
// eslint-disable-next-line no-console | ||
console.error('Error while signing in', error); | ||
return { | ||
success: false, | ||
error: 'Something went wrong! Please try again.', | ||
}; | ||
} | ||
} | ||
|
||
export async function signout() { | ||
const { session } = await validateRequest(); | ||
if (!session) { | ||
return { | ||
success: false, | ||
error: 'Unauthorized', | ||
}; | ||
} | ||
|
||
await lucia.invalidateSession(session.id); | ||
|
||
const sessionCookie = lucia.createBlankSessionCookie(); | ||
cookies().set( | ||
sessionCookie.name, | ||
sessionCookie.value, | ||
sessionCookie.attributes, | ||
); | ||
|
||
revalidatePath('/'); | ||
return { | ||
success: true, | ||
error: null, | ||
}; | ||
} |
This file contains 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,11 @@ | ||
"use client"; | ||
|
||
import React from "react"; | ||
import { signout } from "~/actions/auth"; | ||
import { Button } from "~/components/ui/button"; | ||
|
||
const SignOutBtn = () => { | ||
return <Button onClick={() => void signout()}>Sign Out</Button>; | ||
}; | ||
|
||
export default SignOutBtn; |
This file contains 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 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 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,41 @@ | ||
"use client"; | ||
|
||
import { useFormState } from "react-dom"; | ||
import { signin } from "~/actions/auth"; | ||
import { Button } from "~/components/ui/button"; | ||
import { Input } from "~/components/ui/input"; | ||
import { Label } from "~/components/ui/label"; | ||
|
||
const SignInForm = () => { | ||
const initialState = { error: null, success: false }; | ||
const [formState, formAction] = useFormState(signin, initialState); | ||
|
||
return ( | ||
<form action={formAction}> | ||
{formState.error && ( | ||
<div className="text-red-500 text-center text-sm"> | ||
{formState.error} | ||
</div> | ||
)} | ||
|
||
<div className="flex flex-col gap-3 p-2"> | ||
<Label htmlFor="username">Username</Label> | ||
<Input name="username" id="username" placeholder="username..." /> | ||
</div> | ||
<br /> | ||
<div className="flex flex-col gap-3 p-2"> | ||
<Label htmlFor="password">Password</Label> | ||
<Input | ||
type="password" | ||
name="password" | ||
id="password" | ||
placeholder="password..." | ||
/> | ||
</div> | ||
<br /> | ||
<Button>Continue</Button> | ||
</form> | ||
); | ||
}; | ||
|
||
export default SignInForm; |
This file contains 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,39 @@ | ||
import Link from "next/link"; | ||
import { redirect } from "next/navigation"; | ||
import { | ||
Card, | ||
CardContent, | ||
CardDescription, | ||
CardHeader, | ||
CardTitle, | ||
} from "~/components/ui/card"; | ||
import { validateRequest } from "~/utils/auth"; | ||
import SignInForm from "./_components/SignInForm"; | ||
|
||
export default async function Page() { | ||
const { session, user } = await validateRequest(); | ||
|
||
if (session && user) { | ||
// If the user is already signed in, redirect to the home page | ||
redirect("/"); | ||
} | ||
|
||
return ( | ||
<div className="grid w-full items-center h-[100vh] justify-center gap-1.5"> | ||
<Card className="w-[28rem] m-3"> | ||
<CardHeader> | ||
<CardTitle>Sign in to Studio</CardTitle> | ||
<CardDescription> | ||
Don't have an account?{" "} | ||
<Link className="text-blue-400 underline" href={"/signup"}> | ||
Sign Up | ||
</Link> | ||
</CardDescription> | ||
</CardHeader> | ||
<CardContent> | ||
<SignInForm /> | ||
</CardContent> | ||
</Card> | ||
</div> | ||
); | ||
} |
Oops, something went wrong.
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.
Same comment as
SignUpForm
- can this beerror.message
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.
Answered it here: #13 (comment)