client: finish protected posts
This commit is contained in:
parent
a3130e6d2a
commit
ecd06a2258
9 changed files with 195 additions and 34 deletions
|
@ -1,5 +1,4 @@
|
||||||
import { Page, ButtonGroup, Button, useBodyScroll, useMediaQuery, Tabs, Spacer } from "@geist-ui/core";
|
import { Page, ButtonGroup, Button, useBodyScroll, useMediaQuery, Tabs, Spacer } from "@geist-ui/core";
|
||||||
import { DriftProps } from "../../pages/_app";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import styles from './header.module.css';
|
import styles from './header.module.css';
|
||||||
import { useRouter } from "next/router";
|
import { useRouter } from "next/router";
|
||||||
|
@ -15,6 +14,7 @@ import NewIcon from '@geist-ui/icons/plusCircle';
|
||||||
import YourIcon from '@geist-ui/icons/list'
|
import YourIcon from '@geist-ui/icons/list'
|
||||||
import MoonIcon from '@geist-ui/icons/moon';
|
import MoonIcon from '@geist-ui/icons/moon';
|
||||||
import SunIcon from '@geist-ui/icons/sun';
|
import SunIcon from '@geist-ui/icons/sun';
|
||||||
|
import type { ThemeProps } from "@lib/types";
|
||||||
|
|
||||||
type Tab = {
|
type Tab = {
|
||||||
name: string
|
name: string
|
||||||
|
@ -26,13 +26,13 @@ type Tab = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const Header = ({ changeTheme, theme }: DriftProps) => {
|
const Header = ({ changeTheme, theme }: ThemeProps) => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [selectedTab, setSelectedTab] = useState<string>(router.pathname === '/' ? 'home' : router.pathname.split('/')[1]);
|
const [selectedTab, setSelectedTab] = useState<string>(router.pathname === '/' ? 'home' : router.pathname.split('/')[1]);
|
||||||
const [expanded, setExpanded] = useState<boolean>(false)
|
const [expanded, setExpanded] = useState<boolean>(false)
|
||||||
const [, setBodyHidden] = useBodyScroll(null, { scrollLayer: true })
|
const [, setBodyHidden] = useBodyScroll(null, { scrollLayer: true })
|
||||||
const isMobile = useMediaQuery('xs', { match: 'down' })
|
const isMobile = useMediaQuery('xs', { match: 'down' })
|
||||||
const isSignedIn = useSignedIn()
|
const { signedIn: isSignedIn } = useSignedIn()
|
||||||
const [pages, setPages] = useState<Tab[]>([])
|
const [pages, setPages] = useState<Tab[]>([])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
@ -41,17 +41,15 @@ const Post = () => {
|
||||||
} else {
|
} else {
|
||||||
const json = await res.json()
|
const json = await res.json()
|
||||||
setToast({
|
setToast({
|
||||||
text: json.message,
|
text: json.error.message,
|
||||||
type: 'error'
|
type: 'error'
|
||||||
})
|
})
|
||||||
|
setPasswordModalVisible(false)
|
||||||
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
}, [docs, router, setToast, title])
|
}, [docs, router, setToast, title])
|
||||||
|
|
||||||
const closePasswordModel = () => {
|
|
||||||
setPasswordModalVisible(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const [isSubmitting, setSubmitting] = useState(false)
|
const [isSubmitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
const remove = (id: string) => {
|
const remove = (id: string) => {
|
||||||
|
@ -59,12 +57,12 @@ const Post = () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
const onSubmit = async (visibility: PostVisibility, password?: string) => {
|
const onSubmit = async (visibility: PostVisibility, password?: string) => {
|
||||||
setSubmitting(true)
|
console.log(visibility, password, passwordModalVisible)
|
||||||
|
|
||||||
if (visibility === 'protected' && !password) {
|
if (visibility === 'protected' && !password) {
|
||||||
setPasswordModalVisible(true)
|
setPasswordModalVisible(true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
setSubmitting(true)
|
||||||
|
|
||||||
await sendRequest('/server-api/posts/create', {
|
await sendRequest('/server-api/posts/create', {
|
||||||
title,
|
title,
|
||||||
|
@ -77,6 +75,7 @@ const Post = () => {
|
||||||
|
|
||||||
const onClosePasswordModal = () => {
|
const onClosePasswordModal = () => {
|
||||||
setPasswordModalVisible(false)
|
setPasswordModalVisible(false)
|
||||||
|
setSubmitting(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateTitle = useCallback((title: string, id: string) => {
|
const updateTitle = useCallback((title: string, id: string) => {
|
||||||
|
|
|
@ -2,12 +2,13 @@ import { Input, Modal, Note, Spacer } from "@geist-ui/core"
|
||||||
import { useState } from "react"
|
import { useState } from "react"
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
|
warning?: boolean
|
||||||
isOpen: boolean
|
isOpen: boolean
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onSubmit: (password: string) => 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 [password, setPassword] = useState<string>()
|
||||||
const [confirmPassword, setConfirmPassword] = useState<string>()
|
const [confirmPassword, setConfirmPassword] = useState<string>()
|
||||||
const [error, setError] = useState<string>()
|
const [error, setError] = useState<string>()
|
||||||
|
@ -30,7 +31,7 @@ const PasswordModal = ({ isOpen, onClose, onSubmit: onSubmitAfterVerify }: Props
|
||||||
{<Modal visible={isOpen} >
|
{<Modal visible={isOpen} >
|
||||||
<Modal.Title>Enter a password</Modal.Title>
|
<Modal.Title>Enter a password</Modal.Title>
|
||||||
<Modal.Content>
|
<Modal.Content>
|
||||||
{!error && <Note type="warning" label='Warning'>
|
{!error && warning && <Note type="warning" label='Warning'>
|
||||||
This doesn't protect your post from the server administrator.
|
This doesn't protect your post from the server administrator.
|
||||||
</Note>}
|
</Note>}
|
||||||
{error && <Note type="error" label='Error'>
|
{error && <Note type="error" label='Error'>
|
||||||
|
|
|
@ -3,16 +3,17 @@ import { useEffect, useState } from "react";
|
||||||
|
|
||||||
const useSignedIn = () => {
|
const useSignedIn = () => {
|
||||||
const [signedIn, setSignedIn] = useState(typeof window === 'undefined' ? false : !!Cookies.get("drift-token"));
|
const [signedIn, setSignedIn] = useState(typeof window === 'undefined' ? false : !!Cookies.get("drift-token"));
|
||||||
|
const token = Cookies.get("drift-token")
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Cookies.get("drift-token")) {
|
if (token) {
|
||||||
setSignedIn(true);
|
setSignedIn(true);
|
||||||
} else {
|
} else {
|
||||||
setSignedIn(false);
|
setSignedIn(false);
|
||||||
}
|
}
|
||||||
}, []);
|
}, [token]);
|
||||||
|
|
||||||
return signedIn;
|
return { signedIn, token };
|
||||||
}
|
}
|
||||||
|
|
||||||
export default useSignedIn;
|
export default useSignedIn;
|
||||||
|
|
16
client/lib/types.d.ts
vendored
16
client/lib/types.d.ts
vendored
|
@ -10,3 +10,19 @@ export type Document = {
|
||||||
content: string
|
content: string
|
||||||
id: 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
|
||||||
|
}
|
||||||
|
|
|
@ -14,7 +14,6 @@ type AppProps<P = any> = {
|
||||||
pageProps: P;
|
pageProps: P;
|
||||||
} & Omit<NextAppProps<P>, "pageProps">;
|
} & Omit<NextAppProps<P>, "pageProps">;
|
||||||
|
|
||||||
export type DriftProps = ThemeProps
|
|
||||||
|
|
||||||
function MyApp({ Component, pageProps }: AppProps<ThemeProps>) {
|
function MyApp({ Component, pageProps }: AppProps<ThemeProps>) {
|
||||||
const [themeType, setThemeType] = useSharedState<string>('theme', Cookies.get('drift-theme') || 'light')
|
const [themeType, setThemeType] = useSharedState<string>('theme', Cookies.get('drift-theme') || 'light')
|
||||||
|
|
|
@ -6,24 +6,10 @@ import VisibilityBadge from "@components/visibility-badge";
|
||||||
import PageSeo from "components/page-seo";
|
import PageSeo from "components/page-seo";
|
||||||
import styles from './styles.module.css';
|
import styles from './styles.module.css';
|
||||||
import type { GetStaticPaths, GetStaticProps } from "next";
|
import type { GetStaticPaths, GetStaticProps } from "next";
|
||||||
import { PostVisibility, ThemeProps } from "@lib/types";
|
import { Post, ThemeProps } from "@lib/types";
|
||||||
|
|
||||||
type File = {
|
|
||||||
id: string
|
|
||||||
title: string
|
|
||||||
content: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Files = File[]
|
|
||||||
|
|
||||||
export type PostProps = ThemeProps & {
|
export type PostProps = ThemeProps & {
|
||||||
post: {
|
post: Post
|
||||||
id: string
|
|
||||||
title: string
|
|
||||||
description: string
|
|
||||||
visibility: PostVisibility
|
|
||||||
files: Files
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const Post = ({ post, theme, changeTheme }: PostProps) => {
|
const Post = ({ post, theme, changeTheme }: PostProps) => {
|
||||||
|
|
134
client/pages/post/protected/[id].tsx
Normal file
134
client/pages/post/protected/[id].tsx
Normal 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
|
||||||
|
|
|
@ -27,9 +27,19 @@ posts.post('/create', jwt, async (req, res, next) => {
|
||||||
throw new Error("Please provide a visibility.")
|
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({
|
const newPost = new Post({
|
||||||
title: req.body.title,
|
title: req.body.title,
|
||||||
visibility: req.body.visibility,
|
visibility: req.body.visibility,
|
||||||
|
password: hashedPassword,
|
||||||
})
|
})
|
||||||
|
|
||||||
await newPost.save()
|
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 {
|
try {
|
||||||
const post = await Post.findOne({
|
const post = await Post.findOne({
|
||||||
where: {
|
where: {
|
||||||
|
@ -117,18 +127,33 @@ posts.get("/:id", secretKey, async (req, res, next) => {
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
throw new Error("Post not found.")
|
throw new Error("Post not found.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (post.visibility === 'public' || post?.visibility === 'unlisted') {
|
if (post.visibility === 'public' || post?.visibility === 'unlisted') {
|
||||||
res.json(post);
|
secretKey(req, res, () => {
|
||||||
|
res.json(post);
|
||||||
|
})
|
||||||
} else if (post.visibility === 'private') {
|
} else if (post.visibility === 'private') {
|
||||||
jwt(req as UserJwtRequest, res, () => {
|
jwt(req as UserJwtRequest, res, () => {
|
||||||
res.json(post);
|
res.json(post);
|
||||||
})
|
})
|
||||||
} else if (post.visibility === 'protected') {
|
} 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) {
|
catch (e) {
|
||||||
|
|
Loading…
Reference in a new issue