diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 088c8ed7..9ab86aef 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -28,9 +28,12 @@ model User { } model LoginToken { - id String @id @default(uuid()) - email String - expiresAt DateTime + id String @id @default(uuid()) + email String + expiresAt DateTime + // When the login token is creating by submitting the `subscribe` form + // We store extra info here, like `{email: true,telegram: true}` + subscribeForm Json? @@map("login_tokens") } diff --git a/src/components/common/SubscribeModal.tsx b/src/components/common/SubscribeModal.tsx index 1f9044ff..3f861a97 100644 --- a/src/components/common/SubscribeModal.tsx +++ b/src/components/common/SubscribeModal.tsx @@ -1,10 +1,12 @@ -import React from "react" +import React, { useEffect } from "react" import { useFormik } from "formik" import { useStore } from "~/lib/store" import { Badge } from "../ui/Badge" import { Button } from "../ui/Button" import { Modal } from "../ui/Modal" import toast from "react-hot-toast" +import { trpc } from "~/lib/trpc" +import { Input } from "../ui/Input" export const SubscribeModal: React.FC<{ siteId: string @@ -12,70 +14,117 @@ export const SubscribeModal: React.FC<{ telegram?: boolean email?: boolean } | null -}> = ({ siteId, subscription }) => { + isLoggedIn: boolean +}> = ({ siteId, subscription, isLoggedIn }) => { const [open, setOpen] = useStore((store) => [ store.subscribeModalOpened, store.setSubscribeModalOpened, ]) + const subscribe = trpc.useMutation("site.subscribe") + const unsubscribe = trpc.useMutation("site.unsubscribe") + const trpcContext = trpc.useContext() const subscribeForm = useFormik({ initialValues: { - email: true, - telegram: false, + newUserEmail: "", + email: subscription?.email ?? true, + telegram: subscription?.telegram ?? false, }, onSubmit(values) { - toast.success("not implemented") + subscribe.mutate({ + siteId, + email: values.email, + telegram: values.telegram, + newUser: isLoggedIn + ? undefined + : { + email: values.newUserEmail, + url: location.href, + }, + }) }, }) - const unsubscribeForm = useFormik({ initialValues: {}, onSubmit() {} }) + useEffect(() => { + if (subscribe.isSuccess && isLoggedIn) { + subscribe.reset() + toast.success(subscription ? "Updated!" : "Subscribed!") + trpcContext.invalidateQueries("site.subscription") + } + }, [subscribe, isLoggedIn, subscription]) + + useEffect(() => { + if (unsubscribe.isSuccess) { + unsubscribe.reset() + toast.success("Unsubscribed!") + trpcContext.invalidateQueries("site.subscription") + } + }, [unsubscribe]) return ( -
-
- + {subscribe.isSuccess && !isLoggedIn ? ( +
+

+ We have sent you an email with a link to confirm your subscription. +

+

Please check your inbox (and spam folder).

-
- -
-
- - {subscription && ( - + ) : ( + + {!isLoggedIn && ( +
+ +
+ )} +
+ +
+
+ +
+
+ + {subscription && ( - - )} -
- + )} +
+ + )} ) } diff --git a/src/components/site/SiteLayout.tsx b/src/components/site/SiteLayout.tsx index 0d8bca47..82d29431 100644 --- a/src/components/site/SiteLayout.tsx +++ b/src/components/site/SiteLayout.tsx @@ -31,6 +31,10 @@ const Header: React.FC<{ (store) => store.setSubscribeModalOpened ) const router = useRouter() + const handleClickSubscribe = () => { + setSubscribeModalOpened(true) + } + return (
@@ -47,7 +51,7 @@ const Header: React.FC<{ rounded="full" size="sm" variant={subscribed ? "secondary" : "primary"} - onClick={() => setSubscribeModalOpened(true)} + onClick={handleClickSubscribe} > {subscribed ? ( @@ -184,7 +188,11 @@ export const SiteLayout: React.FC = ({
{site.id && ( - + )} ) diff --git a/src/controllers/site.controller.ts b/src/controllers/site.controller.ts deleted file mode 100644 index 3763ef2f..00000000 --- a/src/controllers/site.controller.ts +++ /dev/null @@ -1,313 +0,0 @@ -import { prisma } from "~/lib/db.server" -import { - checkPageSlug, - checkSubdomain, - getSite, - getSitesByUser, -} from "~/models/site.model" -import { PageVisibilityEnum } from "~/lib/types" -import { isUUID } from "~/lib/uuid" -import { MembershipRole, PageType, type Prisma } from "@prisma/client" -import { nanoid } from "nanoid" -import { Gate } from "~/lib/gate.server" -import { notFound } from "~/lib/server-side-props" -import { renderPageContent } from "~/lib/markdown.server" - -export const siteController = { - async getSites(gate: Gate) { - const user = gate.getUser(true) - const sites = await getSitesByUser({ userId: user.id }) - return sites - }, - - async getSite(siteIdOrSubdomainOrDomain: string) { - const site = await getSite(siteIdOrSubdomainOrDomain) - return { site } - }, - - async getPages( - gate: Gate, - input: { - site: string - type: "post" | "page" - visibility?: PageVisibilityEnum | null - take?: number | null - cursor?: string | null - } - ) { - const site = await getSite(input.site) - - const visibility = input.visibility || PageVisibilityEnum.Published - - if (!gate.allows({ type: "can-list-page", visibility, siteId: site.id })) { - throw gate.permissionError() - } - - const now = new Date() - - const where: Prisma.PageWhereInput = { - siteId: site.id, - deletedAt: null, - type: input.type === "post" ? "POST" : "PAGE", - } - if (input.visibility === PageVisibilityEnum.Published) { - where.published = true - where.publishedAt = { - lte: now, - } - } else if (input.visibility === PageVisibilityEnum.Scheduled) { - where.published = true - where.publishedAt = { - gt: now, - } - } else if (input.visibility === PageVisibilityEnum.Draft) { - where.published = false - } - - const take = input.take || 100 - const [nodes, total] = await Promise.all([ - prisma.page.findMany({ - where, - orderBy: { - createdAt: "desc", - }, - take: take + 1, - cursor: input.cursor - ? { - id: input.cursor, - } - : undefined, - }), - await prisma.page.count({ - where: { - siteId: site.id, - }, - }), - ]) - - const hasMore = nodes.length > take - - return { - nodes, - total, - hasMore, - } - }, - - async createOrUpdatePage( - gate: Gate, - input: { - pageId?: string - siteId: string - slug?: string - title?: string - content?: string - published?: boolean - publishedAt?: string - excerpt?: string - isPost?: boolean - } - ) { - const page = input.pageId - ? await prisma.page.findUnique({ - where: { - id: input.pageId, - }, - include: { - site: true, - }, - }) - : await prisma.page.create({ - data: { - title: "Untitled", - slug: `untitled-${nanoid(4)}`, - site: { - connect: { - id: input.siteId, - }, - }, - content: "", - excerpt: "", - }, - include: { - site: true, - }, - }) - - if (!page || page.deletedAt) { - throw new Error(`Page not found`) - } - - if (!gate.allows({ type: "can-create-page", siteId: page.siteId })) { - throw gate.permissionError() - } - - const slug = input.slug || page.slug - await checkPageSlug({ slug, excludePage: page.id, siteId: page.siteId }) - - const updated = await prisma.page.update({ - where: { - id: page.id, - }, - data: { - title: input.title, - content: input.content, - published: input.published, - publishedAt: input.publishedAt && new Date(input.publishedAt), - excerpt: input.excerpt, - slug, - type: input.isPost ? "POST" : "PAGE", - }, - }) - return { page: updated } - }, - - async deletePage(gate: Gate, { id }: { id: string }) { - const page = await prisma.page.findUnique({ - where: { - id, - }, - }) - - if (!page) { - throw notFound("page not found") - } - - if (!gate.allows({ type: "can-delete-page", siteId: page.siteId })) { - throw gate.permissionError() - } - - await prisma.page.update({ - where: { - id: page.id, - }, - data: { - deletedAt: new Date(), - }, - }) - }, - - async getPage( - gate: Gate, - input: { - /** page slug or id, `site` is needed when `page` is a slug */ - page: string - site: string - renderContent?: boolean - } - ) { - const site = input.site ? await getSite(input.site) : null - - if (input.site && !site) { - throw notFound(`site not found`) - } - - const isPageUUID = isUUID(input.page) - if (!isPageUUID && !input.site) { - throw new Error("missing input site") - } - - const page = isPageUUID - ? await prisma.page.findUnique({ - where: { - id: input.page, - }, - }) - : site - ? await prisma.page.findFirst({ - where: { siteId: site.id, slug: input.page }, - }) - : null - - if (!page || page.deletedAt) { - throw notFound(`page ${input.page} not found`) - } - - if (!gate.allows({ type: "can-read-page", page })) { - throw gate.permissionError() - } - - if (input.renderContent) { - const rendered = await renderPageContent(page.content) - page.content = rendered.html - } - - return page - }, - - async updateSite( - gate: Gate, - payload: { - site: string - name?: string - description?: string - icon?: string | null - subdomain?: string - } - ) { - const site = await getSite(payload.site) - - if (!gate.allows({ type: "can-update-site", site })) { - throw gate.permissionError() - } - - if (payload.subdomain) { - await checkSubdomain({ - subdomain: payload.subdomain, - updatingSiteId: site.id, - }) - } - - const updated = await prisma.site.update({ - where: { - id: site.id, - }, - data: { - name: payload.name, - subdomain: payload.subdomain, - description: payload.description, - icon: payload.icon, - }, - }) - - return { - site: updated, - subdomainUpdated: updated.subdomain !== site.subdomain, - } - }, - - async createSite(gate: Gate, payload: { name: string; subdomain: string }) { - const user = gate.getUser(true) - await checkSubdomain({ subdomain: payload.subdomain }) - - const site = await prisma.site.create({ - data: { - name: payload.name, - subdomain: payload.subdomain, - memberships: { - create: { - role: MembershipRole.OWNER, - user: { - connect: { - id: user.id, - }, - }, - }, - }, - pages: { - create: { - title: "About", - slug: "about", - excerpt: "", - content: `My name is ${payload.name} and I'm a new site.`, - published: true, - publishedAt: new Date(), - type: PageType.PAGE, - }, - }, - }, - }) - - return { site } - }, -} diff --git a/src/lib/db.server.ts b/src/lib/db.server.ts index 1659178a..d3f15b86 100644 --- a/src/lib/db.server.ts +++ b/src/lib/db.server.ts @@ -23,3 +23,5 @@ export const prisma = /* @__PURE__ */ singleton("prisma-read", () => { return client }) + +export type { Prisma } diff --git a/src/lib/mailgun.server.ts b/src/lib/mailgun.server.ts index 60889a55..c3679656 100644 --- a/src/lib/mailgun.server.ts +++ b/src/lib/mailgun.server.ts @@ -5,6 +5,8 @@ import { MAILGUN_APIKEY, MAILGUN_DOMAIN, MAILGUN_EU } from "~/lib/env.server" import type { MailgunMessageData } from "mailgun.js/interfaces/Messages" import { IS_PROD } from "./constants" import { APP_NAME, OUR_DOMAIN } from "./env" +import { SubscribeFormData } from "./types" +import { getSite } from "~/models/site.model" const getClient = () => singleton("mailgun", () => { @@ -17,17 +19,49 @@ const getClient = () => return client }) -export const sendLoginEmail = async (loginLink: string, email: string) => { +export const sendLoginEmail = async (payload: { + token: string + email: string + url: string + subscribeForm?: SubscribeFormData +}) => { + const { protocol, host, pathname } = new URL(payload.url) + const query = new URLSearchParams([ + ["token", payload.token], + ["next", `${protocol}//${host}${pathname}`], + ]) + if (payload.subscribeForm) { + query.append("subscribe", JSON.stringify(payload.subscribeForm)) + } + const loginLink = `${ + IS_PROD ? "https" : "http" + }://${OUR_DOMAIN}/api/login?${query.toString()}` + + let subject = `Log in to ${APP_NAME}` + + let html = `

Please use the link below to log in to ${APP_NAME}:

+ + login + +

This link will expire in 10 minutes.

+ ` + + if (payload.subscribeForm) { + const site = await getSite(payload.subscribeForm.siteId) + subject = `Confirm your subscription to ${site.name}` + html = ` +

Please confirm your subscription to ${site.name} by clicking the link below:

+ + confirm + +

This link will expire in 10 minutes.

` + } + const message: MailgunMessageData = { from: `${APP_NAME} `, - to: email, - subject: `Log in to ${APP_NAME}`, - html: `

Please use the link below to log in to ${APP_NAME}:

- -login - -

This link will expire in 10 minutes.

-`, + to: payload.email, + subject, + html, } console.log(message) diff --git a/src/lib/types.ts b/src/lib/types.ts index ace68593..a37bb08a 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -55,3 +55,12 @@ export type PostOnArchivesPage = { slug: string publishedAt: string | Date } + +/** + * The subscribe form data to store in loginToken + */ +export type SubscribeFormData = { + email?: boolean + telegram?: boolean + siteId: string +} diff --git a/src/models/page.model.ts b/src/models/page.model.ts new file mode 100644 index 00000000..678b8a59 --- /dev/null +++ b/src/models/page.model.ts @@ -0,0 +1,253 @@ +import { nanoid } from "nanoid" +import { prisma, Prisma } from "~/lib/db.server" +import { type Gate } from "~/lib/gate.server" +import { renderPageContent } from "~/lib/markdown.server" +import { notFound } from "~/lib/server-side-props" +import { PageVisibilityEnum } from "~/lib/types" +import { isUUID } from "~/lib/uuid" +import { getSite } from "./site.model" + +const checkPageSlug = async ({ + slug, + excludePage, + siteId, +}: { + slug: string + excludePage?: string + siteId: string +}) => { + if (!slug) { + throw new Error("Missing page slug") + } + const page = await prisma.page.findFirst({ + where: { + siteId, + slug, + id: excludePage && { + not: excludePage, + }, + }, + }) + if (!page) return + + if (page.deletedAt) { + await prisma.page.delete({ + where: { + id: page.id, + }, + }) + return + } + + throw new Error("Page slug already used") +} + +export async function createOrUpdatePage( + gate: Gate, + input: { + pageId?: string + siteId: string + slug?: string + title?: string + content?: string + published?: boolean + publishedAt?: string + excerpt?: string + isPost?: boolean + } +) { + const page = input.pageId + ? await prisma.page.findUnique({ + where: { + id: input.pageId, + }, + include: { + site: true, + }, + }) + : await prisma.page.create({ + data: { + title: "Untitled", + slug: `untitled-${nanoid(4)}`, + site: { + connect: { + id: input.siteId, + }, + }, + content: "", + excerpt: "", + }, + include: { + site: true, + }, + }) + + if (!page || page.deletedAt) { + throw new Error(`Page not found`) + } + + if (!gate.allows({ type: "can-create-page", siteId: page.siteId })) { + throw gate.permissionError() + } + + const slug = input.slug || page.slug + await checkPageSlug({ slug, excludePage: page.id, siteId: page.siteId }) + + const updated = await prisma.page.update({ + where: { + id: page.id, + }, + data: { + title: input.title, + content: input.content, + published: input.published, + publishedAt: input.publishedAt && new Date(input.publishedAt), + excerpt: input.excerpt, + slug, + type: input.isPost ? "POST" : "PAGE", + }, + }) + return { page: updated } +} + +export async function getPagesBySite( + gate: Gate, + input: { + site: string + type: "post" | "page" + visibility?: PageVisibilityEnum | null + take?: number | null + cursor?: string | null + } +) { + const site = await getSite(input.site) + + const visibility = input.visibility || PageVisibilityEnum.Published + + if (!gate.allows({ type: "can-list-page", visibility, siteId: site.id })) { + throw gate.permissionError() + } + + const now = new Date() + + const where: Prisma.PageWhereInput = { + siteId: site.id, + deletedAt: null, + type: input.type === "post" ? "POST" : "PAGE", + } + if (input.visibility === PageVisibilityEnum.Published) { + where.published = true + where.publishedAt = { + lte: now, + } + } else if (input.visibility === PageVisibilityEnum.Scheduled) { + where.published = true + where.publishedAt = { + gt: now, + } + } else if (input.visibility === PageVisibilityEnum.Draft) { + where.published = false + } + + const take = input.take || 100 + const [nodes, total] = await Promise.all([ + prisma.page.findMany({ + where, + orderBy: { + createdAt: "desc", + }, + take: take + 1, + cursor: input.cursor + ? { + id: input.cursor, + } + : undefined, + }), + await prisma.page.count({ + where: { + siteId: site.id, + }, + }), + ]) + + const hasMore = nodes.length > take + + return { + nodes, + total, + hasMore, + } +} + +export async function deletePage(gate: Gate, { id }: { id: string }) { + const page = await prisma.page.findUnique({ + where: { + id, + }, + }) + + if (!page) { + throw notFound("page not found") + } + + if (!gate.allows({ type: "can-delete-page", siteId: page.siteId })) { + throw gate.permissionError() + } + + await prisma.page.update({ + where: { + id: page.id, + }, + data: { + deletedAt: new Date(), + }, + }) +} + +export async function getPage( + gate: Gate, + input: { + /** page slug or id, `site` is needed when `page` is a slug */ + page: string + site: string + renderContent?: boolean + } +) { + const site = input.site ? await getSite(input.site) : null + + if (input.site && !site) { + throw notFound(`site not found`) + } + + const isPageUUID = isUUID(input.page) + if (!isPageUUID && !input.site) { + throw new Error("missing input site") + } + + const page = isPageUUID + ? await prisma.page.findUnique({ + where: { + id: input.page, + }, + }) + : site + ? await prisma.page.findFirst({ + where: { siteId: site.id, slug: input.page }, + }) + : null + + if (!page || page.deletedAt) { + throw notFound(`page ${input.page} not found`) + } + + if (!gate.allows({ type: "can-read-page", page })) { + throw gate.permissionError() + } + + if (input.renderContent) { + const rendered = await renderPageContent(page.content) + page.content = rendered.html + } + + return page +} diff --git a/src/models/site.model.ts b/src/models/site.model.ts index 2d2a294c..72e99fbc 100644 --- a/src/models/site.model.ts +++ b/src/models/site.model.ts @@ -1,6 +1,10 @@ import { prisma } from "~/lib/db.server" import { isUUID } from "~/lib/uuid" -import { MembershipRole } from "@prisma/client" +import { MembershipRole, PageType } from "@prisma/client" +import { Gate } from "~/lib/gate.server" +import dayjs from "dayjs" +import { sendLoginEmail } from "~/lib/mailgun.server" +import { SubscribeFormData } from "~/lib/types" export const checkSubdomain = async ({ subdomain, @@ -30,6 +34,12 @@ export const checkSubdomain = async ({ } } +export async function getSitesForViewer(gate: Gate) { + const user = gate.getUser(true) + const sites = await getSitesByUser({ userId: user.id }) + return sites +} + export const getUserLastActiveSite = async (userId: string) => { const memberships = await prisma.membership.findMany({ where: { @@ -104,41 +114,6 @@ export const getSitesByUser = async ({ userId }: { userId: string }) => { return memberships.map((m) => m.site) } -export const checkPageSlug = async ({ - slug, - excludePage, - siteId, -}: { - slug: string - excludePage?: string - siteId: string -}) => { - if (!slug) { - throw new Error("Missing page slug") - } - const page = await prisma.page.findFirst({ - where: { - siteId, - slug, - id: excludePage && { - not: excludePage, - }, - }, - }) - if (!page) return - - if (page.deletedAt) { - await prisma.page.delete({ - where: { - id: page.id, - }, - }) - return - } - - throw new Error("Page slug already used") -} - export const getSubscription = async (data: { userId: string siteId: string @@ -147,11 +122,192 @@ export const getSubscription = async (data: { ...data, role: MembershipRole.SUBSCRIBER, }) - const config = membership?.config as any + if (!membership) return + const config = membership.config as any return { + ...membership, config: config && { telegram: config.telegram, email: config.email, }, } } + +export async function updateSite( + gate: Gate, + payload: { + site: string + name?: string + description?: string + icon?: string | null + subdomain?: string + } +) { + const site = await getSite(payload.site) + + if (!gate.allows({ type: "can-update-site", site })) { + throw gate.permissionError() + } + + if (payload.subdomain) { + await checkSubdomain({ + subdomain: payload.subdomain, + updatingSiteId: site.id, + }) + } + + const updated = await prisma.site.update({ + where: { + id: site.id, + }, + data: { + name: payload.name, + subdomain: payload.subdomain, + description: payload.description, + icon: payload.icon, + }, + }) + + return { + site: updated, + subdomainUpdated: updated.subdomain !== site.subdomain, + } +} + +export async function createSite( + gate: Gate, + payload: { name: string; subdomain: string } +) { + const user = gate.getUser(true) + await checkSubdomain({ subdomain: payload.subdomain }) + + const site = await prisma.site.create({ + data: { + name: payload.name, + subdomain: payload.subdomain, + memberships: { + create: { + role: MembershipRole.OWNER, + user: { + connect: { + id: user.id, + }, + }, + }, + }, + pages: { + create: { + title: "About", + slug: "about", + excerpt: "", + content: `My name is ${payload.name} and I'm a new site.`, + published: true, + publishedAt: new Date(), + type: PageType.PAGE, + }, + }, + }, + }) + + return { site } +} + +export async function subscribeToSite( + gate: Gate, + input: { + siteId: string + email?: boolean + telegram?: boolean + newUser?: { + email: string + url: string + } + } +) { + const { newUser } = input + if (newUser) { + // Create the login token instead + const subscribeFormData: SubscribeFormData = { + email: input.email, + telegram: input.telegram, + siteId: input.siteId, + } + const loginToken = await prisma.loginToken.create({ + data: { + email: newUser.email, + expiresAt: dayjs().add(10, "minutes").toDate(), + subscribeForm: subscribeFormData, + }, + }) + sendLoginEmail({ + token: loginToken.id, + email: loginToken.email, + url: newUser.url, + subscribeForm: subscribeFormData, + }) + return + } + + const user = gate.getUser(true) + + const site = await getSite(input.siteId) + const subscription = await getSubscription({ + userId: user.id, + siteId: site.id, + }) + if (!subscription) { + await prisma.membership.create({ + data: { + role: MembershipRole.SUBSCRIBER, + user: { + connect: { + id: user.id, + }, + }, + site: { + connect: { + id: site.id, + }, + }, + config: { + email: input.email, + telegram: input.telegram, + }, + }, + }) + } else { + await prisma.membership.update({ + where: { + id: subscription.id, + }, + data: { + config: { + email: input.email, + telegram: input.telegram, + }, + }, + }) + } +} + +export async function unsubscribeFromSite( + gate: Gate, + input: { siteId: string } +) { + const user = gate.getUser(true) + + const subscription = await getSubscription({ + userId: user.id, + siteId: input.siteId, + }) + + if (!subscription) { + throw new Error(`Subscription not found`) + } + + await prisma.membership.delete({ + where: { + id: subscription.id, + }, + }) +} diff --git a/src/pages/_site/[site]/[page].tsx b/src/pages/_site/[site]/[page].tsx index cf14b0a0..0052dfee 100644 --- a/src/pages/_site/[site]/[page].tsx +++ b/src/pages/_site/[site]/[page].tsx @@ -25,6 +25,7 @@ export const getServerSideProps: GetServerSideProps = serverSidePropsHandler( page: pageSlug, renderContent: true, }), + ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }), ]) return { diff --git a/src/pages/_site/[site]/archives.tsx b/src/pages/_site/[site]/archives.tsx index d902a620..1073d096 100644 --- a/src/pages/_site/[site]/archives.tsx +++ b/src/pages/_site/[site]/archives.tsx @@ -20,6 +20,7 @@ export const getServerSideProps: GetServerSideProps = serverSidePropsHandler( await Promise.all([ ssg.fetchQuery("site", { site: domainOrSubdomain }), ssg.fetchQuery("site.pages", { site: domainOrSubdomain, take: 1000 }), + ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }), ]) return { diff --git a/src/pages/_site/[site]/index.tsx b/src/pages/_site/[site]/index.tsx index 0e0159c9..be82d308 100644 --- a/src/pages/_site/[site]/index.tsx +++ b/src/pages/_site/[site]/index.tsx @@ -15,7 +15,10 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => { const trpcContext = await getTRPCContext(ctx) const ssg = createSSGHelpers({ router: appRouter, ctx: trpcContext }) - await Promise.all([ssg.fetchQuery("site", { site: domainOrSubdomain })]) + await Promise.all([ + ssg.fetchQuery("site", { site: domainOrSubdomain }), + ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }), + ]) return { props: { diff --git a/src/pages/api/login.ts b/src/pages/api/login.ts index b4c48d66..359f8528 100644 --- a/src/pages/api/login.ts +++ b/src/pages/api/login.ts @@ -7,6 +7,8 @@ import { generateCookie } from "~/lib/auth.server" import { OUR_DOMAIN } from "~/lib/env" import { IS_PROD } from "~/lib/constants" import { NextApiHandler } from "next" +import { subscribeToSite } from "~/models/site.model" +import { createGate } from "~/lib/gate.server" const handler: NextApiHandler = async (req, res) => { const data = z @@ -14,11 +16,20 @@ const handler: NextApiHandler = async (req, res) => { token: z.string(), next: z.string(), userAgent: z.string(), + subscribe: z + .object({ + siteId: z.string(), + email: z.boolean().optional(), + telegram: z.boolean().optional(), + }) + .optional(), }) .parse({ token: req.query.token, next: req.query.next, userAgent: req.headers["user-agent"], + subscribe: + req.query.subscribe && JSON.parse(req.query.subscribe as string), }) const loginToken = await prisma.loginToken.findUnique({ @@ -39,6 +50,9 @@ const handler: NextApiHandler = async (req, res) => { where: { email: loginToken.email, }, + include: { + memberships: true, + }, }) if (!user) { @@ -48,6 +62,19 @@ const handler: NextApiHandler = async (req, res) => { name: loginToken.email.split("@")[0], username: nanoid(7), }, + include: { + memberships: true, + }, + }) + } + + if (data.subscribe) { + // Subscribe the user to the site + const gate = createGate({ user }) + await subscribeToSite(gate, { + siteId: data.subscribe.siteId, + email: data.subscribe.email, + telegram: data.subscribe.telegram, }) } diff --git a/src/pages/api/save-avatar.ts b/src/pages/api/save-avatar.ts index 067dba77..eabe27f0 100644 --- a/src/pages/api/save-avatar.ts +++ b/src/pages/api/save-avatar.ts @@ -1,10 +1,9 @@ import { NextApiHandler } from "next" import { z } from "zod" -import { siteController } from "~/controllers/site.controller" import { getAuthUser } from "~/lib/auth.server" import { createGate } from "~/lib/gate.server" import { uploadImage } from "~/lib/upload.server" - +import { updateSite } from "~/models/site.model" import { userModel } from "~/models/user.model" export const config = { @@ -28,7 +27,7 @@ const handler: NextApiHandler = async (req, res) => { .parse(data) if (values.site) { - await siteController.updateSite(gate, { + await updateSite(gate, { site: values.site, icon: values.file, }) diff --git a/src/router/auth.ts b/src/router/auth.ts index 51bde8eb..ce638a5c 100644 --- a/src/router/auth.ts +++ b/src/router/auth.ts @@ -1,8 +1,6 @@ import dayjs from "dayjs" import { z } from "zod" -import { IS_PROD } from "~/lib/constants" import { prisma } from "~/lib/db.server" -import { OUR_DOMAIN } from "~/lib/env" import { sendLoginEmail } from "~/lib/mailgun.server" import { createRouter } from "~/lib/trpc.server" @@ -36,16 +34,11 @@ export const authRouter = createRouter() }, }) - const { protocol, host, pathname } = new URL(input.url) - - const url = `${ - IS_PROD ? "https" : "http" - }://${OUR_DOMAIN}/api/login?${new URLSearchParams([ - ["token", token.id], - ["next", `${protocol}//${host}${pathname}`], - ]).toString()}` - - await sendLoginEmail(url, input.email).catch(console.error) + await sendLoginEmail({ + url: input.url, + email: input.email, + token: token.id, + }).catch(console.error) return true }, diff --git a/src/router/dashboard.ts b/src/router/dashboard.ts index 1b6c5909..defac535 100644 --- a/src/router/dashboard.ts +++ b/src/router/dashboard.ts @@ -1,6 +1,6 @@ import { z } from "zod" -import { siteController } from "~/controllers/site.controller" import { createRouter } from "~/lib/trpc.server" +import { getSitesForViewer } from "~/models/site.model" export const dashboardRouter = createRouter().query("sitesForSwitcher", { output: z.array( @@ -13,7 +13,7 @@ export const dashboardRouter = createRouter().query("sitesForSwitcher", { }) ), async resolve({ ctx }) { - const sites = await siteController.getSites(ctx.gate) + const sites = await getSitesForViewer(ctx.gate) return sites }, }) diff --git a/src/router/index.ts b/src/router/index.ts index b5e26294..7d45afec 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -1,8 +1,8 @@ import * as trpc from "@trpc/server" import { z } from "zod" -import { siteController } from "~/controllers/site.controller" import { isNotFoundError } from "~/lib/server-side-props" import { TRPCContext } from "~/lib/trpc.server" +import { getSite } from "~/models/site.model" import { authRouter } from "./auth" import { dashboardRouter } from "./dashboard" import { siteRouter } from "./site" @@ -22,7 +22,7 @@ export const appRouter = trpc subdomain: z.string(), }), async resolve({ input }) { - const { site } = await siteController.getSite(input.site) + const site = await getSite(input.site) return site }, }) diff --git a/src/router/site.ts b/src/router/site.ts index abf1271b..a053bff0 100644 --- a/src/router/site.ts +++ b/src/router/site.ts @@ -1,8 +1,20 @@ import { z } from "zod" -import { siteController } from "~/controllers/site.controller" import { createRouter } from "~/lib/trpc.server" import { PageVisibilityEnum } from "~/lib/types" -import { getSite, getSubscription } from "~/models/site.model" +import { + getSite, + getSubscription, + updateSite, + createSite, + subscribeToSite, + unsubscribeFromSite, +} from "~/models/site.model" +import { + createOrUpdatePage, + getPage, + deletePage, + getPagesBySite, +} from "~/models/page.model" export const siteRouter = createRouter() .query("subscription", { @@ -57,7 +69,7 @@ export const siteRouter = createRouter() hasMore: z.boolean(), }), async resolve({ input, ctx }) { - const result = await siteController.getPages(ctx.gate, input) + const result = await getPagesBySite(ctx.gate, input) return result }, }) @@ -77,7 +89,7 @@ export const siteRouter = createRouter() type: z.enum(["PAGE", "POST"]), }), async resolve({ input, ctx }) { - const page = await siteController.getPage(ctx.gate, input) + const page = await getPage(ctx.gate, input) return page }, }) @@ -98,10 +110,7 @@ export const siteRouter = createRouter() subdomainUpdated: z.boolean(), }), async resolve({ ctx, input }) { - const { site, subdomainUpdated } = await siteController.updateSite( - ctx.gate, - input - ) + const { site, subdomainUpdated } = await updateSite(ctx.gate, input) return { site, subdomainUpdated, @@ -124,7 +133,7 @@ export const siteRouter = createRouter() id: z.string(), }), async resolve({ input, ctx }) { - const { page } = await siteController.createOrUpdatePage(ctx.gate, input) + const { page } = await createOrUpdatePage(ctx.gate, input) return page }, }) @@ -138,7 +147,7 @@ export const siteRouter = createRouter() subdomain: z.string(), }), async resolve({ input, ctx }) { - const { site } = await siteController.createSite(ctx.gate, input) + const { site } = await createSite(ctx.gate, input) return site }, }) @@ -147,6 +156,30 @@ export const siteRouter = createRouter() pageId: z.string(), }), async resolve({ ctx, input }) { - await siteController.deletePage(ctx.gate, { id: input.pageId }) + await deletePage(ctx.gate, { id: input.pageId }) + }, + }) + .mutation("subscribe", { + input: z.object({ + email: z.boolean().optional(), + telegram: z.boolean().optional(), + siteId: z.string(), + newUser: z + .object({ + email: z.string(), + url: z.string(), + }) + .optional(), + }), + async resolve({ input, ctx }) { + await subscribeToSite(ctx.gate, input) + }, + }) + .mutation("unsubscribe", { + input: z.object({ + siteId: z.string(), + }), + async resolve({ input, ctx }) { + await unsubscribeFromSite(ctx.gate, input) }, })