Skip to content

Commit

Permalink
chore: Add .vercel to .gitignore files and update npm dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
Sivanwol committed Aug 18, 2024
1 parent 2fd5de9 commit b02c2d6
Show file tree
Hide file tree
Showing 20 changed files with 193 additions and 85 deletions.
1 change: 1 addition & 0 deletions apps/backoffice/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
2 changes: 1 addition & 1 deletion apps/backoffice/src/app/platform/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Suspense } from "react";
import { redirect } from "next/navigation";
import { session } from "@descope/nextjs-sdk/server";
import { getSessionToken, useDescope } from "@descope/react-sdk";
import { red } from "@mui/material/colors";

import type { MenuGroup } from "@app/ui";
import { DefaultLayout, LoadingPage } from "@app/ui";
Expand Down Expand Up @@ -52,7 +53,6 @@ const menuGroups: MenuGroup[] = [
export default async function PlatformLayout({ children }: { children: any }) {
const currSession = session();
console.log("layout session", currSession);
// api.
if (!currSession) {
redirect("/auth");
}
Expand Down
1 change: 1 addition & 0 deletions apps/platform/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
2 changes: 1 addition & 1 deletion apps/platform/src/app/api/user/register/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export async function POST(_req: NextRequest) {
const firstName = formData.firstName as string;
const lastName = formData.lastName as string;
const email = formData.email as string;
const phone = formData.phone || ("" as string);
const phone = (formData.phone || "") as string;
console.log(`register feedback from descope ${externalId}`);
if (!(await repositories.user.locateUserByExternalId(externalId))) {
console.log(`payload user info`, {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"db:migrate": "turbo -F @app/db migrate",
"db:push": "turbo -F @app/db push",
"db:studio": "turbo -F @app/db studio",
"dev": "turbo watch dev",
"dev": "turbo watch dev --concurrency=20",
"dev:platform": "turbo watch dev -F @app/platform",
"dev:backoffice": "turbo watch dev -F @app/backoffice",
"format": "turbo run format --continue -- --cache --cache-location node_modules/.cache/.prettiercache",
Expand Down
20 changes: 1 addition & 19 deletions packages/auth/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,6 @@ import { z } from "zod";

export const env = createEnv({
server: {
// AUTH_FACEBOOK_ID:
// process.env.NODE_ENV === "production"
// ? z.string().min(1)
// : z.string().min(1).optional(),
// AUTH_FACEBOOK_SECRET:
// process.env.NODE_ENV === "production"
// ? z.string().min(1)
// : z.string().min(1).optional(),
// AUTH_GOOGLE_ID: z.string().min(1),
// AUTH_GOOGLE_SECRET: z.string().min(1),
// AUTH_APPLE_ID:
// process.env.NODE_ENV === "production"
// ? z.string().min(1)
// : z.string().min(1).optional(),
// AUTH_APPLE_SECRET:
// process.env.NODE_ENV === "production"
// ? z.string().min(1)
// : z.string().min(1).optional(),

// AUTH_DESCOPE_ID: z.string().min(1),
BLOB_STORAGE_URL: z.string().min(1),
KV_URL: z.string().min(1),
Expand All @@ -31,6 +12,7 @@ export const env = createEnv({
KV_REST_API_READ_ONLY_TOKEN: z.string().min(1),
AUTH_DESCOPE_SECRET: z.string().min(1),
AUTH_DESCOPE_ISSUER: z.string().min(1),
AUTH_DESCOPE_MGT_KEY: z.string().min(1),
AUTH_SECRET:
process.env.NODE_ENV === "production"
? z.string().min(1)
Expand Down
1 change: 1 addition & 0 deletions packages/auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
"dev": "tsc",
"format": "prettier --check . --ignore-path ../../.gitignore",
"lint": "eslint",
"typecheck": "tsc --noEmit"
Expand Down
121 changes: 99 additions & 22 deletions packages/auth/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,27 @@ import { skipCSRFCheck } from "@auth/core";
import Descope from "@auth/core/providers/descope";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { createSdk } from "@descope/nextjs-sdk/server";
import { kv } from "@vercel/kv";
import { fromUnixTime } from "date-fns";
import superjson from "superjson";
import { z } from "zod";

import type { MediaModel, UserModel } from "@app/db/client";
import { db, repositories } from "@app/db/client";
import { CacheConfig } from "@app/utils";

import { env } from "../env";

const adapter = DrizzleAdapter(db);

export const isSecureContext = env.NODE_ENV !== "development";
console.log({
projectId: env.NEXT_PUBLIC_AUTH_DESCOPE_ID || "",
managementKey: env.AUTH_DESCOPE_MGT_KEY || "",
});
export const descopeSdk = createSdk({
projectId: env.NEXT_PUBLIC_AUTH_DESCOPE_ID || "",
managementKey: env.AUTH_DESCOPE_MGT_KEY || "",
});
export const authConfig = {
adapter,
Expand Down Expand Up @@ -55,52 +64,120 @@ declare module "next-auth" {
user: {
image: string | null;
imageMedia: MediaModel | null;
phone: string | null; // Add the 'phone' property
} & DefaultSession["user"];
userProfile: UserModel | null;
}
}

/** User base details from Descope API */
interface User {
email?: string;
name?: string;
givenName?: string;
middleName?: string;
familyName?: string;
phone?: string;
}
/** User extended details from Descope API */
type UserResponse = User & {
loginIds: string[];
userId: string;
verifiedEmail?: boolean;
verifiedPhone?: boolean;
picture?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customAttributes?: Record<string, any>;
status: string;
};
const registerInitalUserForOnboarding = async (user: UserResponse) => {
console.log(`check if user by id ${user.userId} need do onboarding`);
const requiredOnborading = await repositories.user.HasUserNeedOnBoarding(
user.userId,
);
if (requiredOnborading) {
console.log(`user did onboarding ${user.userId} not required`);
const splitName = user.name?.split(" ") ?? ["", ""];
await repositories.user.register({
externalId: user.userId,
firstName: splitName[0] ?? "",
lastName: splitName[1] ?? "",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
email: user.email!,
phone: "",
});
return;
}
};

const sendAndParseUserInformation = async (
userResp: UserResponse,
authExpDate: number,
) => {
const { userId } = userResp;
const user = await repositories.user.GetUserShortInfoByExternalId(userId);
let avatarUrl = "";
let media = null;
if (user?.avatar) {
media = await repositories.media.GetMediaById(user.avatar);
avatarUrl = env.BLOB_STORAGE_URL + media?.path;
}
return {
user: {
id: userId,
name: `${user?.firstName} ${user?.lastName}`,
email: user?.email,
phone: user?.phone ?? null,
imageMedia: media,
image: user?.avatar ? avatarUrl : null,
},
userProfile: user,
expires: fromUnixTime(authExpDate).toISOString(),
};
};

export const validateToken = async (
token: string,
): Promise<NextAuthSession | null> => {
console.log(`validate token`);
let sessionRes = null;
try {
sessionRes = await descopeSdk.validateJwt(token);
sessionRes = await descopeSdk.validateSession(token);
console.log(`user validated to user ${sessionRes.token.sub}`);
} catch (error) {
console.log("Could not validate user session ", error);
console.error("Could not validate user session ", error);
return null;
}
const authToken = sessionRes.token;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const userId = authToken.sub!;
const res = await fetchCurrentDescopeUserDetails(userId);
if (!res) {
console.error("Could not load user info from descope ");
return null;
}
const descopeUserInfo = res;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const authExpDate = authToken.exp!;
console.log(`locate user ${userId}`);
const user = await repositories.user.GetUserShortInfoByExternalId(userId);
console.log("sessionToken", authToken);
let user = await repositories.user.GetUserShortInfoByExternalId(userId);
console.log(`found user ${userId}`, user);
if (!user) {
console.error(`User not found for id ${userId}`);
return null;
console.warn(`User not register need onboarding ${userId}`);
await registerInitalUserForOnboarding(descopeUserInfo);
user = await repositories.user.GetUserShortInfoByExternalId(userId);
}
console.log("sessionToken", authToken);
let avatarUrl = "";
let media = null;
if (user.avatar) {
media = await repositories.media.GetMediaById(user.avatar);
avatarUrl = env.BLOB_STORAGE_URL + media?.path;
return sendAndParseUserInformation(descopeUserInfo, authExpDate);
};

export const fetchCurrentDescopeUserDetails = async (extrenalId: string) => {
console.log(`fetch user details ${extrenalId}`);
const request = await descopeSdk.management.user.loadByUserId(extrenalId);
if (request.ok) {
return request.data;
}
return {
user: {
id: userId,
name: `${user.firstName} ${user.lastName}`,
email: user.email,
imageMedia: media,
image: user.avatar ? avatarUrl : null,
},
userProfile: user,
expires: fromUnixTime(authExpDate).toISOString(),
};
return null;
};

export const invalidateSessionToken = async (token: string) => {
Expand Down
8 changes: 5 additions & 3 deletions packages/backoffice-api/src/router/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type { TRPCRouterRecord } from "@trpc/server";
import { kv } from "@vercel/kv";
import superjson from "superjson";
import { z } from "zod";

import { invalidateSessionToken } from "@app/auth";
import { repositories } from "@app/db/client";
import { CacheConfig } from "@app/utils";

import { protectedProcedure, publicProcedure } from "../trpc";

Expand All @@ -11,9 +16,6 @@ export const authRouter = {
getUser: protectedProcedure.query(({ ctx }) => {
return ctx.user;
}),
getSecretMessage: protectedProcedure.query(() => {
return "you can see this secret message!";
}),
// eslint-disable-next-line @typescript-eslint/require-await
signOut: protectedProcedure.mutation(async (opts) => {
// if (!opts.ctx.token) {
Expand Down
4 changes: 2 additions & 2 deletions packages/backoffice-api/src/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
console.log(
`incoming protected procedure... ${JSON.stringify(auth?.userProfile)}... at $}{new Date().toISOString()}`,
);

if (!auth?.userProfile) {
if (!auth?.user.id) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: `Sync issue ${ctx.user?.id} has no db record or not existed user`,
Expand All @@ -117,6 +116,7 @@ export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
cookies: { ...ctx.session?.cookies },
jwt: ctx.session?.jwt,
token: { ...ctx.session?.token },
descopeUser: auth.user,
user: auth.userProfile,
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ CREATE TABLE IF NOT EXISTS "media" (
CREATE TABLE IF NOT EXISTS "user" (
"id" serial PRIMARY KEY NOT NULL,
"external_id" varchar(255),
"first_name" varchar(100) NOT NULL,
"last_name" varchar(100) NOT NULL,
"first_name" varchar(100),
"last_name" varchar(100),
"about_me" varchar(500),
"email" varchar(255) NOT NULL,
"phone" varchar(20),
Expand All @@ -170,17 +170,18 @@ CREATE TABLE IF NOT EXISTS "user" (
"address" varchar(255),
"status" "status" DEFAULT 'single',
"user_type" "type" DEFAULT 'driver',
"blocked_at" timestamp,
"onboarding" boolean,
"blocked" boolean,
"created_at" timestamp DEFAULT now() NOT NULL,
"updatedAt" timestamp with time zone,
CONSTRAINT "user_external_id_unique" UNIQUE("external_id")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "vehicle_audits" (
"id" serial PRIMARY KEY NOT NULL,
"vehicle_id" serial NOT NULL,
"vehicle_id" integer,
"note" varchar(500),
"vehicle_image_id" serial NOT NULL,
"vehicle_image_id" integer,
"mileage" integer DEFAULT 0,
"checkout_at" timestamp,
"repair_at" timestamp,
Expand Down
26 changes: 16 additions & 10 deletions packages/db/migrations/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "f5983af7-b1fb-4eec-8f57-7b8ce745bc86",
"id": "09376e1c-a257-4459-b6fa-04b985f19ae9",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
Expand Down Expand Up @@ -695,13 +695,13 @@
"name": "first_name",
"type": "varchar(100)",
"primaryKey": false,
"notNull": true
"notNull": false
},
"last_name": {
"name": "last_name",
"type": "varchar(100)",
"primaryKey": false,
"notNull": true
"notNull": false
},
"about_me": {
"name": "about_me",
Expand Down Expand Up @@ -797,9 +797,15 @@
"notNull": false,
"default": "'driver'"
},
"blocked_at": {
"name": "blocked_at",
"type": "timestamp",
"onboarding": {
"name": "onboarding",
"type": "boolean",
"primaryKey": false,
"notNull": false
},
"blocked": {
"name": "blocked",
"type": "boolean",
"primaryKey": false,
"notNull": false
},
Expand Down Expand Up @@ -850,9 +856,9 @@
},
"vehicle_id": {
"name": "vehicle_id",
"type": "serial",
"type": "integer",
"primaryKey": false,
"notNull": true
"notNull": false
},
"note": {
"name": "note",
Expand All @@ -862,9 +868,9 @@
},
"vehicle_image_id": {
"name": "vehicle_image_id",
"type": "serial",
"type": "integer",
"primaryKey": false,
"notNull": true
"notNull": false
},
"mileage": {
"name": "mileage",
Expand Down
Loading

0 comments on commit b02c2d6

Please sign in to comment.