Skip to content

Commit

Permalink
saving authentication data
Browse files Browse the repository at this point in the history
  • Loading branch information
paolini committed Jun 25, 2024
1 parent 03c168a commit 24a2d44
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 17 deletions.
13 changes: 9 additions & 4 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import NextAuth, {User, Account, Profile} from "next-auth"
import NextAuth, {User, Account, Profile, AuthOptions} from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"

Expand All @@ -12,8 +12,7 @@ const {
DATABASE_NAME,
} = config


const handler = NextAuth({
export const authOptions: AuthOptions = {
providers: discoverProviders(),
callbacks: {
async signIn({ account, profile }) {
Expand All @@ -26,10 +25,16 @@ const handler = NextAuth({
return true
}
},
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 days
},
adapter: MongoDBAdapter(clientPromise, {
databaseName: DATABASE_NAME,
})
})
}

const handler = NextAuth(authOptions)

export {handler as GET, handler as POST}

Expand Down
4 changes: 3 additions & 1 deletion app/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ const config = singleton || (() => {
console.log('config loaded: ',
Object.fromEntries(Object.entries(config).map(
([key, value]) => {
if (key.toUpperCase().includes('SECRET')) value=value.substring(0,2) + '....' + value.substring(value.length-2)
if (key.toUpperCase().includes('SECRET')) {
if (value) value=value.substring(0,2) + '....' + value.substring(value.length-2)
}
return [key, value]
})))
return config
Expand Down
57 changes: 49 additions & 8 deletions app/graphql/route.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,52 @@
import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { gql } from 'graphql-tag'

import { getToken } from "next-auth/jwt"
import clientPromise from "../db"
import { NextApiRequest, NextApiResponse } from 'next'

type Context = {
req: NextApiRequest
res: NextApiResponse
user?: {
email: string
name: string
picture: string
id: string
}
}

const resolvers = {
Query: {
hello: () => 'world',
/*
account: async (email: string, context: any) => {
const client = await clientPromise
console.log("query context:", context)
try {
await client.connect()
const account = client.db("coffee").collection("account")
const result = await account.find({}).toArray()
return result
} catch(error) {
console.error("Error in history function:", error)
} finally {
await client.close()
}
} */
},
Mutation: {
post: async(_: any, {count}: any, context: any) => {
coffee: async(_: any, {count}: {count: number}, context: Context) => {
if (!context.user) throw new Error("not logged in")
const client = await clientPromise
console.log("mutation context:", context)
try {
await client.connect()
const account = client.db("coffee").collection("account")
const result = await account.insertOne({
count,
amountCents: count * 20,
description: "coffee",
email: context.user.email,
timestamp: new Date()
})
return "ok!"
Expand All @@ -32,21 +62,32 @@ const resolvers = {
const typeDefs = gql`
type Query {
hello: String
# account: [String]
}
type Mutation {
post(count: Int!): String
coffee(count: Int!): String
}
`;

const server = new ApolloServer({
const server = new ApolloServer<Context>({
resolvers,
typeDefs,
});

const handler = startServerAndCreateNextHandler(server, {
const handler = startServerAndCreateNextHandler<NextApiRequest,Context>(server, {
context: async (req, res) => {
console.log("context:", req, res)
return { req, res, user: null }
const token = await getToken({ req })
let ctx: Context = { req, res }
if (!token || !token.email) return ctx // not logged in
return {
...ctx,
user: {
email: token.email,
name: token.name || '',
picture: token.picture || '',
id: token.sub || '',
}
}
}
});

Expand Down
28 changes: 24 additions & 4 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { useState } from 'react'
import { useSession, signIn, signOut } from 'next-auth/react'
import { SessionProvider } from 'next-auth/react'
import './globals.css'; // Import global styles if you have them
import { Session } from 'inspector';

export default function Home() {
return <SessionProvider>
Expand All @@ -23,21 +22,27 @@ function Auth() {
</>
} else {
return <>
<p>not signed in</p>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() => signIn()}
>sign in</button>
>accedi</button>
</>
}
}

function CoffeeForm() {
const [count, setCount] = useState(1)
const { data: session } = useSession()
const [ messages, setMessages ] = useState<string[]>([])

if (!session?.user) {
return <></>
}

return <main>
<h1>dm-coffee</h1>
<form>
<Messages messages={messages} setMessages={setMessages} />
<div className="grid gap-6 mb-6 md:grid-cols-1">
<div>
<label
Expand Down Expand Up @@ -79,7 +84,7 @@ function CoffeeForm() {
e.preventDefault()
const query = `
mutation PostMutation($count: Int!) {
post(count: $count)
coffee(count: $count)
}`

const variables = { count }
Expand All @@ -97,6 +102,21 @@ function CoffeeForm() {
}

const data = await response.json()
console.log("response", data)

if (data?.errors?.length > 0) {
data.errors.forEach((error: {message:string}) => {
setMessages(messages => [...messages, error.message])
})
}
}
}

function Messages({messages, setMessages}:{
messages: string[],
setMessages: (messages: string[]) => void
}) {
return <>
{messages.map((message, i) => <p key={i}>{message}</p>)}
</>
}

0 comments on commit 24a2d44

Please sign in to comment.