mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-03 06:27:11 +01:00
move to next-auth
This commit is contained in:
committed by
Thomas Ruoff
parent
9f4180388b
commit
b257bc8258
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
23
pages/api/auth/[...nextauth].ts
Normal file
23
pages/api/auth/[...nextauth].ts
Normal 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,
|
||||
}),
|
||||
],
|
||||
})
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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 />
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user