Merge pull request #6 from StevanFreeborn/stevanfreeborn/feat/add-auth-and-user-persistence

feat: add auth and persisting users
This commit is contained in:
Stevan Freeborn
2023-09-09 22:31:15 -05:00
committed by GitHub
23 changed files with 1843 additions and 9 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
{
"css.lint.unknownAtRules": "ignore"
"css.lint.unknownAtRules": "ignore",
"cSpell.words": ["conve", "nextjs", "signup", "svix"]
}
+39
View File
@@ -0,0 +1,39 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.2.1.
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
ApiFromModules,
FilterApi,
FunctionReference,
} from "convex/server";
import type * as http from "../http";
import type * as users from "../users";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
declare const fullApi: ApiFromModules<{
http: typeof http;
users: typeof users;
}>;
export declare const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
>;
export declare const internal: FilterApi<
typeof fullApi,
FunctionReference<any, "internal">
>;
+23
View File
@@ -0,0 +1,23 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.2.1.
* To regenerate, run `npx convex dev`.
* @module
*/
import { anyApi } from "convex/server";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api = anyApi;
export const internal = anyApi;
+56
View File
@@ -0,0 +1,56 @@
/* eslint-disable */
/**
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.2.1.
* To regenerate, run `npx convex dev`.
* @module
*/
import type { DataModelFromSchemaDefinition } from "convex/server";
import type { DocumentByName, TableNamesInDataModel } from "convex/server";
import type { GenericId } from "convex/values";
import schema from "../schema";
/**
* The names of all of your Convex tables.
*/
export type TableNames = TableNamesInDataModel<DataModel>;
/**
* The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(id)` in query and mutation functions.
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames> = GenericId<TableName>;
/**
* A type describing your Convex data model.
*
* This type includes information about what tables you have, the type of
* documents stored in those tables, and the indexes defined on them.
*
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
+143
View File
@@ -0,0 +1,143 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.2.1.
* To regenerate, run `npx convex dev`.
* @module
*/
import {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const query: QueryBuilder<DataModel, "public">;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const internalQuery: QueryBuilder<DataModel, "internal">;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const mutation: MutationBuilder<DataModel, "public">;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const internalMutation: MutationBuilder<DataModel, "internal">;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export declare const action: ActionBuilder<DataModel, "public">;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export declare const internalAction: ActionBuilder<DataModel, "internal">;
/**
* Define an HTTP action.
*
* This function will be used to respond to HTTP requests received by a Convex
* deployment if the requests matches the path and method where this action
* is routed. Be sure to route your action in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export declare const httpAction: HttpActionBuilder;
/**
* A set of services for use within Convex query functions.
*
* The query context is passed as the first argument to any Convex query
* function run on the server.
*
* This differs from the {@link MutationCtx} because all of the services are
* read-only.
*/
export type QueryCtx = GenericQueryCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*/
export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex action functions.
*
* The action context is passed as the first argument to any Convex action
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<DataModel>;
/**
* An interface to read from the database within Convex query functions.
*
* The two entry points are {@link DatabaseReader.get}, which fetches a single
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
* building a query.
*/
export type DatabaseReader = GenericDatabaseReader<DataModel>;
/**
* An interface to read from and write to the database within Convex mutation
* functions.
*
* Convex guarantees that all writes within a single mutation are
* executed atomically, so you never have to worry about partial writes leaving
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
* for the guarantees Convex provides your functions.
*/
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
+90
View File
@@ -0,0 +1,90 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* Generated by convex@1.2.1.
* To regenerate, run `npx convex dev`.
* @module
*/
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/server";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query = queryGeneric;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const internalQuery = internalQueryGeneric;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const mutation = mutationGeneric;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const internalMutation = internalMutationGeneric;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export const action = actionGeneric;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const internalAction = internalActionGeneric;
/**
* Define a Convex HTTP action.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
* as its second.
* @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
*/
export const httpAction = httpActionGeneric;
+10
View File
@@ -0,0 +1,10 @@
const config = {
providers: [
{
domain: process.env.CLERK_JWT_ISSUER_DOMAIN,
applicationID: 'convex',
},
],
};
export default config;
+86
View File
@@ -0,0 +1,86 @@
import type { WebhookEvent } from '@clerk/backend';
import { httpRouter } from 'convex/server';
import { Webhook } from 'svix';
import { internal } from './_generated/api';
import { httpAction } from './_generated/server';
async function validateRequest(
req: Request
): Promise<WebhookEvent | undefined> {
const payloadString = await req.text();
const svixHeaders = {
'svix-id': req.headers.get('svix-id')!,
'svix-timestamp': req.headers.get('svix-timestamp')!,
'svix-signature': req.headers.get('svix-signature')!,
};
const webhookSecret = process.env.CLERK_WEBHOOK_SECRET;
if (webhookSecret === undefined) {
throw Error('CLERK_WEBHOOK_SECRET is undefined');
}
const wh = new Webhook(webhookSecret);
let evt: Event | null = null;
try {
evt = wh.verify(payloadString, svixHeaders) as Event;
} catch (error) {
console.log(error);
return;
}
return evt as unknown as WebhookEvent;
}
const handleClerkWebhook = httpAction(async (ctx, request) => {
const event = await validateRequest(request);
if (!event) {
return new Response('Error occurred', {
status: 400,
});
}
switch (event.type) {
case 'user.created':
case 'user.updated': {
const existingUser = await ctx.runQuery(internal.users.getUser, {
subject: event.data.id,
});
if (existingUser && event.type === 'user.created') {
console.warn('Overwriting user', event.data.id, 'with', event.data);
}
console.log('creating/updating user', event.data.id);
await ctx.runMutation(internal.users.updateOrCreateUser, {
clerkUser: event.data,
});
break;
}
case 'user.deleted': {
const id = event.data.id!;
await ctx.runMutation(internal.users.deleteUser, { id });
break;
}
default: {
console.log('ignored Clerk webhook event', event.type);
}
}
return new Response(null, {
status: 200,
});
});
const http = httpRouter();
http.route({
path: '/clerk-users-webhook',
method: 'POST',
handler: handleClerkWebhook,
});
export default http;
+8
View File
@@ -0,0 +1,8 @@
import { defineSchema, defineTable } from 'convex/server';
import { v } from 'convex/values';
export default defineSchema({
users: defineTable({
clerkUser: v.any(),
}).index('by_clerk_id', ['clerkUser.id']),
});
+23
View File
@@ -0,0 +1,23 @@
{
/* This TypeScript project config describes the environment that
* Convex functions run in and is used to typecheck them.
* You can modify it, but some settings required to use Convex.
*/
"compilerOptions": {
/* These settings are not required by Convex and can be modified. */
"allowJs": true,
"strict": true,
/* These compiler options are required by Convex */
"target": "ESNext",
"lib": ["ES2021", "dom"],
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true,
"module": "ESNext",
"moduleResolution": "Node",
"isolatedModules": true,
"noEmit": true
},
"include": ["./**/*"],
"exclude": ["./_generated"]
}
+49
View File
@@ -0,0 +1,49 @@
import { UserJSON } from '@clerk/nextjs/dist/types/server';
import { v } from 'convex/values';
import { Doc } from './_generated/dataModel';
import { QueryCtx, internalMutation, internalQuery } from './_generated/server';
export const getUser = internalQuery({
args: { subject: v.string() },
async handler(ctx, args) {
return await userQuery(ctx, args.subject);
},
});
export async function userQuery(
ctx: QueryCtx,
clerkUserId: string
): Promise<(Omit<Doc<'users'>, 'clerkUser'> & { clerkUser: UserJSON }) | null> {
return await ctx.db
.query('users')
.withIndex('by_clerk_id', q => q.eq('clerkUser.id', clerkUserId))
.unique();
}
export const updateOrCreateUser = internalMutation({
args: { clerkUser: v.any() },
async handler(ctx, { clerkUser }: { clerkUser: UserJSON }) {
const userRecord = await userQuery(ctx, clerkUser.id);
if (userRecord === null) {
await ctx.db.insert('users', { clerkUser });
return;
}
await ctx.db.patch(userRecord._id, { clerkUser });
},
});
export const deleteUser = internalMutation({
args: { id: v.string() },
async handler(ctx, { id }) {
const userRecord = await userQuery(ctx, id);
if (userRecord === null) {
console.warn("can't delete user, does not exist", id);
return;
}
await ctx.db.delete(userRecord._id);
},
});
+1080
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -9,16 +9,21 @@
"lint": "next lint"
},
"dependencies": {
"@clerk/nextjs": "^4.23.5",
"@types/node": "20.6.0",
"@types/react": "18.2.21",
"@types/react-dom": "18.2.7",
"autoprefixer": "10.4.15",
"convex": "^1.2.1",
"eslint": "8.49.0",
"eslint-config-next": "13.4.19",
"next": "13.4.19",
"next-themes": "^0.2.1",
"postcss": "8.4.29",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.11.0",
"svix": "^1.11.0",
"tailwindcss": "3.3.3",
"typescript": "5.2.2"
}
+20
View File
@@ -0,0 +1,20 @@
'use client';
import { UserProfile } from '@clerk/nextjs';
export default function AccountPage() {
return (
<main className='flex flex-col items-center'>
<UserProfile
appearance={{
elements: {
card: 'shadow-md dark:bg-secondary-gray [&_*:not(button):not(a)]:dark:text-white',
navbar: 'dark:bg-secondary-gray [&_*]:dark:text-white',
formFieldInput: 'dark:bg-primary-gray dark:text-white',
profileSectionTitle: 'dark:border-white dark:border-opacity-10',
},
}}
/>
</main>
);
}
+22 -2
View File
@@ -1,3 +1,6 @@
import Navbar from '@/components/Navbar';
import { ConvexProvider, NextThemesProvider } from '@/providers';
import { ClerkProvider } from '@clerk/nextjs';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
@@ -14,8 +17,25 @@ export default function RootLayout({
children: React.ReactNode;
}) {
return (
<html lang='en'>
<body className={inter.className}>{children}</body>
<html
lang='en'
className='w-full h-full'
suppressHydrationWarning
>
<body
className={`w-full h-full flex flex-col bg-white text-primary-gray dark:bg-primary-gray dark:text-white ${inter.className}`}
>
<ClerkProvider
publishableKey={process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY}
>
<ConvexProvider>
<NextThemesProvider>
<Navbar />
<div className='p-4'>{children}</div>
</NextThemesProvider>
</ConvexProvider>
</ClerkProvider>
</body>
</html>
);
}
+25
View File
@@ -0,0 +1,25 @@
'use client';
import { SignIn } from '@clerk/nextjs';
export default function LoginPage() {
return (
<main className='flex flex-col items-center'>
<SignIn
appearance={{
elements: {
card: 'shadow-md dark:bg-secondary-gray [&_*:not(button):not(a)]:dark:text-white',
socialButtonsIconButton__github:
'hover:bg-gradient-to-br from-blue-600 via-purple-600 to-red-600 dark:border-white dark:border-opacity-10',
socialButtonsIconButton__google:
'hover:bg-gradient-to-r from-blue-500 via-green-500 to-yellow-500 dark:border-white dark:border-opacity-10',
socialButtonsIconButton__microsoft:
'hover:bg-gradient-to-r from-red-600 via-green-600 to-blue-600 dark:border-white dark:border-opacity-10',
dividerLine: 'dark:bg-white dark:bg-opacity-10',
formFieldInput: 'dark:bg-primary-gray dark:text-white',
},
}}
/>
</main>
);
}
+1 -5
View File
@@ -1,7 +1,3 @@
export default function Home() {
return (
<main>
<h1>conveX</h1>
</main>
);
return <main></main>;
}
+25
View File
@@ -0,0 +1,25 @@
'use client';
import { SignUp } from '@clerk/nextjs';
export default function SignUpPage() {
return (
<main className='flex flex-col items-center'>
<SignUp
appearance={{
elements: {
card: 'shadow-md dark:bg-secondary-gray [&_*:not(button):not(a):not(svg)]:dark:text-white',
socialButtonsIconButton__github:
'hover:bg-gradient-to-br from-blue-600 via-purple-600 to-red-600 dark:border-white dark:border-opacity-10',
socialButtonsIconButton__google:
'hover:bg-gradient-to-r from-blue-500 via-green-500 to-yellow-500 dark:border-white dark:border-opacity-10',
socialButtonsIconButton__microsoft:
'hover:bg-gradient-to-r from-red-600 via-green-600 to-blue-600 dark:border-white dark:border-opacity-10',
dividerLine: 'dark:bg-white dark:bg-opacity-10',
formFieldInput: 'dark:bg-primary-gray dark:text-white',
},
}}
/>
</main>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { SignedIn, SignedOut, UserButton } from '@clerk/nextjs';
import Link from 'next/link';
import ThemeButton from './ThemeButton';
export default function Navbar() {
return (
<nav className='flex items-center justify-between p-5 shadow-md dark:bg-secondary-gray'>
<ul className='flex items-center gap-4'>
<li>
<Link
href='/'
className='italic'
>
conve
<span className='font-bold text-4xl text-primary-accent'>X</span>
</Link>
</li>
</ul>
<ul className='flex items-center gap-4'>
<li>
<ThemeButton />
</li>
<SignedIn>
<li>
<UserButton
appearance={{
elements: {
card: 'dark:bg-secondary-gray [&_*]:dark:text-white',
userButtonTrigger:
'border-solid border-2 border-primary-accent focus:shadow-none',
},
}}
userProfileMode='navigation'
userProfileUrl='/account'
signInUrl='/login'
afterSignOutUrl='/'
/>
</li>
</SignedIn>
<SignedOut>
<li>
<Link href='/login'>Sign in</Link>
</li>
<li>
<Link href='/signup'>Sign up</Link>
</li>
</SignedOut>
</ul>
</nav>
);
}
+30
View File
@@ -0,0 +1,30 @@
'use client';
import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
import { BsMoonStarsFill, BsSunFill } from 'react-icons/bs';
import { ImSpinner2 } from 'react-icons/im';
export default function ThemeButton() {
const [mounted, setMounted] = useState(false);
const { theme, setTheme } = useTheme();
useEffect(() => setMounted(true), []);
const isDark = theme === 'dark';
return (
<button
className='flex items-center justify-center'
onClick={() => setTheme(isDark ? 'light' : 'dark')}
>
{mounted === false ? (
<ImSpinner2 className='w-5 h-5 animate-spin' />
) : isDark ? (
<BsMoonStarsFill className='w-5 h-5' />
) : (
<BsSunFill className='w-5 h-5' />
)}
</button>
);
}
+9
View File
@@ -0,0 +1,9 @@
import { authMiddleware } from '@clerk/nextjs';
export default authMiddleware({
publicRoutes: [],
});
export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
+38
View File
@@ -0,0 +1,38 @@
'use client';
import { useAuth } from '@clerk/nextjs';
import { ConvexReactClient } from 'convex/react';
import { ConvexProviderWithClerk } from 'convex/react-clerk';
import { ThemeProvider } from 'next-themes';
import { ReactNode } from 'react';
const CONVEX_URL = process.env.NEXT_PUBLIC_CONVEX_URL;
if (CONVEX_URL === undefined) {
throw Error('NEXT_PUBLIC_CONVEX_URL is undefined');
}
const client = new ConvexReactClient(CONVEX_URL);
export function ConvexProvider({ children }: { children: ReactNode }) {
return (
<ConvexProviderWithClerk
client={client}
useAuth={useAuth}
>
{children}
</ConvexProviderWithClerk>
);
}
export function NextThemesProvider({ children }: { children: ReactNode }) {
return (
<ThemeProvider
attribute='class'
defaultTheme='light'
enableSystem
>
{children}
</ThemeProvider>
);
}
+8 -1
View File
@@ -1,13 +1,20 @@
import type { Config } from 'tailwindcss';
const config: Config = {
darkMode: 'class',
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
extend: {
colors: {
'primary-gray': '#24272d',
'secondary-gray': '#2f333a',
'primary-accent': '#3743e5',
},
},
},
plugins: [],
};