move to next-auth

This commit is contained in:
Thomas Ruoff
2021-10-02 00:35:28 +02:00
committed by Thomas Ruoff
parent 9f4180388b
commit b257bc8258
12 changed files with 536 additions and 1418 deletions

16
components/denied.tsx Normal file
View File

@@ -0,0 +1,16 @@
import { signIn } from 'next-auth/react'
export default function Denied() {
return (
<>
<h1>Du bist nicht angemeldet.</h1>
<p>
<a
onClick={(e) => {
e.preventDefault()
signIn()
}}>Melde dich an um diese Seite zu sehen.</a>
</p>
</>
)
}

View File

@@ -1,28 +1,19 @@
import { useRouter } from 'next/router'
import { useContext } from 'react'
import { useSession, signOut } from 'next-auth/react'
import UserContext from '../context/user'
import fetch from '../helpers/fetch'
export default function User() {
const router = useRouter()
const { username, role } = useContext(UserContext)
const { data, status } = useSession();
if (!username || !role) {
return <div />
}
const onClickLogout = async () => {
await fetch('/api/logout', { method: 'POST' })
router.reload()
if (status === 'loading' || !data?.user?.email) {
return null;
}
return (
<>
<div className="font-extrabold bg-red-400 px-2 py-1 mr-3 rounded-sm">
{username}
{data.user.email}
</div>
<button onClick={onClickLogout} className="btn btn-blue">
<button onClick={() => signOut()} className="btn btn-blue">
Logout
</button>
</>

View File

@@ -1,23 +0,0 @@
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD
export function authenticateAdmin({
username,
password,
}: {
username: string
password: string
}): boolean {
if (username !== 'admin') {
return false
}
if (!ADMIN_PASSWORD) {
throw new Error('ADMIN_PASSWORD not set. Login disabled!')
}
if (password !== ADMIN_PASSWORD) {
return false
}
return true
}

View File

@@ -1,46 +0,0 @@
import { withIronSession, Handler } from 'next-iron-session'
import { getBaseURL } from '../helpers/url'
export enum USER_ROLE {
ADMIN = 'admin',
}
export type UserData = {
username: string
role: USER_ROLE
}
const SESSION_SECRET =
process.env.SESSION_SECRET || 'dev-env-default-secret-991823723'
export default function withSession(handler: Handler) {
return withIronSession(handler, {
password: SESSION_SECRET,
cookieName: 'pfadi-bussle-cookie',
cookieOptions: {
// the next line allows to use the session in non-https environements like
// Next.js dev mode (http://localhost:3000)
secure: process.env.NODE_ENV === 'production',
},
})
}
export function isAdminSession(req: any) {
const user = req?.session.get('user') as UserData
if (user && user.role === USER_ROLE.ADMIN) {
return user
}
return null
}
export function redirectToLogin(req: any, res: any) {
const redirectTargetUrl = `${getBaseURL()}/login?redirect=${encodeURIComponent(
req.url
)}`
res.writeHead(303, {
Location: redirectTargetUrl,
})
res.end()
}

1530
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,6 +16,7 @@
"ics": "2.31.0",
"mongoose": "5.13.9",
"next": "11.1.2",
"next-auth": "^4.0.0-beta.2",
"next-iron-session": "4.1.14",
"next-mdx-remote": "3.0.4",
"p-retry": "4.6.1",

View File

@@ -1,14 +1,40 @@
import '../styles/index.css'
import UserContext from '../context/user'
import { useEffect } from 'react';
export default function MyApp({ Component, pageProps }) {
const { username, role } = pageProps?.user || {}
import { useSession, signIn, SessionProvider } from "next-auth/react"
import '../styles/index.css'
function Auth({ children }) {
const { data: session, status } = useSession()
const isUser = !!session?.user
useEffect(() => {
if (status === 'loading') return // Do nothing while loading
if (!isUser) signIn() // If not authenticated, force log in
}, [isUser, status])
if (isUser) {
return children
}
// Session is being fetched, or no user.
// If no user, useEffect() will redirect.
return <div>Loading...</div>
}
export default function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<div className="wrapper">
<UserContext.Provider value={{ username, role }}>
<Component {...pageProps} />
</UserContext.Provider>
<SessionProvider session={session}>
{Component.auth ? (
<Auth>
<Component {...pageProps} />
</Auth>
) : (
<Component {...pageProps} />
)}
</SessionProvider>
</div>
)
}

View File

@@ -1,85 +1,74 @@
import React from 'react'
import Link from 'next/link'
import Footer from '../../components/footer'
import Header from '../../components/header'
import { useSession } from 'next-auth/react'
import Layout from '../../components/layout';
import Denied from '../../components/denied';
import { daysFormatFrontend } from '../../helpers/date'
import withSession, { isAdminSession, redirectToLogin } from '../../lib/session'
import { getServerSideRecentBookings } from '../../lib/getServerSideProps'
export const getServerSideProps = withSession(async (context) => {
const { req, res } = context
const adminUser = isAdminSession(req)
if (!adminUser) {
redirectToLogin(req, res)
return { props: {} }
}
const serverSideRecentBookingProps = await getServerSideRecentBookings()
return {
props: {
...serverSideRecentBookingProps.props,
user: adminUser,
},
}
})
export const getServerSideProps = getServerSideRecentBookings;
export default function AdminRecentBookings({ bookings }) {
const { data: session, status} = useSession();
if (typeof window !== 'undefined' && status === "loading") return null;
if (!session) { return <Layout><Denied /></Layout> }
if (!bookings) return null;
return (
<>
<Header />
<main className="main py-3">
{bookings.map((booking: any) => (
<div
key={booking.uuid}
className="mb-6 bg-white shadow overflow-hidden sm:rounded-lg"
>
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
<Link href={`/admin/bookings/${booking.uuid}`}>
<a className="link">Booking {booking.uuid}</a>
</Link>
</h3>
<p className="mt-1 max-w-2xl text-sm text-gray-500">
Last updated {new Date(booking.updatedAt).toLocaleString()}
</p>
</div>
<div className="border-t border-gray-200">
<dl>
<div className="bg-gray-100 px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">
Buchungszeitraum
</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{daysFormatFrontend(booking.days)}
</dd>
</div>
<div className="bg-white px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Bucher</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.name}
</dd>
</div>
<div className="bg-gray-100 px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Email</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.email}
</dd>
</div>
<div className="bg-white px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Status</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.status}
</dd>
</div>
</dl>
</div>
<Layout>
{bookings.map((booking: any) => (
<div
key={booking.uuid}
className="mb-6 bg-white shadow overflow-hidden sm:rounded-lg"
>
<div className="px-4 py-5 sm:px-6">
<h3 className="text-lg leading-6 font-medium text-gray-900">
<Link href={`/admin/bookings/${booking.uuid}`}>
<a className="link">Booking {booking.uuid}</a>
</Link>
</h3>
<p className="mt-1 max-w-2xl text-sm text-gray-500">
Last updated {new Date(booking.updatedAt).toLocaleString()}
</p>
</div>
))}
</main>
<Footer />
</>
<div className="border-t border-gray-200">
<dl>
<div className="bg-gray-100 px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">
Buchungszeitraum
</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{daysFormatFrontend(booking.days)}
</dd>
</div>
<div className="bg-white px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Bucher</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.name}
</dd>
</div>
<div className="bg-gray-100 px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Email</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.email}
</dd>
</div>
<div className="bg-white px-2 py-3 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6">
<dt className="text-sm font-medium text-gray-500">Status</dt>
<dd className="mt-1 text-sm text-gray-900 sm:mt-0 sm:col-span-2">
{booking.status}
</dd>
</div>
</dl>
</div>
</div>
))}
</Layout>
)
}
AdminRecentBookings.auth = true

View File

@@ -0,0 +1,23 @@
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
import EmailProvider from "next-auth/providers/email"
export default NextAuth({
providers: [
EmailProvider({
server: {
host: "smtp.sendgrid.net",
port: 587,
auth: {
user: "apikey",
pass: process.env.SENDGRID_API_KEY,
},
},
from: process.env.FROM_EMAIL
}),
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
})

View File

@@ -1,27 +0,0 @@
import { authenticateAdmin } from '../../lib/authenticate'
import withSession from '../../lib/session'
async function loginHandler(req: any, res: any): Promise<void> {
const { method } = req
switch (method) {
case 'POST':
const { username, password } = req.body
if (!authenticateAdmin({ username, password })) {
res.status(401).end()
return
}
const userData = { username, role: 'admin' }
req.session.set('user', userData)
await req.session.save()
res.json({ message: 'Authenticated', user: userData })
break
default:
res.setHeader('Allow', ['POST'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
export default withSession(loginHandler)

View File

@@ -1,16 +0,0 @@
import withSession from '../../lib/session'
async function loginHandler(req: any, res: any): Promise<void> {
const { method } = req
switch (method) {
case 'POST':
req.session.destroy()
res.json({ message: 'Logged out' })
break
default:
res.setHeader('Allow', ['POST'])
res.status(405).end(`Method ${method} Not Allowed`)
}
}
export default withSession(loginHandler)

View File

@@ -1,76 +0,0 @@
import React, { useState } from 'react'
import { useRouter } from 'next/router'
import Footer from '../components/footer'
import Header from '../components/header'
import Input from '../components/input'
import { getBaseURL } from '../helpers/url'
export default function Login() {
const router = useRouter()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const isValid = !!username.length && !!password.length
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault()
try {
await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username,
password,
}),
}).then((response) => {
if (!response.ok) {
console.error('Unable to login', response.status, response.statusText)
return
}
const redirect = Array.isArray(router.query?.redirect)
? router.query.redirect[0]
: router.query?.redirect
router.push(redirect || getBaseURL())
})
} catch (error) {
console.error('Unable to login', error)
}
}
return (
<>
<Header />
<main className="main w-64">
<form className="form" onSubmit={onSubmit}>
<Input
label="Username"
name="username"
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setUsername(event.target.value)
}
/>
<Input
label="Password"
name="password"
type="password"
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setPassword(event.target.value)
}
/>
<button
type="submit"
className="btn btn-blue ml-0"
disabled={!isValid}
>
Login
</button>
</form>
</main>
<Footer />
</>
)
}