client: finish protected posts

This commit is contained in:
Max Leiter 2022-03-21 18:51:19 -07:00
parent a3130e6d2a
commit ecd06a2258
No known key found for this signature in database
GPG key ID: A3512F2F2F17EBDA
9 changed files with 195 additions and 34 deletions

View file

@ -1,5 +1,4 @@
import { Page, ButtonGroup, Button, useBodyScroll, useMediaQuery, Tabs, Spacer } from "@geist-ui/core";
import { DriftProps } from "../../pages/_app";
import { useEffect, useState } from "react";
import styles from './header.module.css';
import { useRouter } from "next/router";
@ -15,6 +14,7 @@ import NewIcon from '@geist-ui/icons/plusCircle';
import YourIcon from '@geist-ui/icons/list'
import MoonIcon from '@geist-ui/icons/moon';
import SunIcon from '@geist-ui/icons/sun';
import type { ThemeProps } from "@lib/types";
type Tab = {
name: string
@ -26,13 +26,13 @@ type Tab = {
}
const Header = ({ changeTheme, theme }: DriftProps) => {
const Header = ({ changeTheme, theme }: ThemeProps) => {
const router = useRouter();
const [selectedTab, setSelectedTab] = useState<string>(router.pathname === '/' ? 'home' : router.pathname.split('/')[1]);
const [expanded, setExpanded] = useState<boolean>(false)
const [, setBodyHidden] = useBodyScroll(null, { scrollLayer: true })
const isMobile = useMediaQuery('xs', { match: 'down' })
const isSignedIn = useSignedIn()
const { signedIn: isSignedIn } = useSignedIn()
const [pages, setPages] = useState<Tab[]>([])
useEffect(() => {

View file

@ -41,17 +41,15 @@ const Post = () => {
} else {
const json = await res.json()
setToast({
text: json.message,
text: json.error.message,
type: 'error'
})
setPasswordModalVisible(false)
setSubmitting(false)
}
}, [docs, router, setToast, title])
const closePasswordModel = () => {
setPasswordModalVisible(false)
}
const [isSubmitting, setSubmitting] = useState(false)
const remove = (id: string) => {
@ -59,12 +57,12 @@ const Post = () => {
}
const onSubmit = async (visibility: PostVisibility, password?: string) => {
setSubmitting(true)
console.log(visibility, password, passwordModalVisible)
if (visibility === 'protected' && !password) {
setPasswordModalVisible(true)
return
}
setSubmitting(true)
await sendRequest('/server-api/posts/create', {
title,
@ -77,6 +75,7 @@ const Post = () => {
const onClosePasswordModal = () => {
setPasswordModalVisible(false)
setSubmitting(false)
}
const updateTitle = useCallback((title: string, id: string) => {

View file

@ -2,12 +2,13 @@ import { Input, Modal, Note, Spacer } from "@geist-ui/core"
import { useState } from "react"
type Props = {
warning?: boolean
isOpen: boolean
onClose: () => void
onSubmit: (password: string) => void
}
const PasswordModal = ({ isOpen, onClose, onSubmit: onSubmitAfterVerify }: Props) => {
const PasswordModal = ({ isOpen, onClose, onSubmit: onSubmitAfterVerify, warning }: Props) => {
const [password, setPassword] = useState<string>()
const [confirmPassword, setConfirmPassword] = useState<string>()
const [error, setError] = useState<string>()
@ -30,7 +31,7 @@ const PasswordModal = ({ isOpen, onClose, onSubmit: onSubmitAfterVerify }: Props
{<Modal visible={isOpen} >
<Modal.Title>Enter a password</Modal.Title>
<Modal.Content>
{!error && <Note type="warning" label='Warning'>
{!error && warning && <Note type="warning" label='Warning'>
This doesn&apos;t protect your post from the server administrator.
</Note>}
{error && <Note type="error" label='Error'>

View file

@ -3,16 +3,17 @@ import { useEffect, useState } from "react";
const useSignedIn = () => {
const [signedIn, setSignedIn] = useState(typeof window === 'undefined' ? false : !!Cookies.get("drift-token"));
const token = Cookies.get("drift-token")
useEffect(() => {
if (Cookies.get("drift-token")) {
if (token) {
setSignedIn(true);
} else {
setSignedIn(false);
}
}, []);
}, [token]);
return signedIn;
return { signedIn, token };
}
export default useSignedIn;

16
client/lib/types.d.ts vendored
View file

@ -10,3 +10,19 @@ export type Document = {
content: string
id: string
}
type File = {
id: string
title: string
content: string
}
type Files = File[]
export type Post = {
id: string
title: string
description: string
visibility: PostVisibility
files: Files
}

View file

@ -14,7 +14,6 @@ type AppProps<P = any> = {
pageProps: P;
} & Omit<NextAppProps<P>, "pageProps">;
export type DriftProps = ThemeProps
function MyApp({ Component, pageProps }: AppProps<ThemeProps>) {
const [themeType, setThemeType] = useSharedState<string>('theme', Cookies.get('drift-theme') || 'light')

View file

@ -6,24 +6,10 @@ import VisibilityBadge from "@components/visibility-badge";
import PageSeo from "components/page-seo";
import styles from './styles.module.css';
import type { GetStaticPaths, GetStaticProps } from "next";
import { PostVisibility, ThemeProps } from "@lib/types";
type File = {
id: string
title: string
content: string
}
type Files = File[]
import { Post, ThemeProps } from "@lib/types";
export type PostProps = ThemeProps & {
post: {
id: string
title: string
description: string
visibility: PostVisibility
files: Files
}
post: Post
}
const Post = ({ post, theme, changeTheme }: PostProps) => {

View file

@ -0,0 +1,134 @@
import { Button, Page, Text, useToasts } from "@geist-ui/core";
import Document from '@components/document'
import Header from "@components/header";
import VisibilityBadge from "@components/visibility-badge";
import PageSeo from "components/page-seo";
import styles from '../styles.module.css';
import { Post, ThemeProps } from "@lib/types";
import PasswordModal from "@components/new-post/password";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import Cookies from "js-cookie";
const Post = ({ theme, changeTheme }: ThemeProps) => {
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(true);
const [post, setPost] = useState<Post>()
const router = useRouter()
const { setToast } = useToasts()
const download = async () => {
if (!post) return;
const clientZip = require("client-zip")
const blob = await clientZip.downloadZip(post.files.map((file: any) => {
return {
name: file.title,
input: file.content,
lastModified: new Date(file.updatedAt)
}
})).blob()
const link = document.createElement("a")
link.href = URL.createObjectURL(blob)
link.download = `${post.title}.zip`
link.click()
link.remove()
}
useEffect(() => {
if (router.isReady) {
const fetchPostWithAuth = async () => {
const resp = await fetch(`/server-api/posts/${router.query.id}`, {
headers: {
Authorization: `Bearer ${Cookies.get('drift-token')}`
}
})
if (!resp.ok) return
const post = await resp.json()
if (!post) return
setPost(post)
}
fetchPostWithAuth()
}
}, [router.isReady, router.query.id])
const onSubmit = async (password: string) => {
const res = await fetch(`/server-api/posts/${router.query.id}?password=${password}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
}
})
if (!res.ok) {
setToast({
type: "error",
text: "Wrong password"
})
return
}
const data = await res.json()
if (data) {
if (data.error) {
setToast({
text: data.error,
type: "error"
})
} else {
setPost(data)
setIsPasswordModalOpen(false)
}
}
}
const onClose = () => {
setIsPasswordModalOpen(false);
}
if (!router.isReady) {
return <></>
}
if (!post) {
return <Page><PasswordModal warning={false} onClose={onClose} onSubmit={onSubmit} isOpen={isPasswordModalOpen} /></Page>
}
return (
<Page width={"100%"}>
<PageSeo
title={`${post.title} - Drift`}
description={post.description}
isPrivate={true}
/>
<Page.Header>
<Header theme={theme} changeTheme={changeTheme} />
</Page.Header>
<Page.Content width={"var(--main-content-width)"} margin="auto">
{/* {!isLoading && <PostFileExplorer files={post.files} />} */}
<div className={styles.header}>
<div className={styles.titleAndBadge}>
<Text h2>{post.title}</Text>
<span><VisibilityBadge visibility={post.visibility} /></span>
</div>
<Button auto onClick={download}>
Download as ZIP archive
</Button>
</div>
{post.files.map(({ id, content, title }: { id: any, content: string, title: string }) => (
<Document
key={id}
id={id}
content={content}
title={title}
editable={false}
initialTab={'preview'}
/>
))}
</Page.Content>
</Page >
)
}
export default Post

View file

@ -27,9 +27,19 @@ posts.post('/create', jwt, async (req, res, next) => {
throw new Error("Please provide a visibility.")
}
if (req.body.visibility === 'protected' && !req.body.password) {
throw new Error("Please provide a password.")
}
let hashedPassword: string = ''
if (req.body.visibility === 'protected') {
hashedPassword = crypto.createHash('sha256').update(req.body.password).digest('hex');
}
const newPost = new Post({
title: req.body.title,
visibility: req.body.visibility,
password: hashedPassword,
})
await newPost.save()
@ -98,7 +108,7 @@ posts.get("/mine", jwt, secretKey, async (req: UserJwtRequest, res, next) => {
}
})
posts.get("/:id", secretKey, async (req, res, next) => {
posts.get("/:id", async (req, res, next) => {
try {
const post = await Post.findOne({
where: {
@ -117,18 +127,33 @@ posts.get("/:id", secretKey, async (req, res, next) => {
},
]
})
if (!post) {
throw new Error("Post not found.")
}
if (post.visibility === 'public' || post?.visibility === 'unlisted') {
res.json(post);
secretKey(req, res, () => {
res.json(post);
})
} else if (post.visibility === 'private') {
jwt(req as UserJwtRequest, res, () => {
res.json(post);
})
} else if (post.visibility === 'protected') {
const { password } = req.query
if (!password || typeof password !== 'string') {
return jwt(req as UserJwtRequest, res, () => {
res.json(post);
})
}
const hash = crypto.createHash('sha256').update(password).digest('hex').toString()
if (hash !== post.password) {
return res.status(400).json({ error: "Incorrect password." })
}
res.json(post);
}
}
catch (e) {