Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions app/api/bounties/[id]/volunteers/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { auth } from '../../../../../auth'
import {
joinBounty,
withdrawFromBounty,
type AttendanceResult,
} from '../../../../../lib/bounties/attendance'

type RouteContext = { params: Promise<{ id: string }> }

export async function POST(_request: Request, { params }: RouteContext) {
const session = await auth()
const volunteerId = session?.user?.id
if (!volunteerId) {
return errorResponse(
401,
'UNAUTHENTICATED',
'Sign in to join this opportunity.',
)
}

const { id } = await params
return resultResponse(joinBounty(id, volunteerId), 201)
}

export async function DELETE(_request: Request, { params }: RouteContext) {
const session = await auth()
const volunteerId = session?.user?.id
if (!volunteerId) {
return errorResponse(401, 'UNAUTHENTICATED', 'Sign in to withdraw.')
}

const { id } = await params
return resultResponse(withdrawFromBounty(id, volunteerId), 200)
}

async function resultResponse(
resultPromise: Promise<AttendanceResult>,
successStatus: number,
): Promise<Response> {
let result: AttendanceResult
try {
result = await resultPromise
} catch {
return errorResponse(
500,
'INTERNAL_ERROR',
'We could not update your sign-up. Please try again.',
)
}

if (!result.ok) {
const status = result.code === 'BOUNTY_NOT_FOUND' ? 404 : 409
return errorResponse(status, result.code, result.message)
}

return Response.json({ data: { success: true } }, { status: successStatus })
}

function errorResponse(
status: number,
code: string,
message: string,
): Response {
return Response.json({ error: { code, message } }, { status })
}
3 changes: 2 additions & 1 deletion app/login/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useActionState, useState } from 'react'
import { initialLoginFormState } from '../../lib/auth/form-state'
import { loginAction } from './actions'

export function LoginForm() {
export function LoginForm({ returnTo = '/' }: { returnTo?: string }) {
const [state, formAction, isPending] = useActionState(
loginAction,
initialLoginFormState,
Expand All @@ -14,6 +14,7 @@ export function LoginForm() {

return (
<form action={formAction} className="account-form">
<input name="returnTo" type="hidden" value={returnTo} />
{state.error && (
<p className="form-error" role="alert">
{state.error}
Expand Down
4 changes: 3 additions & 1 deletion app/login/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ import {
initialLoginFormState,
type LoginFormState,
} from '../../lib/auth/form-state'
import { getSafePostReturnTo } from '../../lib/auth/return-to'
import { validateLogin } from '../../lib/auth/validation'

export async function loginAction(
_previousState: LoginFormState,
formData: FormData,
): Promise<LoginFormState> {
const values = { email: String(formData.get('email') ?? '').trim() }
const returnTo = getSafePostReturnTo(formData.get('returnTo'))
let credentials: { email: string; password: string }

try {
Expand All @@ -29,7 +31,7 @@ export async function loginAction(
}

try {
await signIn('credentials', { ...credentials, redirectTo: '/' })
await signIn('credentials', { ...credentials, redirectTo: returnTo })
} catch (error) {
if (error instanceof AuthError) {
return {
Expand Down
25 changes: 22 additions & 3 deletions app/login/page.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
import Link from 'next/link'

import { getSafePostReturnTo } from '../../lib/auth/return-to'
import { LoginForm } from './LoginForm'

export default function LoginPage() {
type LoginPageProps = {
searchParams?: Promise<{ returnTo?: string }>
}

export default async function LoginPage({
searchParams = Promise.resolve({}),
}: LoginPageProps) {
const { returnTo: requestedReturnTo } = await searchParams
const returnTo = getSafePostReturnTo(requestedReturnTo)

return (
<main className="account-page">
<section className="account-panel" aria-labelledby="login-title">
<p className="eyebrow">Welcome back!</p>
<h2 id="login-title">Log In</h2>

<LoginForm />
<LoginForm returnTo={returnTo} />

<p className="account-panel__switch">
New to SideCause? <Link href="/register">Create an account</Link>
New to SideCause?{' '}
<Link
href={
returnTo === '/'
? '/register'
: `/register?returnTo=${encodeURIComponent(returnTo)}`
}
>
Create an account
</Link>
</p>
</section>
</main>
Expand Down
89 changes: 89 additions & 0 deletions app/posts/[id]/VolunteerAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useState } from 'react'

import styles from './detail.module.css'

type VolunteerActionProps = {
bountyId: string
status: 'OPEN' | 'FULL' | 'FINISHED'
attendance: 'JOINED' | 'WITHDRAWN' | null
signedIn: boolean
}

export function VolunteerAction({
bountyId,
status,
attendance,
signedIn,
}: VolunteerActionProps) {
const router = useRouter()
const [pending, setPending] = useState(false)
const [error, setError] = useState<string | null>(null)
const returnTo = `/posts/${bountyId}`
const accountHref = `/login?returnTo=${encodeURIComponent(returnTo)}`

let label = 'Sign up'
let disabled = false
if (attendance === 'WITHDRAWN') {
label = 'Unenrolled'
disabled = true
} else if (status === 'FINISHED') {
label = attendance === 'JOINED' ? 'Unenroll' : 'Sign up'
disabled = true
} else if (status === 'FULL' && attendance !== 'JOINED') {
disabled = true
} else if (attendance === 'JOINED') {
label = 'Unenroll'
}

if (!signedIn && !disabled) {
return (
<Link className={styles.signupButton} href={accountHref}>
Sign up
</Link>
)
}

async function updateAttendance() {
setPending(true)
setError(null)
try {
const response = await fetch(`/api/bounties/${bountyId}/volunteers`, {
method: attendance === 'JOINED' ? 'DELETE' : 'POST',
})
const result = (await response.json()) as {
error?: { message?: string }
}
if (!response.ok) {
setError(result.error?.message ?? 'Your sign-up could not be updated.')
return
}
router.refresh()
} catch {
setError('Your sign-up could not be updated. Please try again.')
} finally {
setPending(false)
}
}

return (
<>
<button
className={styles.signupButton}
disabled={disabled || pending}
onClick={updateAttendance}
type="button"
>
{pending ? 'Updating…' : label}
</button>
{error && (
<p className={styles.signupError} role="alert">
{error}
</p>
)}
</>
)
}
15 changes: 15 additions & 0 deletions app/posts/[id]/detail.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -213,16 +213,20 @@
}

.signupButton {
display: inline-flex;
width: 100%;
min-height: 2.75rem;
margin-top: 1rem;
align-items: center;
justify-content: center;
border: 1px solid var(--ink);
border-radius: 0;
color: var(--ink);
background: var(--accent-soft);
font: inherit;
font-weight: 700;
cursor: pointer;
text-decoration: none;
}

.signupButton:hover {
Expand All @@ -236,6 +240,17 @@
opacity: 0.7;
}

.signupButton:focus-visible {
outline: 3px solid #236e69;
outline-offset: 3px;
}

.signupError {
margin-top: 0.75rem;
color: #9b2f24;
font-weight: 700;
}

@media (min-width: 48rem) {
.page {
padding: 3rem;
Expand Down
41 changes: 7 additions & 34 deletions app/posts/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { notFound } from 'next/navigation'

import { auth } from '../../../auth'
import { getAccessiblePostDetail, type PostDifficulty } from './detail-data'
import { VolunteerAction } from './VolunteerAction'
import styles from './detail.module.css'

type PostDetailPageProps = {
Expand All @@ -16,7 +17,6 @@ export default async function PostDetailPage({ params }: PostDetailPageProps) {
const post = await getAccessiblePostDetail(id, session?.user?.id ?? null)

if (!post) notFound()
const action = getPostAction(post.status, post.viewerAttendance)
const statusClassName = {
OPEN: styles.statusOpen,
FULL: styles.statusFull,
Expand Down Expand Up @@ -114,13 +114,12 @@ export default async function PostDetailPage({ params }: PostDetailPageProps) {
</div>
</dl>

<button
className={styles.signupButton}
disabled={action.disabled}
type="button"
>
{action.label}
</button>
<VolunteerAction
attendance={post.viewerAttendance}
bountyId={post.id}
signedIn={Boolean(session?.user?.id)}
status={post.status}
/>
</aside>
</div>
</article>
Expand Down Expand Up @@ -193,32 +192,6 @@ function RequirementList({
)
}

function getPostAction(
status: 'OPEN' | 'FULL' | 'FINISHED',
attendance: 'JOINED' | 'WITHDRAWN' | null,
): { label: string; disabled: boolean } {
if (attendance === 'WITHDRAWN') {
return { label: 'Unenrolled', disabled: true }
}

if (status === 'FINISHED') {
return {
label: attendance === 'JOINED' ? 'Unenroll' : 'Sign up',
disabled: true,
}
}

if (status === 'FULL' && attendance !== 'JOINED') {
return { label: 'Sign up', disabled: true }
}

if (attendance === 'JOINED') {
return { label: 'Unenroll', disabled: false }
}

return { label: 'Sign up', disabled: false }
}

function formatStatus(status: 'OPEN' | 'FULL' | 'FINISHED'): string {
return status.charAt(0) + status.slice(1).toLowerCase()
}
Expand Down
3 changes: 2 additions & 1 deletion app/register/RegisterForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useActionState, useState } from 'react'
import { initialRegisterFormState } from '../../lib/auth/form-state'
import { registerAction } from './actions'

export function RegisterForm() {
export function RegisterForm({ returnTo = '/' }: { returnTo?: string }) {
const [state, formAction, isPending] = useActionState(
registerAction,
initialRegisterFormState,
Expand All @@ -17,6 +17,7 @@ export function RegisterForm() {

return (
<form action={formAction} className="account-form">
<input name="returnTo" type="hidden" value={returnTo} />
{state.error && (
<p className="form-error" role="alert">
{state.error}
Expand Down
4 changes: 3 additions & 1 deletion app/register/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
initialRegisterFormState,
type RegisterFormState,
} from '../../lib/auth/form-state'
import { getSafePostReturnTo } from '../../lib/auth/return-to'
import { assertWithinAuthRateLimit } from '../../lib/auth/rate-limit'
import { hashPassword } from '../../lib/auth/password'
import { validateRegistration } from '../../lib/auth/validation'
Expand All @@ -21,6 +22,7 @@ export async function registerAction(
displayName: String(formData.get('displayName') ?? '').trim(),
email: String(formData.get('email') ?? '').trim(),
}
const returnTo = getSafePostReturnTo(formData.get('returnTo'))
let input: { displayName: string; email: string; password: string }

try {
Expand Down Expand Up @@ -68,7 +70,7 @@ export async function registerAction(
}

try {
await signIn('credentials', { email, password, redirectTo: '/' })
await signIn('credentials', { email, password, redirectTo: returnTo })
} catch (error) {
if (error instanceof AuthError) {
return {
Expand Down
Loading
Loading