migrate post page and create post api, misc changes
This commit is contained in:
parent
60d1b031f5
commit
96c4023c14
33 changed files with 598 additions and 393 deletions
|
@ -14,7 +14,8 @@ const NewFromExisting = async ({
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return router.push("/new")
|
router.push("/new")
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const post = await getPostWithFiles(id)
|
const post = await getPostWithFiles(id)
|
||||||
|
|
|
@ -1,81 +0,0 @@
|
||||||
import type { GetServerSideProps } from "next"
|
|
||||||
|
|
||||||
import type { Post } from "@lib/types"
|
|
||||||
import PostPage from "@components/post-page"
|
|
||||||
import { USER_COOKIE_NAME } from "@lib/constants"
|
|
||||||
|
|
||||||
export type PostProps = {
|
|
||||||
post: Post
|
|
||||||
isProtected?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
const PostView = ({ post, isProtected }: PostProps) => {
|
|
||||||
return <PostPage isProtected={isProtected} post={post} />
|
|
||||||
}
|
|
||||||
|
|
||||||
export const getServerSideProps: GetServerSideProps = async ({
|
|
||||||
params,
|
|
||||||
req,
|
|
||||||
res
|
|
||||||
}) => {
|
|
||||||
const post = await fetch(process.env.API_URL + `/posts/${params?.id}`, {
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"x-secret-key": process.env.SECRET_KEY || "",
|
|
||||||
Authorization: `Bearer ${req.cookies["drift-token"]}`
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (post.status === 401 || post.status === 403) {
|
|
||||||
return {
|
|
||||||
// can't access the post if it's private
|
|
||||||
redirect: {
|
|
||||||
destination: "/",
|
|
||||||
permanent: false
|
|
||||||
},
|
|
||||||
props: {}
|
|
||||||
}
|
|
||||||
} else if (post.status === 404 || !post.ok) {
|
|
||||||
return {
|
|
||||||
redirect: {
|
|
||||||
destination: "/404",
|
|
||||||
permanent: false
|
|
||||||
},
|
|
||||||
props: {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const json = (await post.json()) as Post
|
|
||||||
const isAuthor = json.users?.find(
|
|
||||||
(user) => user.id === req.cookies[USER_COOKIE_NAME]
|
|
||||||
)
|
|
||||||
|
|
||||||
if (json.visibility === "public" || json.visibility === "unlisted") {
|
|
||||||
const sMaxAge = 60 * 60 * 12 // half a day
|
|
||||||
res.setHeader(
|
|
||||||
"Cache-Control",
|
|
||||||
`public, s-maxage=${sMaxAge}, max-age=${sMaxAge}`
|
|
||||||
)
|
|
||||||
} else if (json.visibility === "protected" && !isAuthor) {
|
|
||||||
return {
|
|
||||||
props: {
|
|
||||||
post: {
|
|
||||||
id: json.id,
|
|
||||||
visibility: json.visibility,
|
|
||||||
expiresAt: json.expiresAt
|
|
||||||
},
|
|
||||||
isProtected: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
props: {
|
|
||||||
post: json,
|
|
||||||
key: params?.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default PostView
|
|
|
@ -5,10 +5,10 @@ export default async function Head({
|
||||||
params
|
params
|
||||||
}: {
|
}: {
|
||||||
params: {
|
params: {
|
||||||
slug: string
|
id: string
|
||||||
}
|
}
|
||||||
}) {
|
}) {
|
||||||
const post = await getPostById(params.slug)
|
const post = await getPostById(params.id)
|
||||||
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
return null
|
return null
|
||||||
|
@ -17,7 +17,7 @@ export default async function Head({
|
||||||
return (
|
return (
|
||||||
<PageSeo
|
<PageSeo
|
||||||
title={`${post.title} - Drift`}
|
title={`${post.title} - Drift`}
|
||||||
description={post.description}
|
description={post.description || undefined}
|
||||||
isPrivate={false}
|
isPrivate={false}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
|
|
136
client/app/(posts)/post/[id]/page.tsx
Normal file
136
client/app/(posts)/post/[id]/page.tsx
Normal file
|
@ -0,0 +1,136 @@
|
||||||
|
import type { GetServerSideProps } from "next"
|
||||||
|
|
||||||
|
import type { Post } from "@lib/types"
|
||||||
|
import PostPage from "@components/post-page"
|
||||||
|
import { USER_COOKIE_NAME } from "@lib/constants"
|
||||||
|
import { notFound } from "next/navigation"
|
||||||
|
import { getPostById } from "@lib/server/prisma"
|
||||||
|
import { getCurrentUser, getSession } from "@lib/server/session"
|
||||||
|
import Header from "@components/header"
|
||||||
|
|
||||||
|
export type PostProps = {
|
||||||
|
post: Post
|
||||||
|
isProtected?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const getPost = async (id: string) => {
|
||||||
|
const post = await getPostById(id, true)
|
||||||
|
const user = await getCurrentUser()
|
||||||
|
|
||||||
|
if (!post) {
|
||||||
|
return notFound()
|
||||||
|
}
|
||||||
|
|
||||||
|
const isAuthor = user?.id === post?.authorId
|
||||||
|
|
||||||
|
if (post.visibility === "public") {
|
||||||
|
return { post, isAuthor, signedIn: Boolean(user) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// must be authed to see unlisted/private
|
||||||
|
if (
|
||||||
|
(post.visibility === "unlisted" || post.visibility === "private") &&
|
||||||
|
!user
|
||||||
|
) {
|
||||||
|
return notFound()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (post.visibility === "private" && !isAuthor) {
|
||||||
|
return notFound()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (post.visibility === "protected" && !isAuthor) {
|
||||||
|
return {
|
||||||
|
post,
|
||||||
|
isProtected: true,
|
||||||
|
isAuthor,
|
||||||
|
signedIn: Boolean(user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { post, isAuthor, signedIn: Boolean(user) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const PostView = async ({
|
||||||
|
params
|
||||||
|
}: {
|
||||||
|
params: {
|
||||||
|
id: string,
|
||||||
|
signedIn?: boolean
|
||||||
|
}
|
||||||
|
}) => {
|
||||||
|
const { post, isProtected, isAuthor } = await getPost(params.id)
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Header signedIn />
|
||||||
|
<PostPage isAuthor={isAuthor} isProtected={isProtected} post={post} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// export const getServerSideProps: GetServerSideProps = async ({
|
||||||
|
// params,
|
||||||
|
// req,
|
||||||
|
// res
|
||||||
|
// }) => {
|
||||||
|
// const post = await fetch(process.env.API_URL + `/posts/${params?.id}`, {
|
||||||
|
// method: "GET",
|
||||||
|
// headers: {
|
||||||
|
// "Content-Type": "application/json",
|
||||||
|
// "x-secret-key": process.env.SECRET_KEY || "",
|
||||||
|
// Authorization: `Bearer ${req.cookies["drift-token"]}`
|
||||||
|
// }
|
||||||
|
// })
|
||||||
|
|
||||||
|
// if (post.status === 401 || post.status === 403) {
|
||||||
|
// return {
|
||||||
|
// // can't access the post if it's private
|
||||||
|
// redirect: {
|
||||||
|
// destination: "/",
|
||||||
|
// permanent: false
|
||||||
|
// },
|
||||||
|
// props: {}
|
||||||
|
// }
|
||||||
|
// } else if (post.status === 404 || !post.ok) {
|
||||||
|
// return {
|
||||||
|
// redirect: {
|
||||||
|
// destination: "/404",
|
||||||
|
// permanent: false
|
||||||
|
// },
|
||||||
|
// props: {}
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const json = (await post.json()) as Post
|
||||||
|
// const isAuthor = json.users?.find(
|
||||||
|
// (user) => user.id === req.cookies[USER_COOKIE_NAME]
|
||||||
|
// )
|
||||||
|
|
||||||
|
// if (json.visibility === "public" || json.visibility === "unlisted") {
|
||||||
|
// const sMaxAge = 60 * 60 * 12 // half a day
|
||||||
|
// res.setHeader(
|
||||||
|
// "Cache-Control",
|
||||||
|
// `public, s-maxage=${sMaxAge}, max-age=${sMaxAge}`
|
||||||
|
// )
|
||||||
|
// } else if (json.visibility === "protected" && !isAuthor) {
|
||||||
|
// return {
|
||||||
|
// props: {
|
||||||
|
// post: {
|
||||||
|
// id: json.id,
|
||||||
|
// visibility: json.visibility,
|
||||||
|
// expiresAt: json.expiresAt
|
||||||
|
// },
|
||||||
|
// isProtected: true
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return {
|
||||||
|
// props: {
|
||||||
|
// post: json,
|
||||||
|
// key: params?.id
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
export default PostView
|
|
@ -1,6 +1,4 @@
|
||||||
import { USER_COOKIE_NAME } from "@lib/constants"
|
import { redirect } from "next/navigation"
|
||||||
import { notFound, redirect, useRouter } from "next/navigation"
|
|
||||||
import { cookies } from "next/headers"
|
|
||||||
import { getPostsByUser } from "@lib/server/prisma"
|
import { getPostsByUser } from "@lib/server/prisma"
|
||||||
import PostList from "@components/post-list"
|
import PostList from "@components/post-list"
|
||||||
import { getCurrentUser } from "@lib/server/session"
|
import { getCurrentUser } from "@lib/server/session"
|
||||||
|
|
|
@ -61,10 +61,7 @@ export function LayoutWrapper({
|
||||||
attribute="data-theme"
|
attribute="data-theme"
|
||||||
>
|
>
|
||||||
<CssBaseline />
|
<CssBaseline />
|
||||||
<Page width={"100%"} style={{
|
<Page width={"100%"}>
|
||||||
marginTop: "0 !important",
|
|
||||||
paddingTop: "0 !important"
|
|
||||||
}}>
|
|
||||||
{children}
|
{children}
|
||||||
</Page>
|
</Page>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|
|
@ -47,7 +47,7 @@ const UserTable = () => {
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
setToast({
|
setToast({
|
||||||
text: json.error || "Something went wrong",
|
text: "Something went wrong",
|
||||||
type: "error"
|
type: "error"
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -69,7 +69,7 @@ const UserTable = () => {
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
setToast({
|
setToast({
|
||||||
text: json.error || "Something went wrong",
|
text: "Something went wrong",
|
||||||
type: "error"
|
type: "error"
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,61 +18,10 @@ const Auth = ({
|
||||||
page: "signup" | "signin"
|
page: "signup" | "signin"
|
||||||
requiresServerPassword?: boolean
|
requiresServerPassword?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
const router = useRouter()
|
|
||||||
|
|
||||||
const [username, setUsername] = useState("")
|
|
||||||
const [password, setPassword] = useState("")
|
|
||||||
const [serverPassword, setServerPassword] = useState("")
|
const [serverPassword, setServerPassword] = useState("")
|
||||||
const [errorMsg, setErrorMsg] = useState("")
|
const [errorMsg, setErrorMsg] = useState("")
|
||||||
const signingIn = page === "signin"
|
const signingIn = page === "signin"
|
||||||
|
|
||||||
const handleJson = (json: any) => {
|
|
||||||
// setCookie(USER_COOKIE_NAME, json.userId)
|
|
||||||
|
|
||||||
router.push("/new")
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
|
|
||||||
e.preventDefault()
|
|
||||||
// if (
|
|
||||||
// !signingIn &&
|
|
||||||
// (!NO_EMPTY_SPACE_REGEX.test(username) || password.length < 6)
|
|
||||||
// )
|
|
||||||
// return setErrorMsg(ERROR_MESSAGE)
|
|
||||||
// if (
|
|
||||||
// !signingIn &&
|
|
||||||
// requiresServerPassword &&
|
|
||||||
// !NO_EMPTY_SPACE_REGEX.test(serverPassword)
|
|
||||||
// )
|
|
||||||
// return setErrorMsg(ERROR_MESSAGE)
|
|
||||||
// else setErrorMsg("")
|
|
||||||
|
|
||||||
const reqOpts = {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ username, password, serverPassword })
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// signIn("credentials", {
|
|
||||||
// callbackUrl: "/new",
|
|
||||||
// redirect: false,
|
|
||||||
// username,
|
|
||||||
// password,
|
|
||||||
// serverPassword
|
|
||||||
// })
|
|
||||||
// const signUrl = signingIn ? "/api/auth/signin" : "/api/auth/signup"
|
|
||||||
// const resp = await fetch(signUrl, reqOpts)
|
|
||||||
// const json = await resp.json()
|
|
||||||
// if (!resp.ok) throw new Error(json.error.message)
|
|
||||||
// handleJson(json)
|
|
||||||
} catch (err: any) {
|
|
||||||
setErrorMsg(err.message ?? "Something went wrong")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.container}>
|
<div className={styles.container}>
|
||||||
<div className={styles.form}>
|
<div className={styles.form}>
|
||||||
|
@ -122,7 +71,7 @@ const Auth = ({
|
||||||
auto
|
auto
|
||||||
width="100%"
|
width="100%"
|
||||||
icon={<GithubIcon />}
|
icon={<GithubIcon />}
|
||||||
onClick={() => signIn("github")}
|
onClick={() => signIn("github").catch((err) => setErrorMsg(err.message))}
|
||||||
>
|
>
|
||||||
Sign in with GitHub
|
Sign in with GitHub
|
||||||
</Button>
|
</Button>
|
||||||
|
|
|
@ -7,8 +7,8 @@ import { useCallback, useState } from "react"
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
postId: string
|
postId: string
|
||||||
visibility: PostVisibility
|
visibility: string
|
||||||
setVisibility: (visibility: PostVisibility) => void
|
setVisibility: (visibility: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const VisibilityControl = ({ postId, visibility, setVisibility }: Props) => {
|
const VisibilityControl = ({ postId, visibility, setVisibility }: Props) => {
|
||||||
|
@ -17,12 +17,11 @@ const VisibilityControl = ({ postId, visibility, setVisibility }: Props) => {
|
||||||
const { setToast } = useToasts()
|
const { setToast } = useToasts()
|
||||||
|
|
||||||
const sendRequest = useCallback(
|
const sendRequest = useCallback(
|
||||||
async (visibility: PostVisibility, password?: string) => {
|
async (visibility: string, password?: string) => {
|
||||||
const res = await fetch(`/server-api/posts/${postId}`, {
|
const res = await fetch(`/server-api/posts/${postId}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json"
|
||||||
Authorization: `Bearer ${getCookie(TOKEN_COOKIE_NAME)}`
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ visibility, password })
|
body: JSON.stringify({ visibility, password })
|
||||||
})
|
})
|
||||||
|
@ -33,7 +32,7 @@ const VisibilityControl = ({ postId, visibility, setVisibility }: Props) => {
|
||||||
} else {
|
} else {
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
setToast({
|
setToast({
|
||||||
text: json.error.message,
|
text: "An error occurred",
|
||||||
type: "error"
|
type: "error"
|
||||||
})
|
})
|
||||||
setPasswordModalVisible(false)
|
setPasswordModalVisible(false)
|
||||||
|
@ -63,10 +62,7 @@ const VisibilityControl = ({ postId, visibility, setVisibility }: Props) => {
|
||||||
setSubmitting(false)
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const submitPassword = useCallback(
|
const submitPassword = (password: string) => onSubmit("protected", password)
|
||||||
(password: string) => onSubmit("protected", password),
|
|
||||||
[onSubmit]
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
import { useRouter } from "next/router"
|
|
||||||
import NextLink from "next/link"
|
import NextLink from "next/link"
|
||||||
import styles from "./link.module.css"
|
import styles from "./link.module.css"
|
||||||
|
|
||||||
|
|
|
@ -15,8 +15,6 @@ import DatePicker from "react-datepicker"
|
||||||
import getTitleForPostCopy from "@lib/get-title-for-post-copy"
|
import getTitleForPostCopy from "@lib/get-title-for-post-copy"
|
||||||
import Description from "./description"
|
import Description from "./description"
|
||||||
import { PostWithFiles } from "@lib/server/prisma"
|
import { PostWithFiles } from "@lib/server/prisma"
|
||||||
import { TOKEN_COOKIE_NAME, USER_COOKIE_NAME } from "@lib/constants"
|
|
||||||
import { getCookie } from "cookies-next"
|
|
||||||
|
|
||||||
const emptyDoc = {
|
const emptyDoc = {
|
||||||
title: "",
|
title: "",
|
||||||
|
@ -60,15 +58,13 @@ const Post = ({
|
||||||
title?: string
|
title?: string
|
||||||
files?: DocumentType[]
|
files?: DocumentType[]
|
||||||
password?: string
|
password?: string
|
||||||
userId: string
|
|
||||||
parentId?: string
|
parentId?: string
|
||||||
}
|
}
|
||||||
) => {
|
) => {
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json"
|
||||||
Authorization: `Bearer ${getCookie(TOKEN_COOKIE_NAME)}`
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
title,
|
title,
|
||||||
|
@ -83,8 +79,9 @@ const Post = ({
|
||||||
router.push(`/post/${json.id}`)
|
router.push(`/post/${json.id}`)
|
||||||
} else {
|
} else {
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
|
console.error(json)
|
||||||
setToast({
|
setToast({
|
||||||
text: json.error.message || "Please fill out all fields",
|
text: "Please fill out all fields",
|
||||||
type: "error"
|
type: "error"
|
||||||
})
|
})
|
||||||
setPasswordModalVisible(false)
|
setPasswordModalVisible(false)
|
||||||
|
@ -140,13 +137,11 @@ const Post = ({
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const cookieName = getCookie(USER_COOKIE_NAME)
|
await sendRequest("/api/post", {
|
||||||
await sendRequest("/api/posts/create", {
|
|
||||||
title,
|
title,
|
||||||
files: docs,
|
files: docs,
|
||||||
visibility,
|
visibility,
|
||||||
password,
|
password,
|
||||||
userId: cookieName ? String(getCookie(USER_COOKIE_NAME)) : "",
|
|
||||||
expiresAt: expiresAt || null,
|
expiresAt: expiresAt || null,
|
||||||
parentId: newPostParent
|
parentId: newPostParent
|
||||||
})
|
})
|
||||||
|
@ -260,6 +255,7 @@ const Post = ({
|
||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
// 150 so the post dropdown doesn't overflow
|
||||||
<div style={{ paddingBottom: 150 }}>
|
<div style={{ paddingBottom: 150 }}>
|
||||||
<Title title={title} onChange={onChangeTitle} />
|
<Title title={title} onChange={onChangeTitle} />
|
||||||
<Description description={description} onChange={onChangeDescription} />
|
<Description description={description} onChange={onChangeDescription} />
|
||||||
|
|
|
@ -2,7 +2,7 @@ import React from "react"
|
||||||
|
|
||||||
type PageSeoProps = {
|
type PageSeoProps = {
|
||||||
title?: string
|
title?: string
|
||||||
description?: string | null
|
description?: string
|
||||||
isLoading?: boolean
|
isLoading?: boolean
|
||||||
isPrivate?: boolean
|
isPrivate?: boolean
|
||||||
}
|
}
|
||||||
|
|
|
@ -121,6 +121,7 @@ const PostList = ({ morePosts, initialPosts }: Props) => {
|
||||||
clearable
|
clearable
|
||||||
placeholder="Search..."
|
placeholder="Search..."
|
||||||
onChange={handleSearchChange}
|
onChange={handleSearchChange}
|
||||||
|
disabled={Boolean(!posts?.length)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{!posts && <Text type="error">Failed to load.</Text>}
|
{!posts && <Text type="error">Failed to load.</Text>}
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
import NextLink from "next/link"
|
|
||||||
import VisibilityBadge from "../badges/visibility-badge"
|
import VisibilityBadge from "../badges/visibility-badge"
|
||||||
import {
|
import {
|
||||||
Text,
|
Text,
|
||||||
|
@ -13,12 +12,13 @@ import Trash from "@geist-ui/icons/trash"
|
||||||
import ExpirationBadge from "@components/badges/expiration-badge"
|
import ExpirationBadge from "@components/badges/expiration-badge"
|
||||||
import CreatedAgoBadge from "@components/badges/created-ago-badge"
|
import CreatedAgoBadge from "@components/badges/created-ago-badge"
|
||||||
import Edit from "@geist-ui/icons/edit"
|
import Edit from "@geist-ui/icons/edit"
|
||||||
import { useRouter } from "next/router"
|
import { useRouter } from "next/navigation"
|
||||||
import Parent from "@geist-ui/icons/arrowUpCircle"
|
import Parent from "@geist-ui/icons/arrowUpCircle"
|
||||||
import styles from "./list-item.module.css"
|
import styles from "./list-item.module.css"
|
||||||
import Link from "@components/link"
|
import Link from "@components/link"
|
||||||
import { PostWithFiles, File } from "@lib/server/prisma"
|
import type { PostWithFiles } from "@lib/server/prisma"
|
||||||
import { PostVisibility } from "@lib/types"
|
import type { PostVisibility } from "@lib/types"
|
||||||
|
import type { File } from "@lib/server/prisma"
|
||||||
|
|
||||||
// TODO: isOwner should default to false so this can be used generically
|
// TODO: isOwner should default to false so this can be used generically
|
||||||
const ListItem = ({
|
const ListItem = ({
|
||||||
|
@ -40,6 +40,10 @@ const ListItem = ({
|
||||||
router.push(`/post/${post.parentId}`)
|
router.push(`/post/${post.parentId}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
console.log(post)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FadeIn>
|
<FadeIn>
|
||||||
<li key={post.id}>
|
<li key={post.id}>
|
||||||
|
@ -49,8 +53,7 @@ const ListItem = ({
|
||||||
<Link
|
<Link
|
||||||
colored
|
colored
|
||||||
style={{ marginRight: "var(--gap)" }}
|
style={{ marginRight: "var(--gap)" }}
|
||||||
href={`/post/[id]`}
|
href={`/post/${post.id}`}
|
||||||
as={`/post/${post.id}`}
|
|
||||||
>
|
>
|
||||||
{post.title}
|
{post.title}
|
||||||
</Link>
|
</Link>
|
||||||
|
@ -94,7 +97,7 @@ const ListItem = ({
|
||||||
</Card.Body>
|
</Card.Body>
|
||||||
<Divider h="1px" my={0} />
|
<Divider h="1px" my={0} />
|
||||||
<Card.Content>
|
<Card.Content>
|
||||||
{post.files?.map((file: File) => {
|
{post?.files?.map((file: File) => {
|
||||||
return (
|
return (
|
||||||
<div key={file.id}>
|
<div key={file.id}>
|
||||||
<Link colored href={`/post/${post.id}#${file.title}`}>
|
<Link colored href={`/post/${post.id}#${file.title}`}>
|
||||||
|
@ -105,7 +108,7 @@ const ListItem = ({
|
||||||
})}
|
})}
|
||||||
</Card.Content>
|
</Card.Content>
|
||||||
</Card>
|
</Card>
|
||||||
</li>{" "}
|
</li>
|
||||||
</FadeIn>
|
</FadeIn>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,56 +1,48 @@
|
||||||
import PageSeo from "@components/page-seo"
|
"use client"
|
||||||
|
|
||||||
import VisibilityBadge from "@components/badges/visibility-badge"
|
import VisibilityBadge from "@components/badges/visibility-badge"
|
||||||
import DocumentComponent from "@components/view-document"
|
import DocumentComponent from "@components/view-document"
|
||||||
import styles from "./post-page.module.css"
|
import styles from "./post-page.module.css"
|
||||||
import homeStyles from "@styles/Home.module.css"
|
|
||||||
|
|
||||||
import type { File, Post, PostVisibility } from "@lib/types"
|
import type { PostVisibility } from "@lib/types"
|
||||||
import {
|
import { Button, Text, ButtonGroup, useMediaQuery } from "@geist-ui/core/dist"
|
||||||
Page,
|
|
||||||
Button,
|
|
||||||
Text,
|
|
||||||
ButtonGroup,
|
|
||||||
useMediaQuery
|
|
||||||
} from "@geist-ui/core/dist"
|
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import Archive from "@geist-ui/icons/archive"
|
import Archive from "@geist-ui/icons/archive"
|
||||||
import Edit from "@geist-ui/icons/edit"
|
import Edit from "@geist-ui/icons/edit"
|
||||||
import Parent from "@geist-ui/icons/arrowUpCircle"
|
import Parent from "@geist-ui/icons/arrowUpCircle"
|
||||||
import FileDropdown from "@components/file-dropdown"
|
import FileDropdown from "@components/file-dropdown"
|
||||||
import ScrollToTop from "@components/scroll-to-top"
|
import ScrollToTop from "@components/scroll-to-top"
|
||||||
import { useRouter } from "next/router"
|
import { useRouter } from "next/navigation"
|
||||||
import ExpirationBadge from "@components/badges/expiration-badge"
|
import ExpirationBadge from "@components/badges/expiration-badge"
|
||||||
import CreatedAgoBadge from "@components/badges/created-ago-badge"
|
import CreatedAgoBadge from "@components/badges/created-ago-badge"
|
||||||
import PasswordModalPage from "./password-modal-wrapper"
|
import PasswordModalPage from "./password-modal-wrapper"
|
||||||
import VisibilityControl from "@components/badges/visibility-control"
|
import VisibilityControl from "@components/badges/visibility-control"
|
||||||
import { USER_COOKIE_NAME } from "@lib/constants"
|
import { File, PostWithFiles } from "@lib/server/prisma"
|
||||||
import { getCookie } from "cookies-next"
|
import Header from "@components/header"
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
post: Post
|
post: PostWithFiles
|
||||||
isProtected?: boolean
|
isProtected?: boolean
|
||||||
|
isAuthor?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const PostPage = ({ post: initialPost, isProtected }: Props) => {
|
const PostPage = ({ post: initialPost, isProtected, isAuthor }: Props) => {
|
||||||
const [post, setPost] = useState<Post>(initialPost)
|
const [post, setPost] = useState<PostWithFiles>(initialPost)
|
||||||
const [visibility, setVisibility] = useState<PostVisibility>(post.visibility)
|
const [visibility, setVisibility] = useState<string>(post.visibility)
|
||||||
const [isExpired, setIsExpired] = useState(
|
const [isExpired, setIsExpired] = useState(
|
||||||
post.expiresAt ? new Date(post.expiresAt) < new Date() : null
|
post.expiresAt ? new Date(post.expiresAt) < new Date() : null
|
||||||
)
|
)
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
const [isLoading, setIsLoading] = useState(true)
|
||||||
const [isOwner] = useState(
|
|
||||||
post.users ? post.users[0].id === getCookie(USER_COOKIE_NAME) : false
|
|
||||||
)
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const isMobile = useMediaQuery("mobile")
|
const isMobile = useMediaQuery("mobile")
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOwner && isExpired) {
|
if (!isAuthor && isExpired) {
|
||||||
router.push("/expired")
|
router.push("/expired")
|
||||||
}
|
}
|
||||||
|
|
||||||
const expirationDate = new Date(post.expiresAt ? post.expiresAt : "")
|
const expirationDate = new Date(post.expiresAt ? post.expiresAt : "")
|
||||||
if (!isOwner && expirationDate < new Date()) {
|
if (!isAuthor && expirationDate < new Date()) {
|
||||||
router.push("/expired")
|
router.push("/expired")
|
||||||
} else {
|
} else {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
|
@ -66,7 +58,7 @@ const PostPage = ({ post: initialPost, isProtected }: Props) => {
|
||||||
return () => {
|
return () => {
|
||||||
if (interval) clearInterval(interval)
|
if (interval) clearInterval(interval)
|
||||||
}
|
}
|
||||||
}, [isExpired, isOwner, post.expiresAt, post.users, router])
|
}, [isExpired, isAuthor, post.expiresAt, router])
|
||||||
|
|
||||||
const download = async () => {
|
const download = async () => {
|
||||||
if (!post.files) return
|
if (!post.files) return
|
||||||
|
@ -92,7 +84,7 @@ const PostPage = ({ post: initialPost, isProtected }: Props) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const viewParentClick = () => {
|
const viewParentClick = () => {
|
||||||
router.push(`/post/${post.parent!.id}`)
|
router.push(`/post/${post.parentId}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
|
@ -103,77 +95,74 @@ const PostPage = ({ post: initialPost, isProtected }: Props) => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|
||||||
{!isAvailable && <PasswordModalPage setPost={setPost} />}
|
{!isAvailable && <PasswordModalPage setPost={setPost} />}
|
||||||
<Page.Content className={homeStyles.main}>
|
<div className={styles.header}>
|
||||||
<div className={styles.header}>
|
<span className={styles.buttons}>
|
||||||
<span className={styles.buttons}>
|
<ButtonGroup
|
||||||
<ButtonGroup
|
vertical={isMobile}
|
||||||
vertical={isMobile}
|
marginLeft={0}
|
||||||
marginLeft={0}
|
marginRight={0}
|
||||||
marginRight={0}
|
marginTop={1}
|
||||||
marginTop={1}
|
marginBottom={1}
|
||||||
marginBottom={1}
|
>
|
||||||
|
<Button
|
||||||
|
auto
|
||||||
|
icon={<Edit />}
|
||||||
|
onClick={editACopy}
|
||||||
|
style={{ textTransform: "none" }}
|
||||||
>
|
>
|
||||||
<Button
|
Edit a Copy
|
||||||
auto
|
</Button>
|
||||||
icon={<Edit />}
|
{post.parent && (
|
||||||
onClick={editACopy}
|
<Button auto icon={<Parent />} onClick={viewParentClick}>
|
||||||
style={{ textTransform: "none" }}
|
View Parent
|
||||||
>
|
|
||||||
Edit a Copy
|
|
||||||
</Button>
|
</Button>
|
||||||
{post.parent && (
|
)}
|
||||||
<Button auto icon={<Parent />} onClick={viewParentClick}>
|
<Button
|
||||||
View Parent
|
auto
|
||||||
</Button>
|
onClick={download}
|
||||||
)}
|
icon={<Archive />}
|
||||||
<Button
|
style={{ textTransform: "none" }}
|
||||||
auto
|
>
|
||||||
onClick={download}
|
Download as ZIP Archive
|
||||||
icon={<Archive />}
|
</Button>
|
||||||
style={{ textTransform: "none" }}
|
<FileDropdown isMobile={isMobile} files={post.files || []} />
|
||||||
>
|
</ButtonGroup>
|
||||||
Download as ZIP Archive
|
</span>
|
||||||
</Button>
|
<span className={styles.title}>
|
||||||
<FileDropdown isMobile={isMobile} files={post.files || []} />
|
<Text h3>{post.title}</Text>
|
||||||
</ButtonGroup>
|
<span className={styles.badges}>
|
||||||
</span>
|
<VisibilityBadge visibility={visibility} />
|
||||||
<span className={styles.title}>
|
<CreatedAgoBadge createdAt={post.createdAt} />
|
||||||
<Text h3>{post.title}</Text>
|
<ExpirationBadge postExpirationDate={post.expiresAt} />
|
||||||
<span className={styles.badges}>
|
|
||||||
<VisibilityBadge visibility={visibility} />
|
|
||||||
<CreatedAgoBadge createdAt={post.createdAt} />
|
|
||||||
<ExpirationBadge postExpirationDate={post.expiresAt} />
|
|
||||||
</span>
|
|
||||||
</span>
|
</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{post.description && (
|
||||||
|
<div>
|
||||||
|
<Text p>{post.description}</Text>
|
||||||
</div>
|
</div>
|
||||||
{post.description && (
|
)}
|
||||||
<div>
|
{/* {post.files.length > 1 && <FileTree files={post.files} />} */}
|
||||||
<Text p>{post.description}</Text>
|
{post.files?.map(({ id, content, title }: File) => (
|
||||||
</div>
|
<DocumentComponent
|
||||||
)}
|
key={id}
|
||||||
{/* {post.files.length > 1 && <FileTree files={post.files} />} */}
|
title={title}
|
||||||
{post.files?.map(({ id, content, title }: File) => (
|
initialTab={"preview"}
|
||||||
<DocumentComponent
|
id={id}
|
||||||
key={id}
|
content={content}
|
||||||
title={title}
|
/>
|
||||||
initialTab={"preview"}
|
))}
|
||||||
id={id}
|
{isAuthor && (
|
||||||
content={content}
|
<span className={styles.controls}>
|
||||||
|
<VisibilityControl
|
||||||
|
postId={post.id}
|
||||||
|
visibility={visibility}
|
||||||
|
setVisibility={setVisibility}
|
||||||
/>
|
/>
|
||||||
))}
|
</span>
|
||||||
{isOwner && (
|
)}
|
||||||
<span className={styles.controls}>
|
<ScrollToTop />
|
||||||
<VisibilityControl
|
|
||||||
postId={post.id}
|
|
||||||
visibility={visibility}
|
|
||||||
setVisibility={setVisibility}
|
|
||||||
/>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<ScrollToTop />
|
|
||||||
</Page.Content>
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,21 +1,22 @@
|
||||||
import PasswordModal from "@components/new-post/password-modal"
|
import PasswordModal from "@components/new-post/password-modal"
|
||||||
import { Page, useToasts } from "@geist-ui/core/dist"
|
import { useToasts } from "@geist-ui/core/dist"
|
||||||
import { Post } from "@lib/types"
|
import { Post } from "@lib/server/prisma"
|
||||||
import { useRouter } from "next/router"
|
import { useRouter } from "next/navigation"
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
setPost: (post: Post) => void
|
setPost: (post: Post) => void
|
||||||
|
postId: Post["id"]
|
||||||
}
|
}
|
||||||
|
|
||||||
const PasswordModalPage = ({ setPost }: Props) => {
|
const PasswordModalPage = ({ setPost, postId }: Props) => {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { setToast } = useToasts()
|
const { setToast } = useToasts()
|
||||||
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(true)
|
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(true)
|
||||||
|
|
||||||
const onSubmit = async (password: string) => {
|
const onSubmit = async (password: string) => {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`/server-api/posts/authenticate?id=${router.query.id}&password=${password}`,
|
`/api/posts/authenticate?id=${postId}&password=${password}`,
|
||||||
{
|
{
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
|
|
|
@ -7,17 +7,10 @@ import { User } from "next-auth"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
|
|
||||||
const Profile = ({ user }: { user: User }) => {
|
const Profile = ({ user }: { user: User }) => {
|
||||||
const [name, setName] = useState<string>()
|
const [name, setName] = useState<string>(user.name || "")
|
||||||
const [email, setEmail] = useState<string>()
|
const [email, setEmail] = useState<string>(user.email || "")
|
||||||
const [bio, setBio] = useState<string>()
|
const [bio, setBio] = useState<string>()
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
console.log(user)
|
|
||||||
// if (user?.displayName) setName(user.displayName)
|
|
||||||
if (user?.email) setEmail(user.email)
|
|
||||||
// if (user?.bio) setBio(user.bio)
|
|
||||||
}, [user])
|
|
||||||
|
|
||||||
const { setToast } = useToasts()
|
const { setToast } = useToasts()
|
||||||
|
|
||||||
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
|
13
client/lib/api-middleware/with-methods.ts
Normal file
13
client/lib/api-middleware/with-methods.ts
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
// https://github.com/shadcn/taxonomy/
|
||||||
|
|
||||||
|
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
|
||||||
|
|
||||||
|
export function withMethods(methods: string[], handler: NextApiHandler) {
|
||||||
|
return async function (req: NextApiRequest, res: NextApiResponse) {
|
||||||
|
if (!req.method || !methods.includes(req.method)) {
|
||||||
|
return res.status(405).end()
|
||||||
|
}
|
||||||
|
|
||||||
|
return handler(req, res)
|
||||||
|
}
|
||||||
|
}
|
41
client/lib/api-middleware/with-validation.ts
Normal file
41
client/lib/api-middleware/with-validation.ts
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
import type { NextApiHandler, NextApiRequest, NextApiResponse } from "next"
|
||||||
|
import * as z from "zod"
|
||||||
|
import type { ZodSchema, ZodType } from "zod"
|
||||||
|
|
||||||
|
type NextApiRequestWithParsedBody<T> = NextApiRequest & {
|
||||||
|
parsedBody?: T
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NextApiHandlerWithParsedBody<T> = (
|
||||||
|
req: NextApiRequestWithParsedBody<T>,
|
||||||
|
res: NextApiResponse
|
||||||
|
) => ReturnType<NextApiHandler>
|
||||||
|
|
||||||
|
export function withValidation<T extends ZodSchema>(
|
||||||
|
schema: T,
|
||||||
|
handler: NextApiHandler
|
||||||
|
): (
|
||||||
|
req: NextApiRequest,
|
||||||
|
res: NextApiResponse
|
||||||
|
) => Promise<void | NextApiResponse<any> | NextApiHandlerWithParsedBody<T>> {
|
||||||
|
return async function (req: NextApiRequest, res: NextApiResponse) {
|
||||||
|
try {
|
||||||
|
const body = req.body
|
||||||
|
|
||||||
|
await schema.parseAsync(body)
|
||||||
|
|
||||||
|
;(req as NextApiRequestWithParsedBody<T>).parsedBody = body
|
||||||
|
|
||||||
|
return handler(req, res) as Promise<NextApiHandlerWithParsedBody<T>>
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === "development") {
|
||||||
|
console.error(error)
|
||||||
|
}
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
return res.status(422).json(error.issues)
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(422).end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -44,6 +44,7 @@ export const authOptions: NextAuthOptions = {
|
||||||
// TODO: user should be defined?
|
// TODO: user should be defined?
|
||||||
if (user) {
|
if (user) {
|
||||||
token.id = user.id
|
token.id = user.id
|
||||||
|
token.role = "user"
|
||||||
}
|
}
|
||||||
return token
|
return token
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,9 +28,13 @@ export function getHtmlFromFile({
|
||||||
let contentToRender: string = content || ""
|
let contentToRender: string = content || ""
|
||||||
|
|
||||||
if (!renderAsMarkdown.includes(type)) {
|
if (!renderAsMarkdown.includes(type)) {
|
||||||
contentToRender = `~~~${type}
|
contentToRender = `
|
||||||
|
|
||||||
|
~~~${type}
|
||||||
${content}
|
${content}
|
||||||
~~~`
|
~~~
|
||||||
|
|
||||||
|
`
|
||||||
} else {
|
} else {
|
||||||
contentToRender = "\n" + content
|
contentToRender = "\n" + content
|
||||||
}
|
}
|
||||||
|
|
|
@ -47,11 +47,11 @@ export async function withJwt(
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
email: true,
|
email: true,
|
||||||
displayName: true,
|
// displayName: true,
|
||||||
bio: true,
|
// bio: true,
|
||||||
createdAt: true,
|
// createdAt: true,
|
||||||
updatedAt: true,
|
// updatedAt: true,
|
||||||
deletedAt: true
|
// deletedAt: true
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if (!userObj) {
|
if (!userObj) {
|
||||||
|
|
|
@ -4,10 +4,45 @@ declare global {
|
||||||
|
|
||||||
import config from "@lib/config"
|
import config from "@lib/config"
|
||||||
import { Post, PrismaClient, File, User } from "@prisma/client"
|
import { Post, PrismaClient, File, User } from "@prisma/client"
|
||||||
|
import { cache } from "react"
|
||||||
import { generateAndExpireAccessToken } from "./generate-access-token"
|
import { generateAndExpireAccessToken } from "./generate-access-token"
|
||||||
|
|
||||||
const prisma = new PrismaClient()
|
const prisma = new PrismaClient()
|
||||||
|
|
||||||
|
// we want to update iff they exist the createdAt/updated/expired/deleted items
|
||||||
|
// the input could be an array, in which case we'd check each item in the array
|
||||||
|
// if it's an object, we'd check that object
|
||||||
|
// then we return the changed object or array
|
||||||
|
|
||||||
|
const updateDateForItem = (item: any) => {
|
||||||
|
if (item.createdAt) {
|
||||||
|
item.createdAt = item.createdAt.toISOString()
|
||||||
|
}
|
||||||
|
if (item.updatedAt) {
|
||||||
|
item.updatedAt = item.updatedAt.toISOString()
|
||||||
|
}
|
||||||
|
if (item.expiresAt) {
|
||||||
|
item.expiresAt = item.expiresAt.toISOString()
|
||||||
|
}
|
||||||
|
if (item.deletedAt) {
|
||||||
|
item.deletedAt = item.deletedAt.toISOString()
|
||||||
|
}
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateDates = (input: any) => {
|
||||||
|
if (Array.isArray(input)) {
|
||||||
|
return input.map((item) => updateDateForItem(item))
|
||||||
|
} else {
|
||||||
|
return updateDateForItem(input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
prisma.$use(async (params, next) => {
|
||||||
|
const result = await next(params)
|
||||||
|
return updateDates(result)
|
||||||
|
})
|
||||||
|
|
||||||
export default prisma
|
export default prisma
|
||||||
|
|
||||||
// https://next-auth.js.org/adapters/prisma
|
// https://next-auth.js.org/adapters/prisma
|
||||||
|
@ -30,42 +65,14 @@ export const getFilesForPost = async (postId: string) => {
|
||||||
return files
|
return files
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export async function getFilesByPost(postId: string) {
|
||||||
* When passed in a postId, fetches the post and then the files.
|
const files = await prisma.file.findMany({
|
||||||
* If passed a Post, it will fetch the files
|
where: {
|
||||||
* @param postIdOrPost Post or postId
|
postId
|
||||||
* @returns Promise<PostWithFiles>
|
}
|
||||||
*/
|
})
|
||||||
export async function getPostWithFiles(postId: string): Promise<PostWithFiles>
|
|
||||||
export async function getPostWithFiles(postObject: Post): Promise<PostWithFiles>
|
|
||||||
export async function getPostWithFiles(
|
|
||||||
postIdOrObject: string | Post
|
|
||||||
): Promise<PostWithFiles | undefined> {
|
|
||||||
let post: Post | null
|
|
||||||
if (typeof postIdOrObject === "string") {
|
|
||||||
post = await prisma.post.findUnique({
|
|
||||||
where: {
|
|
||||||
id: postIdOrObject
|
|
||||||
}
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
post = postIdOrObject
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!post) {
|
return files
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
const files = await getFilesForPost(post.id)
|
|
||||||
|
|
||||||
if (!files) {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...post,
|
|
||||||
files
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPostsByUser(userId: string): Promise<Post[]>
|
export async function getPostsByUser(userId: string): Promise<Post[]>
|
||||||
|
@ -77,23 +84,12 @@ export async function getPostsByUser(userId: User["id"], withFiles?: boolean) {
|
||||||
const posts = await prisma.post.findMany({
|
const posts = await prisma.post.findMany({
|
||||||
where: {
|
where: {
|
||||||
authorId: userId
|
authorId: userId
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
files: withFiles
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (withFiles) {
|
|
||||||
const postsWithFiles = await Promise.all(
|
|
||||||
posts.map(async (post) => {
|
|
||||||
const files = await getPostWithFiles(post)
|
|
||||||
return {
|
|
||||||
...post,
|
|
||||||
files
|
|
||||||
}
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
return postsWithFiles
|
|
||||||
}
|
|
||||||
|
|
||||||
return posts
|
return posts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -127,7 +123,11 @@ export const isUserAdmin = async (userId: User["id"]) => {
|
||||||
return user?.role?.toLowerCase() === "admin"
|
return user?.role?.toLowerCase() === "admin"
|
||||||
}
|
}
|
||||||
|
|
||||||
export const createUser = async (username: string, password: string, serverPassword?: string) => {
|
export const createUser = async (
|
||||||
|
username: string,
|
||||||
|
password: string,
|
||||||
|
serverPassword?: string
|
||||||
|
) => {
|
||||||
if (!username || !password) {
|
if (!username || !password) {
|
||||||
throw new Error("Missing param")
|
throw new Error("Missing param")
|
||||||
}
|
}
|
||||||
|
@ -141,9 +141,10 @@ export const createUser = async (username: string, password: string, serverPassw
|
||||||
}
|
}
|
||||||
|
|
||||||
// const salt = await genSalt(10)
|
// const salt = await genSalt(10)
|
||||||
|
|
||||||
// the first user is the admin
|
// the first user is the admin
|
||||||
const isUserAdminByDefault = config.enable_admin && (await prisma.user.count()) === 0
|
const isUserAdminByDefault =
|
||||||
|
config.enable_admin && (await prisma.user.count()) === 0
|
||||||
const userRole = isUserAdminByDefault ? "admin" : "user"
|
const userRole = isUserAdminByDefault ? "admin" : "user"
|
||||||
|
|
||||||
// const user = await prisma.user.create({
|
// const user = await prisma.user.create({
|
||||||
|
@ -162,10 +163,14 @@ export const createUser = async (username: string, password: string, serverPassw
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getPostById = async (postId: Post["id"]) => {
|
export const getPostById = async (postId: Post["id"], withFiles = false) => {
|
||||||
|
console.log("getPostById", postId)
|
||||||
const post = await prisma.post.findUnique({
|
const post = await prisma.post.findUnique({
|
||||||
where: {
|
where: {
|
||||||
id: postId
|
id: postId
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
files: withFiles
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,4 @@
|
||||||
|
|
||||||
import 'server-only';
|
|
||||||
import { unstable_getServerSession } from "next-auth/next"
|
import { unstable_getServerSession } from "next-auth/next"
|
||||||
import { authOptions } from "./auth"
|
import { authOptions } from "./auth"
|
||||||
|
|
||||||
|
|
|
@ -10,7 +10,6 @@ const epochs = [
|
||||||
["second", 1]
|
["second", 1]
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
// Get duration
|
|
||||||
const getDuration = (timeAgoInSeconds: number) => {
|
const getDuration = (timeAgoInSeconds: number) => {
|
||||||
for (let [name, seconds] of epochs) {
|
for (let [name, seconds] of epochs) {
|
||||||
const interval = Math.floor(timeAgoInSeconds / seconds)
|
const interval = Math.floor(timeAgoInSeconds / seconds)
|
||||||
|
|
18
client/lib/validations/post.ts
Normal file
18
client/lib/validations/post.ts
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
import { z } from "zod"
|
||||||
|
|
||||||
|
export const CreatePostSchema = z.object({
|
||||||
|
title: z.string(),
|
||||||
|
description: z.string(),
|
||||||
|
files: z.array(z.object({
|
||||||
|
title: z.string(),
|
||||||
|
content: z.string(),
|
||||||
|
})),
|
||||||
|
visibility: z.string(),
|
||||||
|
password: z.string().optional(),
|
||||||
|
expiresAt: z.number().optional().nullish(),
|
||||||
|
parentId: z.string().optional()
|
||||||
|
})
|
||||||
|
|
||||||
|
export const DeletePostSchema = z.object({
|
||||||
|
id: z.string()
|
||||||
|
})
|
|
@ -25,6 +25,7 @@
|
||||||
"marked": "^4.2.2",
|
"marked": "^4.2.2",
|
||||||
"next": "13.0.3-canary.4",
|
"next": "13.0.3-canary.4",
|
||||||
"next-auth": "^4.16.4",
|
"next-auth": "^4.16.4",
|
||||||
|
"next-joi": "^2.2.1",
|
||||||
"next-themes": "npm:@wits/next-themes@0.2.7",
|
"next-themes": "npm:@wits/next-themes@0.2.7",
|
||||||
"prism-react-renderer": "^1.3.5",
|
"prism-react-renderer": "^1.3.5",
|
||||||
"rc-table": "7.24.1",
|
"rc-table": "7.24.1",
|
||||||
|
|
|
@ -1,52 +1,47 @@
|
||||||
|
import { withMethods } from "@lib/api-middleware/with-methods"
|
||||||
import { getHtmlFromFile } from "@lib/server/get-html-from-drift-file"
|
import { getHtmlFromFile } from "@lib/server/get-html-from-drift-file"
|
||||||
import { parseQueryParam } from "@lib/server/parse-query-param"
|
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||||
import prisma from "@lib/server/prisma"
|
import prisma from "@lib/server/prisma"
|
||||||
import { NextApiRequest, NextApiResponse } from "next"
|
import { NextApiRequest, NextApiResponse } from "next"
|
||||||
|
|
||||||
export default async function handler(
|
export default withMethods(["GET"], (
|
||||||
req: NextApiRequest,
|
req: NextApiRequest,
|
||||||
res: NextApiResponse
|
res: NextApiResponse
|
||||||
) {
|
) => {
|
||||||
switch (req.method) {
|
const query = req.query
|
||||||
case "GET":
|
const fileId = parseQueryParam(query.fileId)
|
||||||
const query = req.query
|
const content = parseQueryParam(query.content)
|
||||||
const fileId = parseQueryParam(query.fileId)
|
const title = parseQueryParam(query.title)
|
||||||
const content = parseQueryParam(query.content)
|
|
||||||
const title = parseQueryParam(query.title)
|
|
||||||
|
|
||||||
if (fileId && (content || title)) {
|
if (fileId && (content || title)) {
|
||||||
return res.status(400).json({ error: "Too many arguments" })
|
return res.status(400).json({ error: "Too many arguments" })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileId) {
|
||||||
|
const file = await prisma.file.findUnique({
|
||||||
|
where: {
|
||||||
|
id: fileId
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
if (fileId) {
|
if (!file) {
|
||||||
// TODO: abstract to getFileById
|
return res.status(404).json({ error: "File not found" })
|
||||||
const file = await prisma.file.findUnique({
|
}
|
||||||
where: {
|
|
||||||
id: fileId
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!file) {
|
return res.json(file.html)
|
||||||
return res.status(404).json({ error: "File not found" })
|
} else {
|
||||||
}
|
if (!content || !title) {
|
||||||
|
return res.status(400).json({ error: "Missing arguments" })
|
||||||
|
}
|
||||||
|
|
||||||
return res.json(file.html)
|
const renderedHTML = getHtmlFromFile({
|
||||||
} else {
|
title,
|
||||||
if (!content || !title) {
|
content
|
||||||
return res.status(400).json({ error: "Missing arguments" })
|
})
|
||||||
}
|
|
||||||
|
|
||||||
const renderedHTML = getHtmlFromFile({
|
res.setHeader("Content-Type", "text/plain")
|
||||||
title,
|
res.status(200).write(renderedHTML)
|
||||||
content
|
res.end()
|
||||||
})
|
return
|
||||||
|
|
||||||
res.setHeader("Content-Type", "text/plain")
|
|
||||||
res.status(200).write(renderedHTML)
|
|
||||||
res.end()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return res.status(405).json({ error: "Method not allowed" })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,22 @@
|
||||||
import { NextApiRequest, NextApiResponse } from "next"
|
import { NextApiRequest, NextApiResponse } from "next"
|
||||||
|
import prisma from "lib/server/prisma"
|
||||||
|
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||||
|
|
||||||
const getRawFile = async (req: NextApiRequest, res: NextApiResponse) => {
|
const getRawFile = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||||
const { id } = req.query
|
const file = await prisma.file.findUnique({
|
||||||
const file = await fetch(`${process.env.API_URL}/files/html/${id}`, {
|
where: {
|
||||||
headers: {
|
id: parseQueryParam(req.query.id)
|
||||||
"x-secret-key": process.env.SECRET_KEY || "",
|
|
||||||
Authorization: `Bearer ${req.cookies["drift-token"]}`
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
if (file.ok) {
|
|
||||||
const json = await file.text()
|
if (!file) {
|
||||||
const data = json
|
return res.status(404).end()
|
||||||
// serve the file raw as plain text
|
|
||||||
res.setHeader("Content-Type", "text/plain; charset=utf-8")
|
|
||||||
res.setHeader("Cache-Control", "s-maxage=86400")
|
|
||||||
res.status(200).write(data, "utf-8")
|
|
||||||
res.end()
|
|
||||||
} else {
|
|
||||||
res.status(404).send("File not found")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
res.setHeader("Content-Type", "text/plain")
|
||||||
|
res.setHeader("Cache-Control", "public, max-age=4800")
|
||||||
|
console.log(file.html)
|
||||||
|
return res.status(200).write(file.html)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default getRawFile
|
export default getRawFile
|
||||||
|
|
136
client/pages/api/post/index.ts
Normal file
136
client/pages/api/post/index.ts
Normal file
|
@ -0,0 +1,136 @@
|
||||||
|
// nextjs typescript api handler
|
||||||
|
|
||||||
|
import { withCurrentUser } from "@lib/api-middleware/with-current-user"
|
||||||
|
import { withMethods } from "@lib/api-middleware/with-methods"
|
||||||
|
import {
|
||||||
|
NextApiHandlerWithParsedBody,
|
||||||
|
withValidation
|
||||||
|
} from "@lib/api-middleware/with-validation"
|
||||||
|
import { authOptions } from "@lib/server/auth"
|
||||||
|
import { CreatePostSchema } from "@lib/validations/post"
|
||||||
|
import { Post } from "@prisma/client"
|
||||||
|
import prisma, { getPostById } from "lib/server/prisma"
|
||||||
|
import { NextApiRequest, NextApiResponse } from "next"
|
||||||
|
import { unstable_getServerSession } from "next-auth/next"
|
||||||
|
import { File } from "lib/server/prisma"
|
||||||
|
import * as crypto from "crypto"
|
||||||
|
import { getHtmlFromFile } from "@lib/server/get-html-from-drift-file"
|
||||||
|
import { getSession } from "next-auth/react"
|
||||||
|
import { parseQueryParam } from "@lib/server/parse-query-param"
|
||||||
|
|
||||||
|
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
||||||
|
if (req.method === "POST") {
|
||||||
|
return await handlePost(req, res)
|
||||||
|
} else {
|
||||||
|
return await handleGet(req, res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withMethods(["POST", "GET"], handler)
|
||||||
|
|
||||||
|
async function handlePost(req: NextApiRequest, res: NextApiResponse<any>) {
|
||||||
|
try {
|
||||||
|
const session = await unstable_getServerSession(req, res, authOptions)
|
||||||
|
|
||||||
|
const files = req.body.files as File[]
|
||||||
|
const fileTitles = files.map((file) => file.title)
|
||||||
|
const missingTitles = fileTitles.filter((title) => title === "")
|
||||||
|
if (missingTitles.length > 0) {
|
||||||
|
throw new Error("All files must have a title")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (files.length === 0) {
|
||||||
|
throw new Error("You must submit at least one file")
|
||||||
|
}
|
||||||
|
|
||||||
|
let hashedPassword: string = ""
|
||||||
|
if (req.body.visibility === "protected") {
|
||||||
|
hashedPassword = crypto
|
||||||
|
.createHash("sha256")
|
||||||
|
.update(req.body.password)
|
||||||
|
.digest("hex")
|
||||||
|
}
|
||||||
|
|
||||||
|
const postFiles = files.map((file) => {
|
||||||
|
const html = getHtmlFromFile(file)
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: file.title,
|
||||||
|
content: file.content,
|
||||||
|
sha: crypto
|
||||||
|
.createHash("sha256")
|
||||||
|
.update(file.content)
|
||||||
|
.digest("hex")
|
||||||
|
.toString(),
|
||||||
|
html: html,
|
||||||
|
userId: session?.user.id
|
||||||
|
// postId: post.id
|
||||||
|
}
|
||||||
|
}) as File[]
|
||||||
|
|
||||||
|
const post = await prisma.post.create({
|
||||||
|
data: {
|
||||||
|
title: req.body.title,
|
||||||
|
description: req.body.description,
|
||||||
|
visibility: req.body.visibility,
|
||||||
|
password: hashedPassword,
|
||||||
|
expiresAt: req.body.expiresAt,
|
||||||
|
// authorId: session?.user.id,
|
||||||
|
author: {
|
||||||
|
connect: {
|
||||||
|
id: session?.user.id
|
||||||
|
}
|
||||||
|
},
|
||||||
|
files: {
|
||||||
|
create: postFiles
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return res.json(post)
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(500).json(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleGet(req: NextApiRequest, res: NextApiResponse<any>) {
|
||||||
|
const id = parseQueryParam(req.query.id)
|
||||||
|
const files = req.query.files ? parseQueryParam(req.query.files) : true
|
||||||
|
|
||||||
|
if (!id) {
|
||||||
|
return res.status(400).json({ error: "Missing id" })
|
||||||
|
}
|
||||||
|
|
||||||
|
const post = await getPostById(id, Boolean(files))
|
||||||
|
|
||||||
|
if (!post) {
|
||||||
|
return res.status(404).json({ message: "Post not found" })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (post.visibility === "public") {
|
||||||
|
res.setHeader("Cache-Control", "s-maxage=86400, stale-while-revalidate")
|
||||||
|
return res.json(post)
|
||||||
|
} else if (post.visibility === "unlisted") {
|
||||||
|
res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate")
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = await getSession({ req })
|
||||||
|
|
||||||
|
// the user can always go directly to their own post
|
||||||
|
if (session?.user.id === post.authorId) {
|
||||||
|
return res.json(post)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (post.visibility === "protected") {
|
||||||
|
return {
|
||||||
|
isProtected: true,
|
||||||
|
post: {
|
||||||
|
id: post.id,
|
||||||
|
visibility: post.visibility,
|
||||||
|
title: post.title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(404).json({ message: "Post not found" })
|
||||||
|
}
|
|
@ -26,6 +26,7 @@ specifiers:
|
||||||
marked: ^4.2.2
|
marked: ^4.2.2
|
||||||
next: 13.0.3-canary.4
|
next: 13.0.3-canary.4
|
||||||
next-auth: ^4.16.4
|
next-auth: ^4.16.4
|
||||||
|
next-joi: ^2.2.1
|
||||||
next-themes: npm:@wits/next-themes@0.2.7
|
next-themes: npm:@wits/next-themes@0.2.7
|
||||||
next-unused: 0.0.6
|
next-unused: 0.0.6
|
||||||
prettier: 2.6.2
|
prettier: 2.6.2
|
||||||
|
@ -61,6 +62,7 @@ dependencies:
|
||||||
marked: 4.2.2
|
marked: 4.2.2
|
||||||
next: 13.0.3-canary.4_biqbaboplfbrettd7655fr4n2y
|
next: 13.0.3-canary.4_biqbaboplfbrettd7655fr4n2y
|
||||||
next-auth: 4.16.4_hsmqkug4agizydugca45idewda
|
next-auth: 4.16.4_hsmqkug4agizydugca45idewda
|
||||||
|
next-joi: 2.2.1_next@13.0.3-canary.4
|
||||||
next-themes: /@wits/next-themes/0.2.7_hsmqkug4agizydugca45idewda
|
next-themes: /@wits/next-themes/0.2.7_hsmqkug4agizydugca45idewda
|
||||||
prism-react-renderer: 1.3.5_react@18.2.0
|
prism-react-renderer: 1.3.5_react@18.2.0
|
||||||
rc-table: 7.24.1_biqbaboplfbrettd7655fr4n2y
|
rc-table: 7.24.1_biqbaboplfbrettd7655fr4n2y
|
||||||
|
@ -2732,6 +2734,15 @@ packages:
|
||||||
uuid: 8.3.2
|
uuid: 8.3.2
|
||||||
dev: false
|
dev: false
|
||||||
|
|
||||||
|
/next-joi/2.2.1_next@13.0.3-canary.4:
|
||||||
|
resolution: {integrity: sha512-m6/rDj9a9sp0CeMGy3np/7T2663QFinfiTY4MuJ9LEicU+6SiDim4wnsqG5CfzI4IQX4tupN6jSCtsv0t2EWnQ==}
|
||||||
|
peerDependencies:
|
||||||
|
joi: '>=17.1.1'
|
||||||
|
next: '>=9.5.1'
|
||||||
|
dependencies:
|
||||||
|
next: 13.0.3-canary.4_biqbaboplfbrettd7655fr4n2y
|
||||||
|
dev: false
|
||||||
|
|
||||||
/next-unused/0.0.6:
|
/next-unused/0.0.6:
|
||||||
resolution: {integrity: sha512-dHFNNBanFq4wvYrULtsjfWyZ6BzOnr5VYI9EYMGAZYF2vkAhFpj2JOuT5Wu2o3LbFSG92PmAZnSUF/LstF82pA==}
|
resolution: {integrity: sha512-dHFNNBanFq4wvYrULtsjfWyZ6BzOnr5VYI9EYMGAZYF2vkAhFpj2JOuT5Wu2o3LbFSG92PmAZnSUF/LstF82pA==}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
|
@ -57,7 +57,7 @@ model Post {
|
||||||
parentId String?
|
parentId String?
|
||||||
description String?
|
description String?
|
||||||
author User? @relation(fields: [authorId], references: [id])
|
author User? @relation(fields: [authorId], references: [id])
|
||||||
authorId String?
|
authorId String
|
||||||
files File[]
|
files File[]
|
||||||
|
|
||||||
@@map("posts")
|
@@map("posts")
|
||||||
|
|
|
@ -161,3 +161,9 @@ code {
|
||||||
#__next {
|
#__next {
|
||||||
isolation: isolate;
|
isolation: isolate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* TODO: this should not be necessary. */
|
||||||
|
main {
|
||||||
|
margin-top: 0 !important;
|
||||||
|
padding-top: 0 !important;
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue