implement subcribe/unsubscribe
TODO: add users to mailgun mailing list as well
This commit is contained in:
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<Modal title="Become a subscriber" open={open} setOpen={setOpen}>
|
||||
<form className="p-5" onSubmit={subscribeForm.handleSubmit}>
|
||||
<div>
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={subscribeForm.values.email}
|
||||
onChange={(e) =>
|
||||
subscribeForm.setFieldValue("email", e.target.checked)
|
||||
}
|
||||
/>
|
||||
<Badge className="mr-1">Soon</Badge>
|
||||
<span>Receive updates via Email</span>
|
||||
</label>
|
||||
{subscribe.isSuccess && !isLoggedIn ? (
|
||||
<div className="p-5 space-y-3">
|
||||
<p>
|
||||
We have sent you an email with a link to confirm your subscription.
|
||||
</p>
|
||||
<p>Please check your inbox (and spam folder).</p>
|
||||
</div>
|
||||
<div className="">
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={subscribeForm.values.telegram}
|
||||
onChange={(e) =>
|
||||
subscribeForm.setFieldValue("telegram", e.target.checked)
|
||||
}
|
||||
/>
|
||||
<Badge>Soon</Badge>
|
||||
<span>Receive updates via Telegram</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-5 space-x-3">
|
||||
<Button type="submit" isLoading={subscribeForm.isSubmitting}>
|
||||
<span>{subscription ? "Update" : "Subscribe"}</span>
|
||||
</Button>
|
||||
{subscription && (
|
||||
<form className="inline" onSubmit={unsubscribeForm.handleSubmit}>
|
||||
) : (
|
||||
<form className="p-5" onSubmit={subscribeForm.handleSubmit}>
|
||||
{!isLoggedIn && (
|
||||
<div className="mb-5">
|
||||
<Input
|
||||
label="Email"
|
||||
name="newUserEmail"
|
||||
type="email"
|
||||
isBlock
|
||||
value={subscribeForm.values.newUserEmail}
|
||||
onChange={subscribeForm.handleChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={subscribeForm.values.email}
|
||||
onChange={(e) =>
|
||||
subscribeForm.setFieldValue("email", e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>Receive updates via Email</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="">
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={subscribeForm.values.telegram}
|
||||
onChange={(e) =>
|
||||
subscribeForm.setFieldValue("telegram", e.target.checked)
|
||||
}
|
||||
/>
|
||||
<span>Receive updates via Telegram</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-5 space-x-3">
|
||||
<Button type="submit" isLoading={subscribe.isLoading}>
|
||||
<span>{subscription ? "Update" : "Subscribe"}</span>
|
||||
</Button>
|
||||
{subscription && (
|
||||
<Button
|
||||
type="submit"
|
||||
type="button"
|
||||
variant="secondary"
|
||||
isLoading={unsubscribeForm.isSubmitting}
|
||||
isLoading={unsubscribe.isLoading}
|
||||
onClick={() => unsubscribe.mutate({ siteId })}
|
||||
>
|
||||
Unsubscribe
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ const Header: React.FC<{
|
||||
(store) => store.setSubscribeModalOpened
|
||||
)
|
||||
const router = useRouter()
|
||||
const handleClickSubscribe = () => {
|
||||
setSubscribeModalOpened(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="border-b">
|
||||
<div className="px-5 max-w-screen-md mx-auto">
|
||||
@@ -47,7 +51,7 @@ const Header: React.FC<{
|
||||
rounded="full"
|
||||
size="sm"
|
||||
variant={subscribed ? "secondary" : "primary"}
|
||||
onClick={() => setSubscribeModalOpened(true)}
|
||||
onClick={handleClickSubscribe}
|
||||
>
|
||||
<span className="-ml-1">
|
||||
{subscribed ? (
|
||||
@@ -184,7 +188,11 @@ export const SiteLayout: React.FC<SiteLayoutProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
{site.id && (
|
||||
<SubscribeModal siteId={site.id} subscription={subscription} />
|
||||
<SubscribeModal
|
||||
siteId={site.id}
|
||||
subscription={subscription}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -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 }
|
||||
},
|
||||
}
|
||||
@@ -23,3 +23,5 @@ export const prisma = /* @__PURE__ */ singleton("prisma-read", () => {
|
||||
|
||||
return client
|
||||
})
|
||||
|
||||
export type { Prisma }
|
||||
|
||||
@@ -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 = `<p>Please use the link below to log in to ${APP_NAME}:</p>
|
||||
|
||||
<a href="${loginLink}">login</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>
|
||||
`
|
||||
|
||||
if (payload.subscribeForm) {
|
||||
const site = await getSite(payload.subscribeForm.siteId)
|
||||
subject = `Confirm your subscription to ${site.name}`
|
||||
html = `
|
||||
<p>Please confirm your subscription to ${site.name} by clicking the link below:</p>
|
||||
|
||||
<a href="${loginLink}">confirm</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>`
|
||||
}
|
||||
|
||||
const message: MailgunMessageData = {
|
||||
from: `${APP_NAME} <hi@${OUR_DOMAIN}>`,
|
||||
to: email,
|
||||
subject: `Log in to ${APP_NAME}`,
|
||||
html: `<p>Please use the link below to log in to ${APP_NAME}:</p>
|
||||
|
||||
<a href="${loginLink}">login</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>
|
||||
`,
|
||||
to: payload.email,
|
||||
subject,
|
||||
html,
|
||||
}
|
||||
|
||||
console.log(message)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+193
-37
@@ -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,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ export const getServerSideProps: GetServerSideProps = serverSidePropsHandler(
|
||||
page: pageSlug,
|
||||
renderContent: true,
|
||||
}),
|
||||
ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }),
|
||||
])
|
||||
|
||||
return {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
+5
-12
@@ -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
|
||||
},
|
||||
|
||||
@@ -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
|
||||
},
|
||||
})
|
||||
|
||||
+2
-2
@@ -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
|
||||
},
|
||||
})
|
||||
|
||||
+44
-11
@@ -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)
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user