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
5 changes: 4 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ NEXT_PUBLIC_ZERO_SERVER='http://localhost:4848'
ZERO_UPSTREAM_DB="postgresql://user:password@127.0.0.1:5432/zstart"
ZERO_CVR_DB="postgresql://user:password@127.0.0.1:5432/zstart_cvr"
ZERO_CHANGE_DB="postgresql://user:password@127.0.0.1:5432/zstart_cdb"
ZERO_AUTH_SECRET="secretkey"
ZERO_REPLICA_FILE="/tmp/zstart_replica.db"
ZERO_AUTH_JWKS_URL="http://localhost:3000/api/auth/jwks"

AUTH_SECRET="" # Added by `npx auth`. Read more: https://cli.authjs.dev

Expand All @@ -12,3 +12,6 @@ AUTH_DRIZZLE_URL=$ZERO_UPSTREAM_DB
AUTH_STRAVA_ID=
AUTH_STRAVA_SECRET=
AUTH_STRAVA_REDIRECT_URL="http://localhost:3000"

BETTER_AUTH_SECRET=
BETTER_AUTH_URL="http://localhost:3000"
4 changes: 1 addition & 3 deletions app/(app)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ export default async function Layout({
<Header />

<ClientOnly fallback={<div>Loading...</div>}>
<ZeroProvider userID={session.user.id} token={session.token}>
{children}
</ZeroProvider>
<ZeroProvider userID={session.user.id}>{children}</ZeroProvider>
</ClientOnly>
</>
);
Expand Down
65 changes: 0 additions & 65 deletions app/actions.ts

This file was deleted.

14 changes: 9 additions & 5 deletions components/single-user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ export const User = ({ id }: { id: string }) => {
const { value } = e.target;

z.mutate.user.update({
id: user.id,
id: user?.id,
name: value,
});
};

if (!user) {
return <div>Loading</div>;
}

return (
<div>
<button
Expand All @@ -41,9 +45,9 @@ export const User = ({ id }: { id: string }) => {
) : (
<div>
<div>User: {user?.name}</div>
<div>User Email: {user?.email}</div>
{/* <div>User Email: {user?.email}</div> */}
<div>ID: {user?.id}</div>
<div>
{/* <div>
User Image:
{user?.image && (
<img
Expand All @@ -54,8 +58,8 @@ export const User = ({ id }: { id: string }) => {
alt="user avatar"
/>
)}
</div>
<div>Provider: {user?.provider?.provider}</div>
</div> */}
<div>Provider: {user?.provider?.providerId}</div>
</div>
)}
</div>
Expand Down
2 changes: 1 addition & 1 deletion components/user-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function UserList() {
{users.length > 0 ? (
<ul className="list-disc list-inside">
{users.map((u) => {
const name = `${u.name} - ${u?.provider?.provider ?? "no provider provided"}`;
const name = `${u.name} - ${u?.provider?.providerId ?? "no provider provided"}`;

return (
<li key={u.id}>
Expand Down
22 changes: 18 additions & 4 deletions components/zero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,35 @@ import { type Schema, schema } from "../schema";
export function ZeroProvider({
children,
userID,
token,
}: {
children: ReactNode;
userID: string;
token: string;
}) {
const z = useMemo(() => {
const jwtStorageKey = `jwt-${userID}`;

return new Zero({
userID,
auth: token,
auth: async (error) => {
if (error === "invalid-token") {
sessionStorage.removeItem(jwtStorageKey);
}
let token = sessionStorage.getItem(jwtStorageKey);
if (!token) {
if (!userID) return undefined;
const response = await fetch("/api/auth/token");
const data = await response.json();
token = data.token;
if (!token) throw new Error("No token found");
sessionStorage.setItem(jwtStorageKey, token);
}
return token ?? undefined;
},
server: process.env.NEXT_PUBLIC_ZERO_SERVER,
schema,
kvStore: "mem",
});
}, [userID, token]);
}, [userID]);

return <ZeroProviderBase zero={z}>{children}</ZeroProviderBase>;
}
Expand Down
8 changes: 7 additions & 1 deletion db/schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { AdapterAccountType } from "@auth/core/adapters";
import { relations, sql } from "drizzle-orm";
import {
boolean,
Expand Down Expand Up @@ -231,3 +230,10 @@ export const tasksRelations = relations(tasks, ({ one }) => ({
references: [user.id],
}),
}));

export const jwks = pgTable("jwks", {
id: text("id").primaryKey(),
publicKey: text("public_key").notNull(),
privateKey: text("private_key").notNull(),
createdAt: timestamp("created_at").notNull(),
});
3 changes: 1 addition & 2 deletions drizzle-zero.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ export default drizzleZeroConfig(drizzleSchema, {
tables: {
providers: true,
account: true,
// this can be set to false
// e.g. users: false,
activities: true,
user: true,
todos: {
Expand All @@ -24,6 +22,7 @@ export default drizzleZeroConfig(drizzleSchema, {
assignedToId: true,
timestamp: true,
},
jwks: false,
tasks: {
id: true,
name: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ CREATE TABLE "activity" (
"updatedAt" text DEFAULT (CURRENT_TIMESTAMP) NOT NULL
);
--> statement-breakpoint
CREATE TABLE "jwks" (
"id" text PRIMARY KEY NOT NULL,
"public_key" text NOT NULL,
"private_key" text NOT NULL,
"created_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
Expand Down
39 changes: 38 additions & 1 deletion drizzle/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "e6e6d81b-76f5-4b8d-911a-987c3ca1f36e",
"id": "9004671c-1eb4-4f01-9e8f-349feb8c0522",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
Expand Down Expand Up @@ -190,6 +190,43 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.jwks": {
"name": "jwks",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"public_key": {
"name": "public_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
"private_key": {
"name": "private_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
Expand Down
4 changes: 2 additions & 2 deletions drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
{
"idx": 0,
"version": "7",
"when": 1760804593389,
"tag": "0000_chubby_absorbing_man",
"when": 1760974090046,
"tag": "0000_nappy_tarot",
"breakpoints": true
}
]
Expand Down
1 change: 0 additions & 1 deletion lib/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
plugins: [genericOAuthClient()],
// baseURL: "http://localhost:3000",
});

export const { signIn, signOut, useSession } = authClient;
16 changes: 3 additions & 13 deletions lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { customSession, genericOAuth } from "better-auth/plugins";
import { customSession, genericOAuth, jwt } from "better-auth/plugins";
import { db } from "@/db"; // your drizzle instance
import { getNewToken } from "../app/actions";

export const auth = betterAuth({
database: drizzleAdapter(db, {
Expand Down Expand Up @@ -42,7 +41,6 @@ export const auth = betterAuth({
const data = await fetch("https://www.strava.com/api/v3/athlete", {
headers: { Authorization: `Bearer ${tokens.accessToken}` },
}).then((data) => data.json());
console.log({ data });
return {
...data,
email: data.username, // This is required to fix the error, even though it makes no sense b/c it isn't an email
Expand All @@ -58,21 +56,13 @@ export const auth = betterAuth({
where: (account, { eq }) => eq(account.userId, user.id),
});

const getJWTToken = await getNewToken(user.id);

// console.log({ account });
// const roles = findUserRoles(session.session.userId);
return {
// roles,
user: {
...user,
newField: "newField",
},
user,
session,
account,
token: getJWTToken,
};
}),
jwt(),
],
baseURL: process.env.BETTER_AUTH_URL,
});