Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

feat: adds beta token for early access (#820)

bautistaaac11864bd0f1f
diff --git a/apps/web/package.json b/apps/web/package.json
index 599bba31..c0382e95 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -11,7 +11,7 @@
"format:fix": "prettier . --write --cache --cache-location=\"node_modules/.cache/prettiercache\" --log-level=warn",
"lint": "eslint . --cache --cache-location \"node_modules/.cache/.eslintcache\" --max-warnings 0",
"lint:fix": "eslint . --fix --cache --cache-location \"node_modules/.cache/.eslintcache\" --max-warnings 0",
- "start": "next start",
+ "start": "dotenv -e ../../.env next start",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"typecheck": "tsc --noEmit"
diff --git a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx
index 779f37ca..391a164b 100644
--- a/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx
+++ b/apps/web/src/app/[locale]/(playgrounds)/challenge-playground/page.tsx
@@ -1,6 +1,15 @@
+import { getServerAuthSession } from '@repo/auth/server';
+import { notFound } from 'next/navigation';
+import { isAdminOrModerator } from '~/utils/auth-guards';
import { Description } from './description';
export default async function ChallengePlaygroundPage() {
+ const session = await getServerAuthSession();
+
+ if (!isAdminOrModerator(session)) {
+ return notFound();
+ }
+
return (
<div className="relative h-full">
<Description />
diff --git a/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts b/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts
index ae42b231..33dea3c5 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts
+++ b/apps/web/src/app/[locale]/challenge/[id]/getChallengeRouteData.ts
@@ -1,4 +1,3 @@
-'use server';
import { type Session } from '@repo/auth/server';
import { prisma } from '@repo/db';
import { cache } from 'react';
diff --git a/apps/web/src/app/[locale]/challenge/[id]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/page.tsx
index 7d29c498..6f19c587 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/page.tsx
@@ -1,9 +1,13 @@
-import { getServerAuthSession } from '@repo/auth/server';
+import { getServerAuthSession, type Session } from '@repo/auth/server';
import { Description } from '../_components/description';
import { Comments } from '../_components/comments';
import { getChallengeRouteData } from './getChallengeRouteData';
import { buildMetaForChallenge } from '~/app/metadata';
import { getRelativeTime } from '~/utils/relativeTime';
+import { getAllFlags } from '~/utils/feature-flags';
+import { redirect } from 'next/navigation';
+import { prisma } from '@repo/db';
+import { isBetaUser } from '~/utils/server/is-beta-user';
interface Props {
params: {
@@ -25,7 +29,14 @@ export async function generateMetadata({ params: { id } }: Props) {
}
export default async function Challenges({ params: { id: challengeId } }: Props) {
+ // early acces you must be authorized
const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
+
const challenge = await getChallengeRouteData(challengeId, session);
return (
@@ -35,3 +46,7 @@ export default async function Challenges({ params: { id: challengeId } }: Props)
</div>
);
}
+
+export function isAuthor(session: Session | null, userId?: string | null) {
+ return userId && session?.user?.id && userId === session?.user?.id;
+}
diff --git a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
index 8ec3f1cb..44359587 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/solutions/[solutionId]/page.tsx
@@ -3,6 +3,8 @@ import { SolutionDetails } from '../_components/solution-detail';
import { getServerAuthSession } from '@repo/auth/server';
import { Comments } from '~/app/[locale]/challenge/_components/comments';
import { getSolutionIdRouteData } from './getSolutionIdRouteData';
+import { isBetaUser } from '~/utils/server/is-beta-user';
+import { redirect } from 'next/navigation';
interface Props {
params: {
@@ -14,6 +16,12 @@ interface Props {
export type ChallengeSolution = NonNullable<Awaited<ReturnType<typeof getSolutionIdRouteData>>>;
export default async function SolutionPage({ params: { solutionId, id: challengeId } }: Props) {
const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
+
const solution = await getSolutionIdRouteData(challengeId, solutionId, session);
return (
diff --git a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
index f818256b..1dcd1394 100644
--- a/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
+++ b/apps/web/src/app/[locale]/challenge/[id]/submissions/[[...catchAll]]/page.tsx
@@ -1,9 +1,10 @@
import { cache } from 'react';
import { prisma } from '@repo/db';
import { getServerAuthSession } from '@repo/auth/server';
-import { notFound } from 'next/navigation';
+import { notFound, redirect } from 'next/navigation';
import { Submissions } from './_components';
import { withUnstableCache } from '~/utils/withUnstableCache';
+import { isBetaUser } from '~/utils/server/is-beta-user';
interface Props {
params: {
@@ -18,6 +19,12 @@ export const metadata = {
export default async function SubmissionPage({ params: { id } }: Props) {
const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
+
const submissions = await withUnstableCache({
fn: getChallengeSubmissions,
args: [session?.user.id ?? '', id],
@@ -33,7 +40,7 @@ export default async function SubmissionPage({ params: { id } }: Props) {
}
export type ChallengeSubmissions = NonNullable<Awaited<ReturnType<typeof getChallengeSubmissions>>>;
-export const getChallengeSubmissions = cache((userId: string, challengeId: string) => {
+const getChallengeSubmissions = cache((userId: string, challengeId: string) => {
return prisma.submission.findMany({
where: { challengeId: Number(challengeId), userId },
orderBy: [
diff --git a/apps/web/src/app/[locale]/claim/_actions.ts b/apps/web/src/app/[locale]/claim/_actions.ts
new file mode 100644
index 00000000..765500a3
--- /dev/null
+++ b/apps/web/src/app/[locale]/claim/_actions.ts
@@ -0,0 +1,31 @@
+'use server';
+
+import { getServerAuthSession } from '@repo/auth/server';
+import { prisma } from '@repo/db';
+import { redirect } from 'next/navigation';
+import { claimFormSchema } from './_schema';
+import { type FormSchema } from './claim-form';
+
+export async function validateToken(claimFormData: FormSchema) {
+ claimFormSchema.parse(claimFormData);
+
+ const session = await getServerAuthSession();
+
+ if (!session) {
+ throw new Error('Not authenticated');
+ }
+
+ await prisma.betaTokens.update({
+ where: {
+ token: claimFormData.code,
+ AND: {
+ userId: null,
+ },
+ },
+ data: {
+ user: { connect: { id: session?.user.id } },
+ },
+ });
+
+ redirect('/explore');
+}
diff --git a/apps/web/src/app/[locale]/claim/_schema.ts b/apps/web/src/app/[locale]/claim/_schema.ts
new file mode 100644
index 00000000..8b60313a
--- /dev/null
+++ b/apps/web/src/app/[locale]/claim/_schema.ts
@@ -0,0 +1,5 @@
+import { z } from 'zod';
+
+export const claimFormSchema = z.object({
+ code: z.string().min(10).max(10),
+});
diff --git a/apps/web/src/app/[locale]/claim/claim-form.tsx b/apps/web/src/app/[locale]/claim/claim-form.tsx
new file mode 100644
index 00000000..2086b6df
--- /dev/null
+++ b/apps/web/src/app/[locale]/claim/claim-form.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import { Button } from '@repo/ui/components/button';
+import { Form, FormControl, FormField, FormItem, FormMessage } from '@repo/ui/components/form';
+import { Input } from '@repo/ui/components/input';
+import { toast } from '@repo/ui/components/use-toast';
+import { useForm } from 'react-hook-form';
+import { type z } from 'zod';
+import { validateToken } from './_actions';
+import { claimFormSchema } from './_schema';
+
+export type FormSchema = z.infer<typeof claimFormSchema>;
+export function ClaimForm() {
+ const form = useForm<FormSchema>({
+ resolver: zodResolver(claimFormSchema),
+ defaultValues: {
+ code: '',
+ },
+ });
+
+ async function onSubmit(data: FormSchema) {
+ try {
+ await validateToken(data);
+ toast({
+ title: 'Token accepted!',
+ });
+ } catch (e) {
+ toast({
+ variant: 'destructive',
+ title: 'Invalid token',
+ });
+ }
+ }
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="mx-auto flex gap-5">
+ <FormField
+ control={form.control}
+ name="code"
+ render={({ field }) => (
+ <FormItem className="w-64">
+ <FormControl>
+ <Input
+ maxLength={10}
+ className="rounded-xl bg-neutral-200 dark:bg-neutral-800"
+ placeholder="Enter Early Access token"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button type="submit">Submit</Button>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/app/[locale]/claim/page.tsx b/apps/web/src/app/[locale]/claim/page.tsx
new file mode 100644
index 00000000..d2695493
--- /dev/null
+++ b/apps/web/src/app/[locale]/claim/page.tsx
@@ -0,0 +1,22 @@
+import { getServerAuthSession } from '@repo/auth/server';
+import { LoginButton } from '../login/_components/LoginButton';
+import { ClaimForm } from './claim-form';
+
+export default async function Claim() {
+ const session = await getServerAuthSession();
+ const header = session ? 'In early access?' : 'Login to claim your token';
+ const subheader = session ? 'Enter the token that was emailed to you' : '';
+ return (
+ <div className="container flex h-full flex-col items-center justify-center">
+ <div className="mx-auto flex w-full flex-col justify-center space-y-6 text-center sm:w-[550px]">
+ <div className="flex flex-col space-y-2 text-center">
+ <h1 className="text-4xl font-bold tracking-tight text-neutral-900 dark:text-white">
+ {header}
+ </h1>
+ <p>{subheader}</p>
+ </div>
+ {session ? <ClaimForm /> : <LoginButton redirectTo="/claim" />}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/explore/_components/index.tsx b/apps/web/src/app/[locale]/explore/_components/index.tsx
index 881bd109..104cd515 100644
--- a/apps/web/src/app/[locale]/explore/_components/index.tsx
+++ b/apps/web/src/app/[locale]/explore/_components/index.tsx
@@ -1,13 +1,23 @@
+import { getServerAuthSession } from '@repo/auth/server';
import { Suspense } from 'react';
+import { Footsies } from '~/components/footsies';
import { ExploreSection } from './explore-section';
import { ExploreSectionSkeleton } from './explore-section-skeleton';
import { getChallengesByTagOrDifficulty } from './explore.action';
-import { Footsies } from '~/components/footsies';
+import { isBetaUser } from '~/utils/server/is-beta-user';
+import { redirect } from 'next/navigation';
// CI fails without this
export const dynamic = 'force-dynamic';
export async function Explore() {
+ const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
+
return (
<div className="flex flex-col gap-8 py-8 md:gap-10 md:py-10">
<div className="container">
diff --git a/apps/web/src/app/[locale]/login/_components/LoginButton.tsx b/apps/web/src/app/[locale]/login/_components/LoginButton.tsx
new file mode 100644
index 00000000..672caa19
--- /dev/null
+++ b/apps/web/src/app/[locale]/login/_components/LoginButton.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { signIn } from '@repo/auth/react';
+import { Button } from '@repo/ui/components/button';
+import { useState } from 'react';
+
+type State = 'error' | 'idle' | 'pending' | 'success';
+
+export function LoginButton({ redirectTo }: { redirectTo: string }) {
+ const [state, setState] = useState<State>('idle');
+
+ const handleSignIn = async () => {
+ try {
+ setState('pending');
+ await signIn('github', { callbackUrl: redirectTo });
+ } catch (error) {
+ setState('error');
+ }
+ };
+
+ return (
+ <Button disabled={state === 'pending'} variant="outline" onClick={handleSignIn}>
+ Github
+ </Button>
+ );
+}
diff --git a/apps/web/src/app/[locale]/login/page.tsx b/apps/web/src/app/[locale]/login/page.tsx
new file mode 100644
index 00000000..53e1d3b2
--- /dev/null
+++ b/apps/web/src/app/[locale]/login/page.tsx
@@ -0,0 +1,36 @@
+import Link from 'next/link';
+import { LoginButton } from './_components/LoginButton';
+
+// @TODO: add a redirect param to send users back to previous page
+export default async function Index() {
+ return (
+ <>
+ <div className="container flex h-full flex-col items-center justify-center">
+ <div className="lg:p-8">
+ <div className="mx-auto flex w-full flex-col justify-center space-y-6 text-center sm:w-[450px]">
+ <div className="flex flex-col space-y-2 text-center">
+ <h1 className="text-4xl font-bold tracking-tight text-neutral-900 dark:text-white">
+ Welcome to Early Access!
+ </h1>
+ <p className="text-muted-foreground text-sm">
+ Start your typescript journey by logging in below.
+ </p>
+ </div>
+ <LoginButton redirectTo="/explore" />
+ <p className="text-muted-foreground mx-auto px-8 text-sm sm:w-[350px]">
+ By clicking continue, you agree to our{' '}
+ <Link href="/tos" className="hover:text-primary underline underline-offset-4">
+ Terms of Service
+ </Link>{' '}
+ and{' '}
+ <Link href="/privacy" className="hover:text-primary underline underline-offset-4">
+ Privacy Policy
+ </Link>
+ .
+ </p>
+ </div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
index 9fcd9fb2..431acb49 100644
--- a/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
+++ b/apps/web/src/app/[locale]/tracks/[slug]/page.tsx
@@ -1,3 +1,6 @@
+import { getServerAuthSession } from '@repo/auth/server';
+import { redirect } from 'next/navigation';
+import { isBetaUser } from '~/utils/server/is-beta-user';
import { TrackDetail } from '../_components/track-details';
import { getTrackDetails } from '../_components/track.action';
@@ -10,7 +13,14 @@ interface Props {
}
// todo: write a suspense skeleton...
-export default function Page({ params }: Props) {
+export default async function Page({ params }: Props) {
+ const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
+
return <TrackDetail slug={params.slug} />;
}
diff --git a/apps/web/src/app/[locale]/tracks/_components/index.tsx b/apps/web/src/app/[locale]/tracks/_components/index.tsx
index fd9da60c..53f6eb3c 100644
--- a/apps/web/src/app/[locale]/tracks/_components/index.tsx
+++ b/apps/web/src/app/[locale]/tracks/_components/index.tsx
@@ -1,9 +1,17 @@
import { getServerAuthSession } from '@repo/auth/server';
+import { redirect } from 'next/navigation';
+import { isBetaUser } from '~/utils/server/is-beta-user';
import { EnrolledTrackSection } from './track-enrolled-section';
import { TrackGrid } from './track-grid';
export async function Tracks() {
+ // early acces you must be authorized
const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
+
+ if (!isBeta) {
+ return redirect('/claim');
+ }
return (
<div className="flex flex-col gap-5 py-8 md:gap-10 md:py-10">
diff --git a/apps/web/src/app/[locale]/wizard/page.tsx b/apps/web/src/app/[locale]/wizard/page.tsx
index c3f0069c..6d9370f4 100644
--- a/apps/web/src/app/[locale]/wizard/page.tsx
+++ b/apps/web/src/app/[locale]/wizard/page.tsx
@@ -1,8 +1,9 @@
import { getServerAuthSession } from '@repo/auth/server';
-import { TypographyH2 } from '@repo/ui/components/typography/h2';
import type { Metadata } from 'next';
-import { Wizard } from './_components';
+import { redirect } from 'next/navigation';
import { buildMetaForDefault } from '~/app/metadata';
+import { isBetaUser } from '~/utils/server/is-beta-user';
+import { Wizard } from './_components';
export async function generateMetadata(): Promise<Metadata> {
return buildMetaForDefault({
@@ -13,13 +14,10 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function Page() {
const session = await getServerAuthSession();
+ const isBeta = await isBetaUser(session);
- if (!session?.user) {
- return (
- <div className="container flex h-full flex-col items-center justify-center">
- <TypographyH2>You must be logged in to create a challenge.</TypographyH2>
- </div>
- );
+ if (!isBeta) {
+ return redirect('/claim');
}
return <Wizard />;
diff --git a/apps/web/src/app/feature-flag-provider.tsx b/apps/web/src/app/feature-flag-provider.tsx
index 02f82aef..b91e715a 100644
--- a/apps/web/src/app/feature-flag-provider.tsx
+++ b/apps/web/src/app/feature-flag-provider.tsx
@@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import { createContext, type ReactNode } from 'react';
+import { mockFlags } from '~/utils/feature-flags';
export const FeatureFlagContext = createContext<Record<string, boolean>>({});
@@ -7,12 +8,6 @@ interface Props {
children: ReactNode;
}
-const mockFlags = {
- loginButton: true,
- exploreButton: true,
- tracksButton: true,
-};
-
const isProd = process.env.NODE_ENV === 'production';
export function FeatureFlagProvider({ children }: Props) {
const { data: featureFlags } = useQuery(['featureFlags'], () => getFeatureFlags());
diff --git a/apps/web/src/components/carousel.tsx b/apps/web/src/components/carousel.tsx
index a28fc298..20d8e633 100644
--- a/apps/web/src/components/carousel.tsx
+++ b/apps/web/src/components/carousel.tsx
@@ -1,4 +1,5 @@
'use client';
+
import { ChevronLeft, ChevronRight } from '@repo/ui/icons';
import clsx from 'clsx';
import { useEffect, useRef, useState, type ReactNode, useCallback, useId } from 'react';
diff --git a/apps/web/src/components/navigation.tsx b/apps/web/src/components/navigation.tsx
index 46ffed5a..a02e2ff1 100644
--- a/apps/web/src/components/navigation.tsx
+++ b/apps/web/src/components/navigation.tsx
@@ -1,6 +1,6 @@
'use client';
-import { signIn, signOut, useSession } from '@repo/auth/react';
+import { signOut, useSession } from '@repo/auth/react';
import { Button } from '@repo/ui/components/button';
import {
DropdownMenu,
@@ -73,7 +73,7 @@ export function Navigation() {
hero
</span>
</Link>
- {featureFlags?.exploreButton ? (
+ {featureFlags?.enableExplore ? (
<Link href="/explore" className="ml-4">
<div
className={clsx('hover:text-foreground text-foreground/80 transition-colors', {
@@ -84,7 +84,7 @@ export function Navigation() {
</div>
</Link>
) : null}
- {featureFlags?.tracksButton ? (
+ {featureFlags?.enableTracks ? (
<Link href="/tracks" className="ml-4">
<div
className={clsx('hover:text-foreground text-foreground/80 transition-colors', {
@@ -99,7 +99,7 @@ export function Navigation() {
<div className="flex">
<div className="flex items-center justify-end gap-2">
<ThemeButton />
- {featureFlags?.loginButton ? <LoginButton /> : null}
+ {featureFlags?.enableLogin ? <LoginButton /> : null}
</div>
</div>
</div>
@@ -137,23 +137,11 @@ function ThemeButton() {
}
function LoginButton() {
- const [loading, setLoading] = useState(false);
const { data: session, status } = useSession();
const router = useRouter();
const isAdminOrMod = isAdminOrModerator(session);
- // NOTE: 1. loading == true -> 2. signIn() -> 3. session status == 'loading' (loading == false)
- const handleSignIn = async () => {
- try {
- setLoading(true);
- // page reloads after sign in, so no need to setLoading(false), othersiwe ugly visual glitch
- await signIn('github', { redirect: false });
- } catch (error) {
- // only set loading to false if there was an error and page didn't reload after sign in
- setLoading(false);
- }
- };
const handleSignOut = async () => {
await signOut({ redirect: false });
router.refresh();
@@ -212,12 +200,11 @@ function LoginButton() {
</DropdownMenuContent>
</DropdownMenu>
) : (
- <Button
+ <Link
className="focus:bg-accent w-20 rounded-lg bg-transparent p-2 text-black duration-300 hover:bg-gray-200 focus:outline-none dark:text-white hover:dark:bg-gray-800"
- disabled={loading || status === 'loading'}
- onClick={handleSignIn}
+ href="/login"
>
- {loading || status === 'loading' ? (
+ {status === 'loading' ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<div className="flex items-center space-x-2">
@@ -225,6 +212,6 @@ function LoginButton() {
<span className="dark:text-white">Login</span>
</div>
)}
- </Button>
+ </Link>
);
}
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index 9bef28bc..0583bfc2 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -1,5 +1,5 @@
-import { NextResponse, type NextRequest } from 'next/server';
import { createI18nMiddleware } from 'next-international/middleware';
+import { type NextRequest } from 'next/server';
const I18nMiddleware = createI18nMiddleware({
locales: ['en'],
@@ -15,20 +15,6 @@ export function middleware(req: NextRequest) {
return I18nMiddleware(req);
}
- const path = req.nextUrl.pathname;
-
- // if path is /explore or /challenge/* and redirect to /waitlist
- if (
- path === '/explore' ||
- path.startsWith('/challenge') ||
- path.startsWith('/challenge-playground') ||
- path.startsWith('/challenge/') ||
- path.startsWith('/tracks') ||
- path.startsWith('/tracks/')
- ) {
- return NextResponse.redirect(new URL('/waitlist', req.url));
- }
-
return I18nMiddleware(req);
}
diff --git a/apps/web/src/utils/feature-flags.ts b/apps/web/src/utils/feature-flags.ts
index 481bca28..29c48663 100644
--- a/apps/web/src/utils/feature-flags.ts
+++ b/apps/web/src/utils/feature-flags.ts
@@ -1,34 +1,15 @@
-import { createClient, type EdgeConfigItems } from '@vercel/edge-config';
+import { createClient } from '@vercel/edge-config';
-const mockFlags = {
- loginButton: true,
- exploreButton: true,
- tracksButton: true,
+export const mockFlags = {
+ enableLogin: true,
+ enableExplore: true,
+ enableTracks: true,
+ enableEarlyAccess: true,
};
-/**
- * This will try to eval a feature flag on the prod app
- *
- * @example
- * ```
- * const isFeatureEnabled = await evaluateFlag('my-feature-flag');
- * ```
- */
-export async function evaluateFlag(key: string): Promise<boolean> {
- if (!process.env.EDGE_CONFIG) {
- return mockFlags[key as keyof typeof mockFlags];
- }
- const edgeConfig = createClient(process.env.EDGE_CONFIG);
-
- const featureFlag = await edgeConfig.get(key);
-
- const rawValue = featureFlag?.valueOf();
- return rawValue == true;
-}
-
-export async function getAllFlags(): Promise<EdgeConfigItems> {
+export async function getAllFlags() {
const allFeatureFlag = process.env.EDGE_CONFIG
- ? await createClient(process.env.EDGE_CONFIG).getAll()
+ ? await createClient(process.env.EDGE_CONFIG).getAll<typeof mockFlags>()
: mockFlags;
return allFeatureFlag;
}
diff --git a/apps/web/src/utils/server/is-beta-user.ts b/apps/web/src/utils/server/is-beta-user.ts
new file mode 100644
index 00000000..8d550721
--- /dev/null
+++ b/apps/web/src/utils/server/is-beta-user.ts
@@ -0,0 +1,19 @@
+import type { Session } from '@repo/auth/server';
+import { prisma } from '@repo/db';
+import { getAllFlags } from '../feature-flags';
+
+export async function isBetaUser(session: Session | null) {
+ const flags = await getAllFlags();
+
+ const isBetaUser = await prisma.betaTokens.findFirst({
+ where: {
+ userId: session?.user.id ?? '',
+ },
+ });
+
+ if ((!session || !isBetaUser) && flags.enableEarlyAccess) {
+ return false;
+ }
+
+ return true;
+}
diff --git a/packages/auth/src/server.ts b/packages/auth/src/server.ts
index 86e9e832..56a89acb 100644
--- a/packages/auth/src/server.ts
+++ b/packages/auth/src/server.ts
@@ -37,6 +37,9 @@ if (!process.env.GITHUB_SECRET) {
const useSecureCookies = Boolean(process.env.VERCEL_URL);
export const authOptions: NextAuthOptions = {
+ pages: {
+ signIn: '/login',
+ },
cookies: {
sessionToken: {
name: `${useSecureCookies ? '__Secure-' : ''}next-auth.session-token`,
@@ -50,11 +53,6 @@ export const authOptions: NextAuthOptions = {
},
},
callbacks: {
- redirect: ({ url, baseUrl }) => {
- if (url.startsWith('/')) return `${baseUrl}${url}`;
- else if (new URL(url).origin === baseUrl) return url;
- return baseUrl;
- },
session: async ({ session, user }) => {
// 1. State
let userRoles: RoleTypes[] = [];
diff --git a/packages/db/mocks/user.mock.ts b/packages/db/mocks/user.mock.ts
index 50b8668b..47023d20 100644
--- a/packages/db/mocks/user.mock.ts
+++ b/packages/db/mocks/user.mock.ts
@@ -1,5 +1,5 @@
import { faker } from '@faker-js/faker';
-import { type Prisma, UserStatus } from '@prisma/client';
+import { type Prisma } from '@prisma/client';
/**
*
@@ -15,7 +15,7 @@ export default function UserMock(): Prisma.UserCreateManyInput {
email,
emailVerified: faker.date.between({ from: createdAt, to: new Date() }),
name: faker.person.fullName(),
- status: faker.helpers.enumValue(UserStatus),
+ status: 'ACTIVE',
createdAt,
};
}
diff --git a/packages/db/schema.prisma b/packages/db/schema.prisma
index 71adbcfe..d416cd01 100644
--- a/packages/db/schema.prisma
+++ b/packages/db/schema.prisma
@@ -130,6 +130,7 @@ model User {
imageUpload ImageUpload[]
tracks Track[]
+ BetaTokens BetaTokens[]
}
model VerificationToken {
@@ -400,3 +401,12 @@ model Track {
trackChallenges TrackChallenge[]
enrolledUsers User[]
}
+
+model BetaTokens {
+ id Int @id @default(autoincrement())
+ token String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+
+ @@index([userId])
+}
diff --git a/packages/db/temp/export-tokens.ts b/packages/db/temp/export-tokens.ts
new file mode 100644
index 00000000..679c6aa0
--- /dev/null
+++ b/packages/db/temp/export-tokens.ts
@@ -0,0 +1,24 @@
+// @ts-nocheck
+// this file is temporary
+import { createObjectCsvWriter } from 'csv-writer';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { prisma } from '.';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+const csvPath = path.join(__dirname, '../.tmp/dump.csv');
+
+const csvWriter = createObjectCsvWriter({
+ path: csvPath,
+ header: [{ id: 'token', title: 'token' }],
+});
+
+const tokens = await prisma.betaTokens.findMany({
+ select: {
+ token: true,
+ },
+});
+
+await csvWriter.writeRecords(tokens);
diff --git a/packages/db/temp/populate-tokens.ts b/packages/db/temp/populate-tokens.ts
new file mode 100644
index 00000000..3af96113
--- /dev/null
+++ b/packages/db/temp/populate-tokens.ts
@@ -0,0 +1,26 @@
+import { prisma } from '../src';
+
+const TOKEN_LIMIT = 3069;
+
+function generateRandomStr() {
+ const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ let result = '';
+ for (let i = 0; i < 10; i++) {
+ result += chars[Math.floor(Math.random() * chars.length)];
+ }
+ return result;
+}
+
+async function populateTokens() {
+ await prisma.betaTokens.deleteMany();
+ await prisma.betaTokens.createMany({
+ data: Array.from(new Array(TOKEN_LIMIT).keys()).map(() => {
+ return {
+ isClaimed: false,
+ token: generateRandomStr(),
+ };
+ }),
+ });
+}
+
+populateTokens();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 82a90363..87bc2e3e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8926,6 +8926,22 @@ packages:
camelcase-css: 2.0.1
postcss: 8.4.28
+ resolution: {integrity: sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==}
+ engines: {node: '>= 10'}
+ peerDependencies:
+ postcss: '>=8.0.9'
+ ts-node: '>=9.0.0'
+ peerDependenciesMeta:
+ postcss:
+ optional: true
+ ts-node:
+ optional: true
+ dependencies:
+ lilconfig: 2.1.0
+ yaml: 1.10.2
+ dev: true
+
resolution: {integrity: sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==}
engines: {node: '>= 10'}
@@ -8941,6 +8957,7 @@ packages:
lilconfig: 2.1.0
postcss: 8.4.21
yaml: 1.10.2
+ dev: false
resolution: {integrity: sha512-vEJIc8RdiBRu3oRAI0ymerOn+7rPuMvRXslTvZUKZonDHFIczxztIyJ1urxM1x9JXEikvpWWTUUqal5j/8QgvA==}
@@ -9002,6 +9019,7 @@ packages:
nanoid: 3.3.6
picocolors: 1.0.0
source-map-js: 1.0.2
+ dev: false
resolution: {integrity: sha512-jrXHFF8iTloAenySjM/ob3gSj7pCu0Ji49hnjqzsgSRa50hkWCKD0HQ+gMNJkW38jBI68MpAAg7ZWwHwX8NMMw==}
@@ -10497,7 +10515,7 @@ packages:
execa: 5.1.1
globby: 11.1.0
joycon: 3.1.1
- postcss-load-config: 3.1.4([email protected])
+ postcss-load-config: 3.1.4
resolve-from: 5.0.0
rollup: 2.79.1
source-map: 0.7.4