采用Next和Next Auth实现将功能与Slack集成
首先,需要在Slack上创建一个App并获得下列两个值:Client ID和Client Secret。
接下来,可以使用Next Auth库安装必要的依赖项,其中包括注意事项中提到的Slack Provider模块。如下所示:
npm install next-auth
npm install @next-auth/slack
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
const options = {
// Configure one or more authentication providers
providers: [
Providers.Slack({
clientId: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET
})
// ... add more providers here
]
}
export default (req, res) => NextAuth(req, res, options)
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import Adapters from 'next-auth/adapters'
const options = {
// Configure one or more authentication providers
providers: [
Providers.Slack({
clientId: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET
})
// ... add more providers here
],
adapter: Adapters.Prisma.Adapter({ prisma })
}
export default (req, res) => NextAuth(req, res, options)
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
if (!session) {
res.status(401).send('Unauthorised')
return
}
// Do something with session.user object, or just...
res.send('Hello world')
}
import { signIn, signOut, useSession } from 'next-auth/client'
import { useEffect } from 'react'
export default function Home() {
const [ session, loading ] = useSession()
useEffect(() => {
const fetchData = async () => {
if (session) {
const res = await fetch('/api/slack')
const data = await res.json()
console.log(data)
}
}
fetchData()
}, [session])
if (loading) {
return Loading...
}
return <>
{session && <>
Signed in as {session.user.email}
>
}
{!session && <>
Not signed in
>
}
>
}
通过这个示例,我们可以使用Next和Next Auth