Skip to content

Open-source status page, incident response and uptime monitoring

🚀 create user and redirect (#40)

Thibault Le Ouay3eac2a9ae680
diff --git a/apps/web/package.json b/apps/web/package.json
index 9fc7db89d..1de3eb2e3 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -9,7 +9,7 @@
"lint": "next lint"
},
"dependencies": {
- "@clerk/nextjs": "4.21.10",
+ "@clerk/nextjs": "4.21.14",
"@openstatus/api": "workspace:^",
"@openstatus/db": "workspace:^",
"@openstatus/tinybird": "workspace:*",
diff --git a/apps/web/src/app/api/webhook/clerk/route.ts b/apps/web/src/app/api/webhook/clerk/route.ts
index 915bceaa0..589fcfb89 100644
--- a/apps/web/src/app/api/webhook/clerk/route.ts
+++ b/apps/web/src/app/api/webhook/clerk/route.ts
@@ -31,7 +31,6 @@ export async function POST(req: NextRequest) {
const ctx = createTRPCContext({ req });
const caller = lambdaRouter.createCaller(ctx);
-
const event = r.data.type;
switch (event) {
case "user.created":
diff --git a/apps/web/src/app/app/(auth)/sign-in/[[...sign-in]]/page.tsx b/apps/web/src/app/app/(auth)/sign-in/[[...sign-in]]/page.tsx
index 5ee3fe347..be02cbf49 100644
--- a/apps/web/src/app/app/(auth)/sign-in/[[...sign-in]]/page.tsx
+++ b/apps/web/src/app/app/(auth)/sign-in/[[...sign-in]]/page.tsx
@@ -1,5 +1,9 @@
-import { SignIn } from "@clerk/nextjs";
+"use client";
+
+import { SignIn, useSignIn, useSignUp } from "@clerk/nextjs";
export default function Page() {
- return <SignIn />;
-}
\ No newline at end of file
+ const { isLoaded, signIn } = useSignIn();
+
+ return <SignIn redirectUrl={"/app"} />;
+}
diff --git a/apps/web/src/app/app/(auth)/sign-up/[[...sign-up]]/page.tsx b/apps/web/src/app/app/(auth)/sign-up/[[...sign-up]]/page.tsx
index 20e230ba4..6e034c062 100644
--- a/apps/web/src/app/app/(auth)/sign-up/[[...sign-up]]/page.tsx
+++ b/apps/web/src/app/app/(auth)/sign-up/[[...sign-up]]/page.tsx
@@ -1,5 +1,8 @@
-import { SignUp } from "@clerk/nextjs";
+import { SignUp, useSignUp } from "@clerk/nextjs";
export default function Page() {
- return <SignUp />;
-}
\ No newline at end of file
+ const { signUp } = useSignUp();
+
+ console.log("signUp", signUp);
+ return <SignUp redirectUrl={"/app"} />;
+}
diff --git a/apps/web/src/app/app/(dashboard)/endpoint/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceId]/endpoint/page.tsx
similarity index 100%
rename from apps/web/src/app/app/(dashboard)/endpoint/page.tsx
rename to apps/web/src/app/app/(dashboard)/[workspaceId]/endpoint/page.tsx
diff --git a/apps/web/src/app/app/(dashboard)/incident/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceId]/incident/page.tsx
similarity index 100%
rename from apps/web/src/app/app/(dashboard)/incident/page.tsx
rename to apps/web/src/app/app/(dashboard)/[workspaceId]/incident/page.tsx
diff --git a/apps/web/src/app/app/(dashboard)/monitor/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceId]/monitor/page.tsx
similarity index 100%
rename from apps/web/src/app/app/(dashboard)/monitor/page.tsx
rename to apps/web/src/app/app/(dashboard)/[workspaceId]/monitor/page.tsx
diff --git a/apps/web/src/app/app/(dashboard)/[workspaceId]/page.tsx b/apps/web/src/app/app/(dashboard)/[workspaceId]/page.tsx
new file mode 100644
index 000000000..a69f85c95
--- /dev/null
+++ b/apps/web/src/app/app/(dashboard)/[workspaceId]/page.tsx
@@ -0,0 +1,14 @@
+import * as React from "react";
+import { auth, currentUser } from "@clerk/nextjs";
+
+import { Header } from "@/components/header";
+
+export default async function AppPage() {
+ const user = await currentUser();
+ console.log({ user });
+ return (
+ <div>
+ <Header title="App" description="Overview of all your websites" />
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/app-sidebar.tsx b/apps/web/src/components/layout/app-sidebar.tsx
index dc6eafbb7..7cc4147bb 100644
--- a/apps/web/src/components/layout/app-sidebar.tsx
+++ b/apps/web/src/components/layout/app-sidebar.tsx
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
-import { usePathname } from "next/navigation";
+import { useParams, usePathname } from "next/navigation";
import { pagesConfig } from "@/config/pages";
import { cn } from "@/lib/utils";
@@ -9,6 +9,7 @@ import { Icons } from "../icons";
export function AppSidebar() {
const pathname = usePathname();
+ const params = useParams();
return (
<ul className="grid gap-1">
{pagesConfig.map(({ title, href, icon, disabled }) => {
@@ -16,7 +17,7 @@ export function AppSidebar() {
return (
<li key={title} className="w-full">
<Link
- href={href}
+ href={`/app/${params.workspaceId}/${href}`}
className={cn(
"hover:bg-muted/50 hover:text-foreground text-muted-foreground group -mx-2 flex w-full min-w-[200px] items-center rounded-md border border-transparent px-3 py-1",
pathname === href &&
diff --git a/apps/web/src/config/pages.ts b/apps/web/src/config/pages.ts
index 0671f5d70..b0ed76be3 100644
--- a/apps/web/src/config/pages.ts
+++ b/apps/web/src/config/pages.ts
@@ -12,25 +12,25 @@ export const pagesConfig = [
{
title: "Dashboard",
description: "Get an overview of what's hot.",
- href: "/app",
+ href: "/",
icon: "layout-dashboard",
},
{
title: "Endpoint",
description: "Keep track of all your endpoints.",
- href: "/app/endpoint",
+ href: "/endpoint",
icon: "link",
},
{
title: "Monitor",
description: "Check all the responses in one place.",
- href: "/app/monitor",
+ href: "/monitor",
icon: "activity",
},
{
title: "Incident",
description: "War room where you handle the incidents.",
- href: "/app/incident",
+ href: "/incident",
icon: "siren",
disabled: true,
},
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index f744dfb90..defffb594 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -1,4 +1,10 @@
-import { authMiddleware } from "@clerk/nextjs";
+import { NextResponse } from "next/server";
+import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
+
+import { createTRPCContext } from "@openstatus/api";
+import { edgeRouter } from "@openstatus/api/src/edge";
+import { db, eq } from "@openstatus/db";
+import { user, usersToWorkspaces } from "@openstatus/db/src/schema";
export default authMiddleware({
publicRoutes: [
@@ -15,8 +21,35 @@ export default authMiddleware({
"/api/checker/regions/(.*)",
"/api/checker/cron/10m",
],
+ async afterAuth(auth, req, evt) {
+ // handle users who aren't authenticated
+ if (!auth.userId && !auth.isPublicRoute) {
+ return redirectToSignIn({ returnBackUrl: req.url });
+ }
+
+ // redirect them to organization selection page
+ if (auth.userId && req.nextUrl.pathname === "/app") {
+ const userQuery = db
+ .select()
+ .from(user)
+ .where(eq(user.tenantId, auth.userId))
+ .as("userQuery");
+ const result = await db
+ .select()
+ .from(usersToWorkspaces)
+ .leftJoin(userQuery, eq(userQuery.id, usersToWorkspaces.userId))
+ .execute();
+ if (result.length) {
+ const orgSelection = new URL(
+ `/app/${result[0].users_to_workspaces.workspaceId}`,
+ req.url,
+ );
+ return NextResponse.redirect(orgSelection);
+ }
+ }
+ },
});
export const config = {
- matcher: ["/((?!api|trpc|_next/static|_next/image|favicon.ico).*)"],
+ matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
diff --git a/packages/api/src/router/clerk/webhook.ts b/packages/api/src/router/clerk/webhook.ts
index 464839f2b..479968271 100644
--- a/packages/api/src/router/clerk/webhook.ts
+++ b/packages/api/src/router/clerk/webhook.ts
@@ -1,6 +1,6 @@
import * as z from "zod";
-import { user } from "@openstatus/db/src/schema";
+import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema";
import { createTRPCRouter, publicProcedure } from "../../trpc";
import { clerkEvent } from "./type";
@@ -14,9 +14,28 @@ export const webhookProcedure = publicProcedure.input(
export const webhookRouter = createTRPCRouter({
userCreated: webhookProcedure.mutation(async (opts) => {
if (opts.input.data.type === "user.created") {
- await opts.ctx.db.insert(user).values({
- tenantId: opts.input.data.data.id,
- });
+ // There's no primary key with drizzle I checked the tennant is not already in the database
+ const alreadyExists = await opts.ctx.db
+ .select({ id: user.id })
+ .from(user);
+
+ if (alreadyExists.length) return;
+
+ const userResult = await opts.ctx.db
+ .insert(user)
+ .values({
+ tenantId: opts.input.data.data.id,
+ })
+ .execute();
+ const workspaceResult = await opts.ctx.db.insert(workspace).values({});
+
+ await opts.ctx.db
+ .insert(usersToWorkspaces)
+ .values({
+ userId: Number(userResult.insertId),
+ workspaceId: Number(workspaceResult.insertId),
+ })
+ .execute();
}
}),
userUpdated: webhookProcedure.mutation(async (opts) => {
diff --git a/packages/api/src/router/workspace.ts b/packages/api/src/router/workspace.ts
index 5515f25d7..787500cff 100644
--- a/packages/api/src/router/workspace.ts
+++ b/packages/api/src/router/workspace.ts
@@ -8,7 +8,12 @@ import { createTRPCRouter, protectedProcedure } from "../trpc";
export const workspaceRouter = createTRPCRouter({
getUserWorkspace: protectedProcedure.query(async (opts) => {
return await opts.ctx.db.query.workspace.findMany({
- with: { user: { where: eq(user.tenantId, opts.ctx.auth.userId) } },
+ with: {
+ usersToWorkspaces: {
+ where: eq(user.tenantId, opts.ctx.auth.userId),
+ with: { user: true },
+ },
+ },
});
}),
getWorkspace: protectedProcedure
diff --git a/packages/db/src/schema/user.ts b/packages/db/src/schema/user.ts
index 28c0425c8..f68801678 100644
--- a/packages/db/src/schema/user.ts
+++ b/packages/db/src/schema/user.ts
@@ -1,5 +1,11 @@
import { relations } from "drizzle-orm";
-import { int, mysqlTable, timestamp, varchar } from "drizzle-orm/mysql-core";
+import {
+ int,
+ mysqlTable,
+ primaryKey,
+ timestamp,
+ varchar,
+} from "drizzle-orm/mysql-core";
import { workspace } from "./workspace";
@@ -12,5 +18,16 @@ export const user = mysqlTable("user", {
});
export const userRelations = relations(user, ({ many }) => ({
- workspace: many(workspace),
+ usersToWorkspaces: many(usersToWorkspaces),
}));
+
+export const usersToWorkspaces = mysqlTable(
+ "users_to_workspaces",
+ {
+ userId: int("user_id").notNull(),
+ workspaceId: int("workspace_id").notNull(),
+ },
+ (t) => ({
+ pk: primaryKey(t.userId, t.workspaceId),
+ }),
+);
diff --git a/packages/db/src/schema/workspace.ts b/packages/db/src/schema/workspace.ts
index 5d72ccabe..624fed59e 100644
--- a/packages/db/src/schema/workspace.ts
+++ b/packages/db/src/schema/workspace.ts
@@ -8,7 +8,7 @@ import {
} from "drizzle-orm/mysql-core";
import { page } from "./page";
-import { user } from "./user";
+import { user, usersToWorkspaces } from "./user";
export const workspace = mysqlTable("workspace", {
id: int("id").autoincrement().primaryKey(),
@@ -22,5 +22,5 @@ export const workspace = mysqlTable("workspace", {
export const workspaceRelations = relations(workspace, ({ many }) => ({
page: many(page),
- user: many(user),
+ usersToWorkspaces: many(usersToWorkspaces),
}));
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 287c5d914..35d0ce59d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -36,8 +36,8 @@ importers:
apps/web:
dependencies:
'@clerk/nextjs':
- specifier: 4.21.10
+ specifier: 4.21.14
'@openstatus/api':
specifier: workspace:^
version: link:../../packages/api
@@ -568,6 +568,19 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-An1VKCFlFTROUYuELDwY5B6FmbVmIDuW837t0JfgbOLBYo1yoUgXZHB/wttGISaHt+CiOs1+CAI2U3iHxkaxhA==}
+ engines: {node: '>=14'}
+ dependencies:
+ '@clerk/types': 3.46.1
+ '@peculiar/webcrypto': 1.4.1
+ '@types/node': 16.18.6
+ deepmerge: 4.2.2
+ node-fetch-native: 1.0.1
+ snakecase-keys: 5.4.4
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-y5edxot+7adnyUqOGNgS7bEA3eoM53FMC8jV8VmUFvKLkOOMQpgfdo3/I7PWoTrRaNwqNWmhQGy1J3uqw8gv4g==}
engines: {node: '>=14'}
@@ -581,6 +594,19 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-vtGOszKYpDdV3cFtiG24jf1UdFGrXIfIzTyjh3aHd2mXGE2dIm8m04X3+mHBDStJFpJNzim8f+7HMLVeMRJhkA==}
+ engines: {node: '>=14'}
+ peerDependencies:
+ react: '>=16'
+ dependencies:
+ '@clerk/shared': 0.19.1([email protected])
+ '@clerk/types': 3.46.1
+ react: 18.2.0
+ swr: 1.3.0([email protected])
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-6LzLFEMZMnUE4O19XOW/6LAoAnHP7mZ2scMCib4dOvTRQxcZz1ql34ZMzewNYKrS6V5loQlslc1bnPlJ2zoX3g==}
engines: {node: '>=14'}
@@ -596,6 +622,21 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-fif8iwedLDFgllPLx8xwxA66ICbp7KjsSULqb8mcKXHPnZ/xL17eZSx4puHg4CEGBmOxY6IL5nbRj1+s+TfgqQ==}
+ engines: {node: '>=14'}
+ dependencies:
+ '@clerk/backend': 0.24.0
+ '@clerk/types': 3.46.1
+ '@types/cookies': 0.7.7
+ '@types/express': 4.17.14
+ '@types/node-fetch': 2.6.2
+ camelcase-keys: 6.2.2
+ cookie: 0.5.0
+ snakecase-keys: 3.2.1
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-5G02qZOBwbYvBxbHVPKpINyhZ1a3TLZ3noBExx5JHo8+UbpEp7ENd1TyFF/oO0EWG/VTbloP1Gegjm2XG9KeKw==}
engines: {node: '>=14'}
@@ -615,6 +656,25 @@ packages:
tslib: 2.4.1
dev: false
+ resolution: {integrity: sha512-r+s9EKG0CPPj31p6UZmxPQ2A3+JVE70PmBYiC/pRrF3Oo57pYJGVmBB+eUWVYaYJNcJxhYoYb/QLsL8Xl0dUVQ==}
+ engines: {node: '>=14'}
+ peerDependencies:
+ next: '>=10'
+ react: ^17.0.2 || ^18.0.0-0
+ react-dom: ^17.0.2 || ^18.0.0-0
+ dependencies:
+ '@clerk/backend': 0.24.0
+ '@clerk/clerk-react': 4.22.0([email protected])
+ '@clerk/clerk-sdk-node': 4.10.15
+ '@clerk/types': 3.46.1
+ path-to-regexp: 6.2.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ tslib: 2.4.1
+ dev: false
+
resolution: {integrity: sha512-5RwASoff6CPgHcrM3kuvgUwp9qQa02zkjUdV8lNzQYEhojz6dfahLv3xZW3MS1UqDOIGrbrPviqi9pBmjpNKPA==}
peerDependencies:
@@ -633,6 +693,13 @@ packages:
csstype: 3.1.1
dev: false
+ resolution: {integrity: sha512-IA/iSXJJZym4Z6f9OcT9OJayK2opVhxUVJky15aY4iVsJCPScgApBuuzC7N4vfXwA6RI/wGebFbvmsEQ3oI/UA==}
+ engines: {node: '>=14'}
+ dependencies:
+ csstype: 3.1.1
+ dev: false
+
/@cspotcode/[email protected]:
resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
engines: {node: '>=12'}