feat: basic initial UI layout for mobile and desktop
This commit is contained in:
63
apps/api/src/auth.ts
Normal file
63
apps/api/src/auth.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { passkey } from '@better-auth/passkey'
|
||||
import { organization } from 'better-auth/plugins/organization'
|
||||
import { prisma } from './db'
|
||||
import { emailProvider } from './lib/email'
|
||||
|
||||
export const auth = betterAuth({
|
||||
appName: 'Gruperly',
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: 'postgresql',
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await emailProvider.sendPasswordResetEmail({
|
||||
email: user.email,
|
||||
url,
|
||||
name: user.name,
|
||||
})
|
||||
},
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: true,
|
||||
sendOnSignIn: true,
|
||||
autoSignInAfterVerification: true,
|
||||
sendVerificationEmail: async ({ user, token }) => {
|
||||
const webUrl = process.env.WEB_URL ?? 'http://localhost:6173'
|
||||
const verificationUrl = new URL('/verify-email', webUrl)
|
||||
verificationUrl.searchParams.set('token', token)
|
||||
await emailProvider.sendVerificationEmail({
|
||||
email: user.email,
|
||||
url: verificationUrl.toString(),
|
||||
name: user.name,
|
||||
})
|
||||
},
|
||||
},
|
||||
socialProviders: {
|
||||
...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
|
||||
? {
|
||||
google: {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
plugins: [
|
||||
organization({
|
||||
acronym: 'GRP',
|
||||
allowUserToCreateOrganization: true,
|
||||
organizationLimit: 10,
|
||||
}),
|
||||
passkey({
|
||||
rpName: 'Gruperly',
|
||||
}),
|
||||
],
|
||||
trustedOrigins: [
|
||||
process.env.BETTER_AUTH_URL ?? 'http://localhost:4000',
|
||||
process.env.WEB_URL ?? 'http://localhost:6173',
|
||||
],
|
||||
})
|
||||
10
apps/api/src/env.ts
Normal file
10
apps/api/src/env.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import type { auth } from './auth'
|
||||
|
||||
type Session = typeof auth.$Infer.Session
|
||||
|
||||
export type AppEnv = {
|
||||
Variables: {
|
||||
user: Session['user'] | null
|
||||
session: Session['session'] | null
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,50 @@
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { authRoutes } from './routes/auth'
|
||||
import { groupsRoutes } from './routes/groups'
|
||||
import { studentsRoutes } from './routes/students'
|
||||
import { paymentsRoutes } from './routes/payments'
|
||||
import { waitlistRoutes } from './routes/waitlist'
|
||||
import { auth } from './auth'
|
||||
import type { AppEnv } from './env'
|
||||
import { listGroups, createGroupFromOrganization } from './routes/groups'
|
||||
import { listPlaceholder as students } from './routes/students'
|
||||
import { listPlaceholder as payments } from './routes/payments'
|
||||
import { listPlaceholder as waitlist } from './routes/waitlist'
|
||||
|
||||
const app = new Hono()
|
||||
const app = new Hono<AppEnv>()
|
||||
|
||||
app.use('*', cors())
|
||||
const webOrigin = process.env.WEB_URL ?? 'http://localhost:6173'
|
||||
|
||||
app.use(
|
||||
'*',
|
||||
cors({
|
||||
origin: [webOrigin],
|
||||
credentials: true,
|
||||
allowHeaders: ['Content-Type', 'Authorization'],
|
||||
maxAge: 600,
|
||||
}),
|
||||
)
|
||||
|
||||
// BetterAuth endpoints (sign-up, sign-in, session, org, passkeys, ...)
|
||||
app.all('/api/auth', (c) => auth.handler(c.req.raw))
|
||||
app.all('/api/auth/*', (c) => auth.handler(c.req.raw))
|
||||
|
||||
// Sesión disponible en todos los handlers vía c.get('user') / c.get('session')
|
||||
app.use('*', async (c, next) => {
|
||||
const session = await auth.api.getSession({ headers: c.req.raw.headers })
|
||||
if (session) {
|
||||
c.set('user', session.user)
|
||||
c.set('session', session.session)
|
||||
} else {
|
||||
c.set('user', null)
|
||||
c.set('session', null)
|
||||
}
|
||||
await next()
|
||||
})
|
||||
|
||||
app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }))
|
||||
|
||||
app.route('/auth', authRoutes)
|
||||
app.route('/groups', groupsRoutes)
|
||||
app.route('/students', studentsRoutes)
|
||||
app.route('/payments', paymentsRoutes)
|
||||
app.route('/waitlist', waitlistRoutes)
|
||||
app.get('/api/groups', listGroups)
|
||||
app.post('/api/groups/from-organization', createGroupFromOrganization)
|
||||
app.get('/api/students', students)
|
||||
app.get('/api/payments', payments)
|
||||
app.get('/api/waitlist', waitlist)
|
||||
|
||||
export default app
|
||||
|
||||
@@ -27,4 +55,4 @@ Bun.serve({
|
||||
fetch: app.fetch,
|
||||
})
|
||||
|
||||
console.log(`Gruperly API running on http://localhost:${port}`)
|
||||
console.log(`Gruperly API running on http://localhost:${port}`)
|
||||
94
apps/api/src/lib/email.ts
Normal file
94
apps/api/src/lib/email.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import nodemailer, { type Transporter } from 'nodemailer'
|
||||
|
||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: string }
|
||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||
|
||||
interface EmailProvider {
|
||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
|
||||
sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
|
||||
}
|
||||
|
||||
class SMTPEmailProvider implements EmailProvider {
|
||||
private transporter: Transporter
|
||||
|
||||
constructor() {
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: process.env.EMAIL_SERVER_HOST,
|
||||
port: Number(process.env.EMAIL_SERVER_PORT ?? 587),
|
||||
secure: (process.env.EMAIL_SERVER_PORT ?? '587') === '465',
|
||||
auth: {
|
||||
user: process.env.EMAIL_SERVER_USER,
|
||||
pass: process.env.EMAIL_SERVER_PASSWORD,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
private from() {
|
||||
return process.env.EMAIL_FROM ?? 'Gruperly <no-reply@gruperly.com>'
|
||||
}
|
||||
|
||||
private layout(title: string, body: string) {
|
||||
return `
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px; color: #0a2540;">
|
||||
<h2 style="margin: 0 0 16px;">Gruperly</h2>
|
||||
<h3 style="margin: 0 0 8px;">${title}</h3>
|
||||
<p style="line-height: 1.6; color: #334155;">${body}</p>
|
||||
</div>
|
||||
`
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
}
|
||||
await this.transporter.sendMail({ from: this.from(), to, subject, html })
|
||||
}
|
||||
|
||||
async sendVerificationEmail({ email, url, name }: VerificationEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Verificar email</a>`
|
||||
await this.send(
|
||||
email,
|
||||
'Verifica tu email en Gruperly',
|
||||
this.layout(
|
||||
'Confirma tu dirección de email',
|
||||
`${name ? `Hola ${name}, ` : 'Hola, '}gracias por crear tu cuenta en Gruperly. Para empezar, verifica tu email con el botón de abajo (el enlace vence en 1 hora).<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Restablecer contraseña</a>`
|
||||
await this.send(
|
||||
email,
|
||||
'Restablece tu contraseña en Gruperly',
|
||||
this.layout(
|
||||
'Solicitaste restablecer tu contraseña',
|
||||
`${name ? `Hola ${name}, ` : 'Hola, '}haz clic en el botón para elegir una nueva contraseña (el enlace vence en 1 hora). Si no fuiste tú, ignora este email.<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) {
|
||||
const link = `<a href="${url}" style="display:inline-block;background:#1e90ff;color:#fff;text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">Unirme a ${organizationName}</a>`
|
||||
await this.send(
|
||||
email,
|
||||
`Te invitaron a ${organizationName} en Gruperly`,
|
||||
this.layout(
|
||||
`Te invitaron a ${organizationName}`,
|
||||
`Acepta la invitación con el botón de abajo para empezar a colaborar en Gruperly.<br/><br/>${link}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
export const emailProvider = createEmailProvider()
|
||||
@@ -1,5 +0,0 @@
|
||||
import { Hono } from 'hono'
|
||||
|
||||
export const authRoutes = new Hono()
|
||||
|
||||
authRoutes.get('/session', (c) => c.json({ message: 'placeholder' }))
|
||||
@@ -1,5 +1,65 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { prisma } from '../db/client'
|
||||
import type { AppEnv } from '../env'
|
||||
import { Role } from '../../prisma/generated/prisma/client'
|
||||
|
||||
export const groupsRoutes = new Hono()
|
||||
const fromOrganizationSchema = z.object({
|
||||
organizationId: z.string().min(1),
|
||||
})
|
||||
|
||||
groupsRoutes.get('/', (c) => c.json([]))
|
||||
export async function listGroups(c: Context<AppEnv>) {
|
||||
const user = c.get('user')
|
||||
if (!user) return c.json({ message: 'No autorizado' }, 401)
|
||||
|
||||
void user
|
||||
return c.json([])
|
||||
}
|
||||
|
||||
// Crea un Group a partir de una Organization de Better Auth (mapeo 1:1).
|
||||
// Solo el owner de la organización puede crear su grupo.
|
||||
export async function createGroupFromOrganization(c: Context<AppEnv>) {
|
||||
const user = c.get('user')
|
||||
if (!user) return c.json({ message: 'No autorizado' }, 401)
|
||||
|
||||
const body = await c.req.json().catch(() => null)
|
||||
const parsed = fromOrganizationSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ message: 'Cuerpo inválido', issues: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
const organization = await prisma.organization.findUnique({
|
||||
where: { id: parsed.data.organizationId },
|
||||
include: { members: true },
|
||||
})
|
||||
if (!organization) return c.json({ message: 'Organización no encontrada' }, 404)
|
||||
|
||||
const membership = organization.members.find((m) => m.userId === user.id)
|
||||
if (!membership || membership.role !== 'owner') {
|
||||
return c.json({ message: 'Solo el owner puede crear el grupo' }, 403)
|
||||
}
|
||||
|
||||
const existing = await prisma.group.findFirst({
|
||||
where: { createdById: user.id, name: organization.name },
|
||||
})
|
||||
if (existing) return c.json({ group: existing, alreadyExists: true })
|
||||
|
||||
const group = await prisma.$transaction(async (tx) => {
|
||||
const created = await tx.group.create({
|
||||
data: {
|
||||
name: organization.name,
|
||||
createdById: user.id,
|
||||
},
|
||||
})
|
||||
await tx.groupMember.create({
|
||||
data: {
|
||||
groupId: created.id,
|
||||
userId: user.id,
|
||||
role: Role.OWNER,
|
||||
},
|
||||
})
|
||||
return created
|
||||
})
|
||||
|
||||
return c.json({ group }, 201)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
|
||||
export const paymentsRoutes = new Hono()
|
||||
|
||||
paymentsRoutes.get('/', (c) => c.json([]))
|
||||
export function listPlaceholder(c: Context) {
|
||||
return c.json([])
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
|
||||
export const studentsRoutes = new Hono()
|
||||
|
||||
studentsRoutes.get('/', (c) => c.json([]))
|
||||
export function listPlaceholder(c: Context) {
|
||||
return c.json([])
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
|
||||
export const waitlistRoutes = new Hono()
|
||||
|
||||
waitlistRoutes.get('/', (c) => c.json([]))
|
||||
export function listPlaceholder(c: Context) {
|
||||
return c.json([])
|
||||
}
|
||||
Reference in New Issue
Block a user