mirror of
https://github.com/tomru/pfadi-bussle.git
synced 2026-03-04 23:17:12 +01:00
move to next-auth
This commit is contained in:
committed by
Thomas Ruoff
parent
9f4180388b
commit
b257bc8258
16
components/denied.tsx
Normal file
16
components/denied.tsx
Normal 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>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,28 +1,19 @@
|
|||||||
import { useRouter } from 'next/router'
|
import { useSession, signOut } from 'next-auth/react'
|
||||||
import { useContext } from 'react'
|
|
||||||
|
|
||||||
import UserContext from '../context/user'
|
|
||||||
import fetch from '../helpers/fetch'
|
|
||||||
|
|
||||||
export default function User() {
|
export default function User() {
|
||||||
const router = useRouter()
|
const { data, status } = useSession();
|
||||||
const { username, role } = useContext(UserContext)
|
|
||||||
|
|
||||||
if (!username || !role) {
|
if (status === 'loading' || !data?.user?.email) {
|
||||||
return <div />
|
return null;
|
||||||
}
|
|
||||||
|
|
||||||
const onClickLogout = async () => {
|
|
||||||
await fetch('/api/logout', { method: 'POST' })
|
|
||||||
router.reload()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="font-extrabold bg-red-400 px-2 py-1 mr-3 rounded-sm">
|
<div className="font-extrabold bg-red-400 px-2 py-1 mr-3 rounded-sm">
|
||||||
{username}
|
{data.user.email}
|
||||||
</div>
|
</div>
|
||||||
<button onClick={onClickLogout} className="btn btn-blue">
|
<button onClick={() => signOut()} className="btn btn-blue">
|
||||||
Logout
|
Logout
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -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
1530
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,7 @@
|
|||||||
"ics": "2.31.0",
|
"ics": "2.31.0",
|
||||||
"mongoose": "5.13.9",
|
"mongoose": "5.13.9",
|
||||||
"next": "11.1.2",
|
"next": "11.1.2",
|
||||||
|
"next-auth": "^4.0.0-beta.2",
|
||||||
"next-iron-session": "4.1.14",
|
"next-iron-session": "4.1.14",
|
||||||
"next-mdx-remote": "3.0.4",
|
"next-mdx-remote": "3.0.4",
|
||||||
"p-retry": "4.6.1",
|
"p-retry": "4.6.1",
|
||||||
|
|||||||
@@ -1,14 +1,40 @@
|
|||||||
import '../styles/index.css'
|
import { useEffect } from 'react';
|
||||||
import UserContext from '../context/user'
|
|
||||||
|
|
||||||
export default function MyApp({ Component, pageProps }) {
|
import { useSession, signIn, SessionProvider } from "next-auth/react"
|
||||||
const { username, role } = pageProps?.user || {}
|
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 (
|
return (
|
||||||
<div className="wrapper">
|
<div className="wrapper">
|
||||||
<UserContext.Provider value={{ username, role }}>
|
<SessionProvider session={session}>
|
||||||
|
{Component.auth ? (
|
||||||
|
<Auth>
|
||||||
<Component {...pageProps} />
|
<Component {...pageProps} />
|
||||||
</UserContext.Provider>
|
</Auth>
|
||||||
|
) : (
|
||||||
|
<Component {...pageProps} />
|
||||||
|
)}
|
||||||
|
</SessionProvider>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,36 +1,25 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import Footer from '../../components/footer'
|
import { useSession } from 'next-auth/react'
|
||||||
import Header from '../../components/header'
|
import Layout from '../../components/layout';
|
||||||
|
import Denied from '../../components/denied';
|
||||||
import { daysFormatFrontend } from '../../helpers/date'
|
import { daysFormatFrontend } from '../../helpers/date'
|
||||||
import withSession, { isAdminSession, redirectToLogin } from '../../lib/session'
|
|
||||||
|
|
||||||
import { getServerSideRecentBookings } from '../../lib/getServerSideProps'
|
import { getServerSideRecentBookings } from '../../lib/getServerSideProps'
|
||||||
|
|
||||||
export const getServerSideProps = withSession(async (context) => {
|
export const getServerSideProps = getServerSideRecentBookings;
|
||||||
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 default function AdminRecentBookings({ bookings }) {
|
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 (
|
return (
|
||||||
<>
|
<Layout>
|
||||||
<Header />
|
|
||||||
<main className="main py-3">
|
|
||||||
{bookings.map((booking: any) => (
|
{bookings.map((booking: any) => (
|
||||||
<div
|
<div
|
||||||
key={booking.uuid}
|
key={booking.uuid}
|
||||||
@@ -78,8 +67,8 @@ export default function AdminRecentBookings({ bookings }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</main>
|
</Layout>
|
||||||
<Footer />
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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