Skip to content

Commit

Permalink
Revert "remove NextAuth"
Browse files Browse the repository at this point in the history
This reverts commit 4eaceab.
  • Loading branch information
wtLau committed Apr 12, 2024
1 parent dbf2b0d commit f82da00
Show file tree
Hide file tree
Showing 8 changed files with 10,351 additions and 14,360 deletions.
1 change: 0 additions & 1 deletion .yarnrc.yml

This file was deleted.

31 changes: 23 additions & 8 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'styles/global.css'

import { MDXProvider } from '@mdx-js/react'
import { CssBaseline } from '@mui/material'
import { Provider as NextAuthProvider } from 'next-auth/client'
import type { AppProps } from 'next/app'
import { useRouter } from 'next/dist/client/router'
import React, { useEffect } from 'react'
Expand Down Expand Up @@ -32,16 +33,30 @@ function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Head />
<ThemeCustomProvider theme={theme}>
<CssBaseline />
<AppLayout>
<MDXProvider components={MDXComponents}>
<Component {...pageProps} />
</MDXProvider>
</AppLayout>
</ThemeCustomProvider>
<NextAuthProvider session={pageProps.session}>
<ThemeCustomProvider theme={theme}>
<CssBaseline />
<AppLayout>
<MDXProvider components={MDXComponents}>
<Component {...pageProps} />
</MDXProvider>
</AppLayout>
</ThemeCustomProvider>
</NextAuthProvider>
</>
)
}

// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }

export default MyApp
8 changes: 5 additions & 3 deletions pages/about.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Typography, Button, Grid } from '@mui/material'
import { useSession } from 'next-auth/client'
import Image from 'next/image'
import React, { useState, useEffect } from 'react'

Expand All @@ -9,8 +10,9 @@ import { companyData } from '@data/companyData'
import { skillsData, TSkills } from '@data/skillsData'

const About = () => {
const [session] = useSession()
const [skills, setSkills] = useState<TSkills[]>([])
const userName = 'stranger'
const userName = session?.user?.name || 'stranger'

useEffect(() => {
setSkills(skillsData)
Expand Down Expand Up @@ -39,8 +41,8 @@ const About = () => {
/>
<Grid item xs={12}>
<Typography paragraph>
Hi, ${userName}. My name is Brian, and I am currently living in
North Vancouver, Canada.
{session && `Hi, ${userName}.`} My name is Brian, and I am
currently living in North Vancouver, Canada.
</Typography>

<Typography paragraph>
Expand Down
99 changes: 99 additions & 0 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
providers: [
// Providers.Email({
// server: process.env.EMAIL_SERVER,
// from: process.env.EMAIL_FROM,
// }),
Providers.GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
Providers.Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
Providers.LinkedIn({
clientId: process.env.LINKEDIN_ID,
clientSecret: process.env.LINKEDIN_SECRET,
}),
],
// Database optional. MySQL, Maria DB, Postgres and MongoDB are supported.
// https://next-auth.js.org/configuration/databases
//
// Notes:
// * You must to install an appropriate node_module for your database
// * The Email provider requires a database (OAuth providers do not)
// database: process.env.DATABASE_URL,

// The secret should be set to a reasonably long random string.
// It is used to sign cookies and to sign and encrypt JSON Web Tokens, unless
// a separate secret is defined explicitly for encrypting the JWT.
secret: process.env.SECRET_COOKIE_PASSWORD,

session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
jwt: true,

// Seconds - How long until an idle session expires and is no longer valid.
// maxAge: 30 * 24 * 60 * 60, // 30 days

// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
// updateAge: 24 * 60 * 60, // 24 hours
},

// JSON Web tokens are only used for sessions if the `jwt: true` session
// option is set - or by default if no database is specified.
// https://next-auth.js.org/configuration/options#jwt
jwt: {
// A secret to use for key generation (you should set this explicitly)
// secret: 'INp8IvdIyeMcoGAgFGoA61DdBglwwSqnXJZkgz8PSnw',
// Set to true to use encryption (default: false)
// encryption: true,
// You can define your own encode/decode functions for signing and encryption
// if you want to override the default behaviour.
// encode: async ({ secret, token, maxAge }) => {},
// decode: async ({ secret, token, maxAge }) => {},
},

// You can define custom pages to override the built-in ones. These will be regular Next.js pages
// so ensure that they are placed outside of the '/api' folder, e.g. signIn: '/auth/mycustom-signin'
// The routes shown here are the default URLs that will be used when a custom
// pages is not specified for that route.
// https://next-auth.js.org/configuration/pages
pages: {
// signIn: '/auth/signin', // Displays signin buttons
// signOut: '/auth/signout', // Displays form with sign out button
// error: '/auth/error', // Error code passed in query string as ?error=
// verifyRequest: '/auth/verify-request', // Used for check email page
// newUser: null // If set, new users will be directed here on first sign in
},

// Callbacks are asynchronous functions you can use to control what happens
// when an action is performed.
// https://next-auth.js.org/configuration/callbacks
callbacks: {
// async signIn(user, account, profile) { return true },
async redirect(url, baseUrl) {
return baseUrl
},
// async session(session, user) { return session },
// async jwt(token, user, account, profile, isNewUser) { return token }
},

// Events are useful for logging
// https://next-auth.js.org/configuration/events
events: {},

// Enable debug messages in the console if you are having problems
debug: false,
})
19 changes: 19 additions & 0 deletions pages/api/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// This is an example of to protect an API route
import { NextApiRequest, NextApiResponse } from 'next'
import { getSession } from 'next-auth/client'

const user = async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession({ req })

if (session) {
res.send({
content:
'This is protected content. You can access this content because you are signed in.',
})
} else {
res.send({
error: 'You must be sign in to view the protected content on this page.',
})
}
}
export default user
4 changes: 3 additions & 1 deletion pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Typography } from '@mui/material'
import Grid from '@mui/material/Grid'
import { styled } from '@mui/material/styles'
import { useSession } from 'next-auth/client'
import { FC } from 'react'

import { Link } from '@components/ui'
Expand All @@ -9,7 +10,8 @@ const StyledGrid = styled(Grid)({
})

const Index: FC = () => {
const userName = 'stranger'
const [session] = useSession()
const userName = session?.user?.name || 'stranger'
return (
<StyledGrid container justifyContent='center' alignItems='center'>
<Grid container spacing={8} alignContent='center'>
Expand Down
42 changes: 42 additions & 0 deletions pages/profile.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Grid, Typography, CircularProgress } from '@mui/material'
import { useSession } from 'next-auth/client'
import React, { useEffect, useState } from 'react'

const Profile = () => {
const [content, setContent] = useState()
const [session, loading] = useSession()
const userName = session?.user?.name
// Fetch content from protected route
useEffect(() => {
const fetchData = async () => {
const res = await fetch('/api/user')
const json = await res.json()
if (json.content) {
setContent(json.content)
}
}
fetchData()
}, [session])

if (loading) {
return <CircularProgress />
}

// If no session exists, display access denied message
if (!session) {
return <Typography>Access Denied</Typography>
}

return (
<Grid>
<h1>Protected Page</h1>
<p>{`You're sign in as`}</p>

<strong>{userName || '\u00a0'}</strong>
<br />
<strong>{content}</strong>
</Grid>
)
}

export default Profile
Loading

0 comments on commit f82da00

Please sign in to comment.