|
1 | 1 | import NextAuth from 'next-auth' |
| 2 | +import { mergeDeepRight } from 'ramda' |
| 3 | +const db = require('../../../lib/db') |
2 | 4 |
|
3 | 5 | export const authOptions = { |
| 6 | + // Configure one or more authentication providers |
4 | 7 | providers: [ |
5 | 8 | { |
6 | | - id: 'openstreetmap', |
7 | | - name: 'openstreetmap', |
8 | | - clientId: process.env.OSM_CONSUMER_KEY, |
9 | | - clientSecret: process.env.OSM_CONSUMER_SECRET, |
| 9 | + id: 'osm-teams', |
| 10 | + name: 'OSM Teams', |
10 | 11 | type: 'oauth', |
11 | | - authorization: { |
12 | | - url: 'https://www.openstreetmap.org/oauth2/authorize', |
13 | | - params: { |
14 | | - scope: 'read_prefs', |
15 | | - }, |
16 | | - }, |
17 | | - token: 'https://www.openstreetmap.org/oauth2/token', |
18 | | - userinfo: 'https://api.openstreetmap.org/api/0.6/user/details.json', |
19 | | - profile({ user }) { |
| 12 | + wellKnown: 'https://mapping.team/hyauth/.well-known/openid-configuration', |
| 13 | + authorization: { params: { scope: 'openid offline' } }, |
| 14 | + idToken: true, |
| 15 | + async profile(profile) { |
20 | 16 | return { |
21 | | - id: user.id, |
22 | | - name: user.display_name, |
23 | | - image: user.img?.href, |
| 17 | + id: profile.sub, |
| 18 | + name: profile.preferred_username, |
| 19 | + image: profile.picture, |
24 | 20 | } |
25 | 21 | }, |
| 22 | + clientId: process.env.OSM_TEAMS_CLIENT_ID, |
| 23 | + clientSecret: process.env.OSM_TEAMS_CLIENT_SECRET, |
26 | 24 | }, |
27 | 25 | ], |
28 | 26 | callbacks: { |
| 27 | + async jwt({ token, account, profile }) { |
| 28 | + // Persist the OAuth access_token and or the user id to the token right after signin |
| 29 | + if (account) { |
| 30 | + token.accessToken = account.access_token |
| 31 | + token.userId = profile.sub |
| 32 | + } |
| 33 | + return token |
| 34 | + }, |
29 | 35 | async session({ session, token }) { |
30 | | - // Add user id to session |
31 | | - const userId = parseInt(token.sub) |
32 | | - session.user_id = userId |
| 36 | + // Send properties to the client, like an access_token and user id from a provider. |
| 37 | + session.accessToken = token.accessToken |
| 38 | + session.user_id = token.userId |
33 | 39 | return session |
34 | 40 | }, |
35 | 41 | }, |
| 42 | + |
| 43 | + events: { |
| 44 | + async signIn({ profile }) { |
| 45 | + // On successful sign in we should persist the user to the database |
| 46 | + let [user] = await db('users').where('id', profile.id) |
| 47 | + if (user) { |
| 48 | + const newProfile = mergeDeepRight(user.profile, profile) |
| 49 | + await db('users') |
| 50 | + .where('id', profile.id) |
| 51 | + .update({ |
| 52 | + profile: JSON.stringify(newProfile), |
| 53 | + }) |
| 54 | + } else { |
| 55 | + await db('users').insert({ |
| 56 | + id: profile.id, |
| 57 | + profile: JSON.stringify(profile), |
| 58 | + }) |
| 59 | + } |
| 60 | + }, |
| 61 | + }, |
36 | 62 | } |
37 | 63 |
|
38 | 64 | export default NextAuth(authOptions) |
0 commit comments