chore: bulk commit of pre-existing changes
Build & Deploy / Build & Push Docker Image (push) Successful in 48s
Test / API Unit Tests (push) Successful in 9m48s
Test / Marketplace Unit Tests (push) Successful in 9m38s
Test / Admin Unit Tests (push) Successful in 9m33s
Build & Deploy / Deploy to VPS (push) Has been cancelled
Test / Dashboard Unit Tests (push) Has been cancelled
Test / API Integration Tests (push) Has been cancelled
Build & Deploy / Build & Push Docker Image (push) Successful in 48s
Test / API Unit Tests (push) Successful in 9m48s
Test / Marketplace Unit Tests (push) Successful in 9m38s
Test / Admin Unit Tests (push) Successful in 9m33s
Build & Deploy / Deploy to VPS (push) Has been cancelled
Test / Dashboard Unit Tests (push) Has been cancelled
Test / API Integration Tests (push) Has been cancelled
Includes: - Admin dashboard layout and page updates - API account auth module (routes, schemas, service) - Dashboard sign-up form extraction, middleware refactor - Marketplace proxy and middleware updates - CORS origins expansion for dev environment - Seed email domain correction (.com → .ma) - Docs: create-account guide, fleet page, signup plan - Various UI component and layout refinements
This commit is contained in:
+35
-2
@@ -1,5 +1,5 @@
|
||||
import express from 'express'
|
||||
import cors from 'cors'
|
||||
import cors, { type CorsOptions } from 'cors'
|
||||
import helmet from 'helmet'
|
||||
import morgan from 'morgan'
|
||||
import swaggerUi from 'swagger-ui-express'
|
||||
@@ -12,6 +12,7 @@ import { requestIdMiddleware } from './middleware/requestId'
|
||||
import webhookRouter from './modules/webhooks/webhook.routes'
|
||||
import companyAuthRouter from './modules/auth/auth.company.routes'
|
||||
import employeeAuthRouter from './modules/auth/auth.employee.routes'
|
||||
import accountAuthRouter from './modules/auth/auth.account.routes'
|
||||
import renterAuthRouter from './modules/auth/auth.renter.routes'
|
||||
import teamRouter from './modules/team/team.routes'
|
||||
import offersRouter from './modules/offers/offer.routes'
|
||||
@@ -40,8 +41,12 @@ const v1 = '/api/v1'
|
||||
|
||||
const defaultCorsOrigins = [
|
||||
'http://localhost:3000',
|
||||
'http://localhost:3001',
|
||||
'http://localhost:3002',
|
||||
'http://localhost:4000',
|
||||
'http://127.0.0.1:3000',
|
||||
'http://127.0.0.1:3001',
|
||||
'http://127.0.0.1:3002',
|
||||
'http://127.0.0.1:4000',
|
||||
]
|
||||
|
||||
@@ -49,6 +54,33 @@ export const corsOrigins = process.env.CORS_ORIGINS
|
||||
? process.env.CORS_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean)
|
||||
: defaultCorsOrigins
|
||||
|
||||
function isAllowedLocalDevOrigin(origin: string) {
|
||||
if (process.env.NODE_ENV === 'production') return false
|
||||
|
||||
try {
|
||||
const url = new URL(origin)
|
||||
return (
|
||||
url.protocol === 'http:' &&
|
||||
['localhost', '127.0.0.1'].includes(url.hostname) &&
|
||||
['3000', '3001', '3002', '4000'].includes(url.port)
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function isCorsOriginAllowed(origin: string | undefined) {
|
||||
if (!origin) return true
|
||||
return corsOrigins.includes(origin) || isAllowedLocalDevOrigin(origin)
|
||||
}
|
||||
|
||||
export const corsOptions: CorsOptions = {
|
||||
origin(origin, callback) {
|
||||
callback(null, isCorsOriginAllowed(origin))
|
||||
},
|
||||
credentials: true,
|
||||
}
|
||||
|
||||
const routeDocs = [
|
||||
{ method: 'GET', path: '/health', description: 'Health check' },
|
||||
{ method: 'GET', path: `${v1}/docs`, description: 'Machine-readable API index' },
|
||||
@@ -74,7 +106,7 @@ const routeDocs = [
|
||||
|
||||
export function createApp() {
|
||||
const app = express()
|
||||
const corsMiddleware = cors({ origin: corsOrigins, credentials: true })
|
||||
const corsMiddleware = cors(corsOptions)
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
app.set('trust proxy', 1)
|
||||
@@ -147,6 +179,7 @@ export function createApp() {
|
||||
app.use(express.json({ limit: '10mb' }))
|
||||
|
||||
// ─── API Routes ─────────────────────────────────────────────
|
||||
app.use(`${v1}/auth/account`, authLimiter, accountAuthRouter)
|
||||
app.use(`${v1}/auth/renter`, authLimiter, renterAuthRouter)
|
||||
app.use(`${v1}/auth/company`, authLimiter, companyAuthRouter)
|
||||
app.use(`${v1}/auth/employee`, authLimiter, employeeAuthRouter)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Router } from 'express'
|
||||
import { parseBody } from '../../http/validate'
|
||||
import { created } from '../../http/respond'
|
||||
import { setSessionCookie } from '../../security/sessionCookies'
|
||||
import { accountStartSchema } from './auth.account.schemas'
|
||||
import * as service from './auth.account.service'
|
||||
|
||||
const router = Router()
|
||||
|
||||
/**
|
||||
* POST /api/v1/auth/account/start
|
||||
*
|
||||
* Minimal signup — Step 0 of progressive profiling.
|
||||
* Creates a DRAFT company + OWNER employee and returns a JWT session.
|
||||
* See progressive-signup-plan.md Section 3.
|
||||
*/
|
||||
router.post('/start', async (req, res, next) => {
|
||||
try {
|
||||
const body = parseBody(accountStartSchema, req)
|
||||
const result = await service.startAccount(body)
|
||||
if ('token' in result) setSessionCookie(res, 'employee', result.token, 8 * 60 * 60 * 1000)
|
||||
created(res, result)
|
||||
} catch (err) { next(err) }
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Minimal signup schema — only asks for what's needed to create an identity.
|
||||
* See progressive-signup-plan.md Section 3.
|
||||
*/
|
||||
export const accountStartSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8).max(128),
|
||||
preferredLanguage: z.enum(['en', 'fr', 'ar']).default('en'),
|
||||
})
|
||||
|
||||
export const companyProfileSchema = z.object({
|
||||
firstName: z.string().min(1).max(80).optional(),
|
||||
lastName: z.string().min(1).max(80).optional(),
|
||||
firstNameAr: z.string().max(80).optional(),
|
||||
lastNameAr: z.string().max(80).optional(),
|
||||
companyName: z.string().min(2).max(120).optional(),
|
||||
companyNameAr: z.string().max(120).optional(),
|
||||
phone: z.string().min(1).max(80).optional(),
|
||||
companyEmail: z.string().email().optional(),
|
||||
streetAddress: z.string().min(1).max(200).optional(),
|
||||
streetAddressAr: z.string().max(200).optional(),
|
||||
city: z.string().min(1).max(120).optional(),
|
||||
cityAr: z.string().max(120).optional(),
|
||||
country: z.string().min(1).max(120).optional(),
|
||||
countryAr: z.string().max(120).optional(),
|
||||
zipCode: z.string().min(1).max(40).optional(),
|
||||
fax: z.string().max(80).optional(),
|
||||
yearsActive: z.string().max(80).optional(),
|
||||
})
|
||||
|
||||
export const legalIdentitySchema = z.object({
|
||||
legalName: z.string().min(2).max(160),
|
||||
legalForm: z.string().min(1).max(80),
|
||||
registrationNumber: z.string().min(1).max(120),
|
||||
iceNumber: z.string().min(1).max(120),
|
||||
taxId: z.string().min(1).max(120),
|
||||
operatingLicenseNumber: z.string().min(1).max(120),
|
||||
operatingLicenseIssuedAt: z.string().min(1).max(40),
|
||||
operatingLicenseIssuedBy: z.string().min(1).max(160),
|
||||
})
|
||||
|
||||
export const paymentSetupSchema = z.object({
|
||||
paymentProvider: z.enum(['AMANPAY', 'PAYPAL']),
|
||||
responsibleName: z.string().min(1).max(160),
|
||||
responsibleRole: z.string().min(1).max(120),
|
||||
responsibleIdentityNumber: z.string().min(1).max(120),
|
||||
responsibleQualification: z.string().max(200).optional(),
|
||||
responsiblePhone: z.string().min(1).max(80),
|
||||
responsibleEmail: z.string().email(),
|
||||
representativeName: z.string().max(160).optional(),
|
||||
representativeTitle: z.string().max(120).optional(),
|
||||
})
|
||||
|
||||
export const planSchema = z.object({
|
||||
plan: z.enum(['STARTER', 'GROWTH', 'PRO']),
|
||||
billingPeriod: z.enum(['MONTHLY', 'ANNUAL']),
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { AppError } from '../../http/errors'
|
||||
import { prisma } from '../../lib/prisma'
|
||||
import { signActorToken } from '../../security/tokens'
|
||||
import { presentEmployeeSession } from './auth.presenter'
|
||||
import * as repo from './auth.company.repo'
|
||||
import type { output } from 'zod'
|
||||
import type { accountStartSchema } from './auth.account.schemas'
|
||||
|
||||
type AccountStartInput = output<typeof accountStartSchema>
|
||||
|
||||
/**
|
||||
* Minimal account creation — Step 0 of progressive signup.
|
||||
* Creates a DRAFT company + OWNER employee, logs the user in immediately.
|
||||
*/
|
||||
export async function startAccount(body: AccountStartInput) {
|
||||
if (await repo.findEmployeeByEmail(body.email)) {
|
||||
throw new AppError('An account with this email already exists', 409, 'email_taken')
|
||||
}
|
||||
|
||||
const slug = `company-${Date.now().toString(36)}`
|
||||
const passwordHash = await bcrypt.hash(body.password, 12)
|
||||
|
||||
const result = await prisma.$transaction(async (tx: any) => {
|
||||
const now = new Date()
|
||||
const trialEndAt = new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000)
|
||||
|
||||
const company = await tx.company.create({
|
||||
data: {
|
||||
name: '',
|
||||
slug,
|
||||
email: body.email,
|
||||
address: {},
|
||||
status: 'TRIALING',
|
||||
},
|
||||
})
|
||||
|
||||
await tx.brandSettings.create({
|
||||
data: {
|
||||
companyId: company.id,
|
||||
displayName: body.email.split('@')[0] || 'My Workspace',
|
||||
subdomain: slug,
|
||||
defaultLocale: body.preferredLanguage,
|
||||
defaultCurrency: 'MAD',
|
||||
},
|
||||
})
|
||||
|
||||
await tx.subscription.create({
|
||||
data: {
|
||||
companyId: company.id,
|
||||
plan: 'STARTER',
|
||||
billingPeriod: 'MONTHLY',
|
||||
currency: 'MAD',
|
||||
status: 'TRIALING',
|
||||
trialStartAt: now,
|
||||
trialEndAt,
|
||||
currentPeriodStart: now,
|
||||
currentPeriodEnd: trialEndAt,
|
||||
},
|
||||
})
|
||||
|
||||
const employee = await tx.employee.create({
|
||||
data: {
|
||||
companyId: company.id,
|
||||
clerkUserId: `local_owner_${company.id}`,
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: body.email,
|
||||
passwordHash,
|
||||
role: 'OWNER',
|
||||
preferredLanguage: body.preferredLanguage,
|
||||
isActive: true,
|
||||
},
|
||||
include: { company: true },
|
||||
})
|
||||
|
||||
return employee
|
||||
})
|
||||
|
||||
const token = signActorToken(result.id, 'employee', {
|
||||
expiresIn: (process.env.JWT_EXPIRY ?? '8h') as any,
|
||||
})
|
||||
|
||||
return { token, ...presentEmployeeSession(result as any, token) }
|
||||
}
|
||||
@@ -75,6 +75,18 @@ describe('API foundation integration', () => {
|
||||
expect(res.body.paths).toHaveProperty('/health')
|
||||
})
|
||||
|
||||
it('allows dashboard credentialed preflights to employee auth routes', async () => {
|
||||
const res = await request(app)
|
||||
.options('/api/v1/auth/employee/menu')
|
||||
.set('Origin', 'http://localhost:3001')
|
||||
.set('Access-Control-Request-Method', 'GET')
|
||||
.set('Access-Control-Request-Headers', 'content-type')
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(res.headers['access-control-allow-origin']).toBe('http://localhost:3001')
|
||||
expect(res.headers['access-control-allow-credentials']).toBe('true')
|
||||
})
|
||||
|
||||
it('blocks legacy anonymous access to customer identity document storage paths', async () => {
|
||||
const res = await request(app).get('/storage/companies/company_1/customers/customer_1/passport.jpg')
|
||||
|
||||
|
||||
Reference in New Issue
Block a user