Merge pull request #65 from spencerwooo/protected-route

Protected routes, folders, and files support
This commit is contained in:
Spencer Woo
2021-08-30 15:54:39 +01:00
committed by GitHub
13 changed files with 931 additions and 1190 deletions
+56
View File
@@ -0,0 +1,56 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { FunctionComponent } from 'react'
import { matchProtectedRoute } from '../utils/tools'
import useLocalStorage from '../utils/useLocalStorage'
const Auth: FunctionComponent<{ redirect: string }> = ({ redirect }) => {
const authTokenPath = matchProtectedRoute(redirect)
const router = useRouter()
const [token, setToken] = useLocalStorage(authTokenPath, '')
return (
<div className="flex flex-col space-y-4 max-w-sm mx-auto md:my-10">
<div className="mx-auto w-3/4 md:w-5/6">
<Image src={'/images/no-looking.png'} alt="authenticate" width={912} height={912} />
</div>
<div className="dark:text-gray-100 text-gray-900 text-lg font-bold">Enter Password</div>
<p className="text-sm text-gray-500">
This route (the folder itself and the files inside) is password protected. If you know the password, please
enter it below.
</p>
<input
className="font-mono p-2 bg-blue-50 dark:bg-gray-600 dark:text-white rounded focus:ring focus:ring-blue-300 dark:focus:ring-blue-700 focus:outline-none"
autoFocus
type="text"
placeholder="************"
value={token}
onChange={e => {
setToken(e.target.value)
}}
onKeyPress={e => {
if (e.key === 'Enter' || e.key === 'NumpadEnter') {
router.reload()
}
}}
/>
<button
className="inline-flex space-x-2 items-center justify-center bg-blue-500 rounded py-2 px-4 text-white focus:outline-none focus:ring focus:ring-blue-300 hover:bg-blue-600"
onClick={() => {
router.reload()
}}
>
<span>Lemme in</span>
<FontAwesomeIcon icon="arrow-right" />
</button>
</div>
)
}
export default Auth
+3 -2
View File
@@ -17,6 +17,7 @@ import { VideoPreview } from './previews/VideoPreview'
import { AudioPreview } from './previews/AudioPreview'
import Loading from './Loading'
import FourOhFour from './FourOhFour'
import Auth from './Auth'
import TextPreview from './previews/TextPreview'
import MarkdownPreview from './previews/MarkdownPreview'
import CodePreview from './previews/CodePreview'
@@ -105,12 +106,12 @@ const FileListing: FunctionComponent<{ query?: ParsedUrlQuery }> = ({ query }) =
const path = queryToPath(query)
const { data, error } = useStaleSWR(`/api?path=${path}`)
const { data, error } = useStaleSWR(`/api?path=${path}`, path)
if (error) {
return (
<div className="shadow bg-white dark:bg-gray-900 rounded p-3">
<FourOhFour errorMsg={error.message} />
{error.message.includes('401') ? <Auth redirect={path} /> : <FourOhFour errorMsg={error.message} />}
</div>
)
}
+6 -2
View File
@@ -5,9 +5,13 @@ const FourOhFour: FunctionComponent<{ errorMsg: string }> = ({ errorMsg }) => {
return (
<div className="text-center my-20">
<div className="mx-auto w-1/2 md:w-1/3">
<Image src={'/404.png'} alt="404" width={825} height={910} />
<Image src={'/images/empty.png'} alt="404" width={912} height={912} />
</div>
<div className="text-gray-500 mt-5">
Error: {errorMsg}.{' '}
<kbd className="border bg-gray-200 font-mono text-sm px-2 py-1 rounded border-opacity-20">F12</kbd> for more
details.
</div>
<div className="text-gray-500 mt-5">Error: {errorMsg}</div>
</div>
)
}
+140 -11
View File
@@ -1,24 +1,153 @@
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { IconName } from '@fortawesome/fontawesome-svg-core'
import { Dialog, Transition } from '@headlessui/react'
import toast, { Toaster } from 'react-hot-toast'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { Fragment, useEffect, useState } from 'react'
import siteConfig from '../config/site.json'
const Navbar = () => {
const router = useRouter()
const [tokenPresent, setTokenPresent] = useState(false)
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
const storedToken = () => {
for (const r of siteConfig.protectedRoutes) {
if (localStorage.hasOwnProperty(r)) {
return true
}
}
return false
}
setTokenPresent(storedToken())
}, [])
const clearTokens = () => {
setIsOpen(false)
siteConfig.protectedRoutes.forEach(r => {
localStorage.removeItem(r)
})
toast.success('Cleared all tokens')
setTimeout(() => {
router.reload()
}, 1000)
}
return (
<div className="text-left p-1 bg-white dark:bg-gray-900 sticky top-0 bg-opacity-80 backdrop-blur-md shadow-sm z-[100]">
<div className="max-w-4xl w-full mx-auto flex items-center justify-between">
<h1 className="font-bold text-xl p-2 rounded dark:text-white hover:opacity-80">
<Link href="/">{siteConfig.title}</Link>
</h1>
<a
href="https://github.com/spencerwooo/onedrive-vercel-index"
target="_blank"
rel="noopener noreferrer"
className="p-2 rounded dark:text-white hover:opacity-80"
>
<FontAwesomeIcon icon={['fab', 'github']} size="lg" />
</a>
<Toaster />
<Link href="/">
<a className="flex items-center space-x-2 font-bold text-xl p-2 dark:text-white hover:opacity-80">
<FontAwesomeIcon icon="cloud" />
<span className="hidden sm:block">{siteConfig.title}</span>
</a>
</Link>
<div className="flex items-center">
{siteConfig.contacts.map((c, i) => (
<a
key={i}
href={c.link}
target="_blank"
rel="noopener noreferrer"
className="p-2 rounded hover:bg-gray-200 dark:text-white dark:hover:bg-gray-700"
>
{c.platform === 'email' ? (
<FontAwesomeIcon icon={['far', 'envelope']} size="lg" />
) : (
<FontAwesomeIcon icon={['fab', c.platform as IconName]} size="lg" />
)}
</a>
))}
{tokenPresent && (
<button
className="flex space-x-2 items-center p-2 rounded hover:bg-gray-200 dark:text-white dark:hover:bg-gray-700"
onClick={() => setIsOpen(true)}
>
<span>Logout</span>
<FontAwesomeIcon icon="sign-out-alt" />
</button>
)}
</div>
</div>
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="fixed inset-0 z-10 overflow-y-auto" open={isOpen} onClose={() => setIsOpen(false)}>
<div className="min-h-screen px-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-50"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Dialog.Overlay className="fixed inset-0 bg-gray-50 dark:bg-gray-800" />
</Transition.Child>
{/* This element is to trick the browser into centering the modal contents. */}
<span className="inline-block h-screen align-middle" aria-hidden="true">
&#8203;
</span>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-50"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<div className="inline-block w-full max-w-md p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-gray-900 shadow-lg rounded">
<Dialog.Title className="text-lg font-bold text-gray-900 dark:text-gray-100">
Clear all tokens?
</Dialog.Title>
<div className="mt-2">
<p className="text-sm text-gray-500">
These tokens are used to authenticate yourself into password protected folders, clearing them means
that you will need to re-enter the passwords again.
</p>
</div>
<div className="mt-4 font-mono text-sm dark:text-gray-100 max-h-32 overflow-y-scroll">
{siteConfig.protectedRoutes.map((r, i) => (
<div key={i} className="flex space-x-1 items-center">
<FontAwesomeIcon icon="key" />
<span className="truncate">{r}</span>
</div>
))}
</div>
<div className="mt-8 flex justify-end items-center">
<button
className="inline-flex space-x-2 items-center justify-center bg-blue-500 rounded py-2 px-4 text-white focus:outline-none focus:ring focus:ring-blue-300 hover:bg-blue-600 mr-3"
onClick={() => setIsOpen(false)}
>
Cancel
</button>
<button
className="inline-flex space-x-2 items-center justify-center bg-red-500 rounded py-2 px-4 text-white focus:outline-none focus:ring focus:ring-red-300 hover:bg-red-600"
onClick={() => clearTokens()}
>
<FontAwesomeIcon icon={['far', 'trash-alt']} />
<span>Clear all</span>
</button>
</div>
</div>
</Transition.Child>
</div>
</Dialog>
</Transition>
</div>
)
}
+15 -1
View File
@@ -1,4 +1,18 @@
{
"title": "Spencer's OneDrive Index",
"footer": "Powered by <a class=\"hover:underline\" href=\"https://github.com/spencerwooo/onedrive-vercel-index\" target=\"_blank\" rel=\"noopener noreferrer\">onedrive-vercel-index</a>. Made with ❤ by SpencerWoo."
"footer": "Powered by <a class=\"hover:underline\" href=\"https://github.com/spencerwooo/onedrive-vercel-index\" target=\"_blank\" rel=\"noopener noreferrer\">onedrive-vercel-index</a>. Made with ❤ by SpencerWoo.",
"protectedRoutes": [
"/🌞 Private folder/u-need-a-password",
"/🥟 Some test files/Protected route"
],
"contacts": [
{
"platform": "email",
"link": "mailto:spencer.wushangbo@gmail.com"
},
{
"platform": "github",
"link": "https://github.com/spencerwooo/onedrive-vercel-index"
}
]
}
+541 -1166
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -14,6 +14,7 @@
"@fortawesome/free-regular-svg-icons": "^5.15.3",
"@fortawesome/free-solid-svg-icons": "^5.15.3",
"@fortawesome/react-fontawesome": "^0.1.14",
"@headlessui/react": "^1.4.0",
"axios": "^0.21.1",
"emoji-regex": "^9.2.2",
"next": "^11.1.0",
+11 -1
View File
@@ -18,6 +18,8 @@ import {
faFolder,
faCopy,
faArrowAltCircleDown,
faTrashAlt,
faEnvelope,
} from '@fortawesome/free-regular-svg-icons'
import {
faPlus,
@@ -30,6 +32,9 @@ import {
faFileDownload,
faUndo,
faBook,
faKey,
faSignOutAlt,
faCloud,
} from '@fortawesome/free-solid-svg-icons'
import { faGithub, faMarkdown } from '@fortawesome/free-brands-svg-icons'
@@ -61,7 +66,12 @@ library.add(
faDownload,
faUndo,
faBook,
faArrowAltCircleDown
faArrowAltCircleDown,
faKey,
faTrashAlt,
faSignOutAlt,
faEnvelope,
faCloud
)
function MyApp({ Component, pageProps }: AppProps) {
+41
View File
@@ -3,6 +3,7 @@ import type { NextApiRequest, NextApiResponse } from 'next'
import { posix as pathPosix } from 'path'
import apiConfig from '../../config/api.json'
import siteConfig from '../../config/site.json'
const basePath = pathPosix.resolve('/', apiConfig.base)
const encodePath = (path: string) => {
@@ -49,6 +50,46 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (typeof path === 'string') {
const accessToken = await getAccessToken()
// Handle authentication through .password
const protectedRoutes = siteConfig.protectedRoutes
let authTokenPath = ''
for (const r of protectedRoutes) {
if (path.startsWith(r)) {
authTokenPath = `${r}/.password`
break
}
}
// Fetch password from remote file content
if (authTokenPath !== '') {
try {
const token = await axios.get(`${apiConfig.driveApi}/root${encodePath(authTokenPath)}`, {
headers: { Authorization: `Bearer ${accessToken}` },
params: {
select: '@microsoft.graph.downloadUrl,file',
},
})
// Handle request and check for header 'od-protected-token'
const odProtectedToken = await axios.get(token.data['@microsoft.graph.downloadUrl'])
// console.log(req.headers['od-protected-token'], odProtectedToken.data.trim())
if (req.headers['od-protected-token'] !== odProtectedToken.data.trim()) {
res.status(401).json({ error: 'Password required for this folder.' })
return
}
} catch (error) {
// Password file not found, fallback to 404
if (error.response.status === 404) {
res.status(404).json({ error: "You didn't set a password for your protected folder." })
}
res.status(500).end()
return
}
}
// Handle response from OneDrive API
const requestUrl = `${apiConfig.driveApi}/root${encodePath(path)}`
const { data } = await axios.get(requestUrl, {
headers: { Authorization: `Bearer ${accessToken}` },
Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

+39 -7
View File
@@ -1,5 +1,7 @@
import useSWR, { cache, Key } from 'swr'
import axios from 'axios'
import useSWR, { cache, Key } from 'swr'
import siteConfig from '../config/site.json'
/**
* Extract the current web page's base url
@@ -13,19 +15,49 @@ export const getBaseUrl = () => {
}
// Common axios fetch function
const fetcher = (url: string) => axios.get(url).then(res => res.data)
const fetcher = (url: string, token?: string) => {
return token
? axios
.get(url, {
headers: { 'od-protected-token': token },
})
.then(res => res.data)
: axios.get(url).then(res => res.data)
}
/**
* Use stale SWR instead of revalidating on each request. Not ideal for this scenario but have to do
* if fetching serverside props from component instead of pages.
* @param dataKey request url
* @param url request url
* @returns useSWR instance
*/
export const useStaleSWR = (dataKey: Key) => {
export const useStaleSWR = (url: Key, path: string = '') => {
const revalidationOptions = {
revalidateOnMount: !cache.has(dataKey),
revalidateOnMount: !(cache.has(`arg@"${url}"@null`) || cache.has(url)),
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateOnReconnect: true,
}
return useSWR(dataKey, fetcher, revalidationOptions)
const token =
typeof window !== 'undefined' ? JSON.parse(localStorage.getItem(matchProtectedRoute(path)) as string) : ''
return useSWR([url, token], fetcher, revalidationOptions)
}
export const matchProtectedRoute = (route: string) => {
const protectedRoutes = siteConfig.protectedRoutes
let authTokenPath = ''
for (const r of protectedRoutes) {
if (
route.startsWith(
r
.split('/')
.map(p => encodeURIComponent(p))
.join('/')
)
) {
authTokenPath = r
break
}
}
return authTokenPath
}
+78
View File
@@ -0,0 +1,78 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
type SetValue<T> = Dispatch<SetStateAction<T>>
function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T>] {
// Get from local storage then
// parse stored json or return initialValue
const readValue = (): T => {
// Prevent build error "window is undefined" but keep keep working
if (typeof window === 'undefined') {
return initialValue
}
try {
const item = window.localStorage.getItem(key)
return item ? (JSON.parse(item) as T) : initialValue
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error)
return initialValue
}
}
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState<T>(readValue)
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue: SetValue<T> = value => {
// Prevent build error "window is undefined" but keeps working
if (typeof window == 'undefined') {
console.warn(`Tried setting localStorage key “${key}” even though environment is not a client`)
}
try {
// Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(storedValue) : value
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(newValue))
// Save state
setStoredValue(newValue)
// We dispatch a custom event so every useLocalStorage hook are notified
window.dispatchEvent(new Event('local-storage'))
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error)
}
}
useEffect(() => {
setStoredValue(readValue())
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
const handleStorageChange = () => {
setStoredValue(readValue())
}
// this only works for other documents, not the current one
window.addEventListener('storage', handleStorageChange)
// this is a custom event, triggered in writeValueToLocalStorage
window.addEventListener('local-storage', handleStorageChange)
return () => {
window.removeEventListener('storage', handleStorageChange)
window.removeEventListener('local-storage', handleStorageChange)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return [storedValue, setValue]
}
export default useLocalStorage