Skip to content

Commit

Permalink
Fix discord login issues (#106)
Browse files Browse the repository at this point in the history
* Bump a lot of deps

* Adjust docker build tag generation

* Use branch and pr as ref value for tag creation

* Do not optimize images

* Adjust discord provider config for auth.js

* Add more error handling to auth.ts

* Display correct error message
  • Loading branch information
Yasamato authored Dec 4, 2024
1 parent 8f09b2d commit 0c632da
Show file tree
Hide file tree
Showing 98 changed files with 2,493 additions and 1,843 deletions.
5 changes: 3 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ NEXT_PUBLIC_SITE_NAME="The Anime Index"
# remove trailing slash !!!
NEXT_PUBLIC_DOMAIN="https://piracy.moe"
NEXTAUTH_URL="https://piracy.moe"
AUTH_TRUST_HOST="true"

# secret for session hash validations
NEXTAUTH_SECRET="generate_a_real_long_and_secure_random_string"
Expand All @@ -26,8 +27,8 @@ PING_DEBUG="false"

# Discord OAuth2 credits
# for more info read https://discord.com/developers/docs/topics/oauth2
DISCORD_CLIENT_ID="your_discord_oauth_client_id"
DISCORD_CLIENT_SECRET="your_discord_oauth_client_secret"
AUTH_DISCORD_ID="your_discord_oauth_client_id"
AUTH_DISCORD_SECRET="your_discord_oauth_client_secret"
DISCORD_BOT_TOKEN="your_discord_bot_token"

# Setup login whitelist
Expand Down
8 changes: 5 additions & 3 deletions .github/workflows/publish-docker-image.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,25 @@ jobs:
uses: actions/checkout@v3

- name: Log in to the Container registry
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
# set latest tag for default branch
type=raw,value=latest,enable={{is_default_branch}}
type=ref,event=branch
type=ref,event=pr
- name: Build and push Docker image
uses: docker/build-push-action@v3
uses: docker/build-push-action@v6
with:
context: .
push: true
Expand Down
10 changes: 9 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:22.3
FROM node:23.3
WORKDIR /app

# We use the image browserless/chrome instead of having our own chrome instance here
Expand All @@ -12,6 +12,7 @@ ENV NEXT_PUBLIC_SITE_NAME="The Anime Index"
# connection urls
ENV NEXTAUTH_URL="https://theindex.moe"
ENV NEXT_PUBLIC_DOMAIN="https://theindex.moe"
ENV AUTH_TRUST_HOST="true"
ENV DATABASE_URL="mongodb://mongo:27017/index"
ENV CACHE_URL="redis://redis:6379"
ENV AUDIT_WEBHOOK=""
Expand Down Expand Up @@ -40,6 +41,13 @@ COPY package.json package-lock.json ./
RUN npm ci
ENV PATH /app/node_modules/.bin:$PATH

# manully add .js to import as something is messed up...
RUN sed -i 's/next\/server/next\/server.js/' /app/node_modules/next-auth/lib/env.js \
&& sed -i 's/next\/server/next\/server.js/' /app/node_modules/next-auth/lib/index.js \
&& sed -i 's/next\/headers/next\/headers.js/' /app/node_modules/next-auth/lib/index.js \
&& sed -i 's/next\/headers/next\/headers.js/' /app/node_modules/next-auth/lib/actions.js \
&& sed -i 's/next\/navigation/next\/navigation.js/' /app/node_modules/next-auth/lib/actions.js

# build the web app
COPY . .

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ Here is a collection of the possible environment variables with their default va
| `CACHE_URL` | Connection string for the redis cache database | `"redis://redis:6379"` |
| `CHROME_URL` | WebSocket URL to a running chrome instance | `"ws://chrome:3300"` |
| `AUDIT_WEBHOOK` | WebHook-URL for audit-log, leave empty to disable support | `""` |
| `DISCORD_CLIENT_ID` | Discord OAuth2 client ID | `"your_discord_oauth_client_id"` |
| `DISCORD_CLIENT_SECRET` | Discord OAuth2 client secret | `"your_discord_oauth_client_secret"` |
| `AUTH_DISCORD_ID` | Discord OAuth2 client ID | `"your_discord_oauth_client_id"` |
| `AUTH_DISCORD_SECRET` | Discord OAuth2 client secret | `"your_discord_oauth_client_secret"` |
| `DISCORD_BOT_TOKEN` | Required to access BOT resources | `"your_discord_bot_token"` |
| `SETUP_WHITELIST_DISCORD_ID` | If you need help getting your id, check out this [guide](https://wiki.discord.id/obtain-ids/desktop) | `"your_discord_id"` |

Expand Down
3 changes: 3 additions & 0 deletions app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { handlers } from '../../../../auth'

export const { GET, POST } = handlers
131 changes: 131 additions & 0 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import NextAuth from 'next-auth'
import Discord from 'next-auth/providers/discord'
import { addUser } from './lib/db/users'
import { AccountType, type User } from './types/User'
import { MongoDBAdapter } from '@auth/mongodb-adapter'
import { dbClient } from './lib/db/db'
import { ObjectId } from 'mongodb'
import type { NextAuthConfig } from 'next-auth'
import { findOneTyped } from './lib/db/dbTyped'
import { Types } from './types/Components'

export const authOptions: NextAuthConfig = {
providers: [Discord],
theme: {
colorScheme: 'dark',
brandColor: '#0d6efd',
logo: process.env.NEXT_PUBLIC_DOMAIN + '/icons/logo.png',
},
callbacks: {
// we want to access the user id
async session({ session, user }) {
if (user) {
const id = user.id.toString()
session.user.uid = id

const userData = (await findOneTyped(Types.user, id)) as User
// create user account if not found
if (userData === null) {
console.log(
'User',
user.name,
id,
'could not be found, creating new user'
)
await addUser({
uid: id,
accountType: AccountType.user,
}).catch((error) => {
console.error(
'Failed to add new user in session callback',
user,
'due to',
error
)
})

session.user.accountType = AccountType.user
} else {
session.user.accountType = userData.accountType
}
} else {
console.warn('session call with no user provided')
}
return session
},
},
events: {
async signIn({ user, account, profile, isNewUser }) {
if (typeof user === 'undefined' || user === null) {
console.error('Sign In event with no user provided:', user)
return
}

if (isNewUser) {
console.log('Creating new user', user.name)
const accountType =
typeof account !== 'undefined' &&
account !== null &&
typeof process.env.SETUP_WHITELIST_DISCORD_ID !== 'undefined' &&
process.env.SETUP_WHITELIST_DISCORD_ID !== '' &&
account.providerAccountId === process.env.SETUP_WHITELIST_DISCORD_ID
? AccountType.admin
: AccountType.user
if (typeof user.id !== 'undefined') {
await addUser({
uid: user.id.toString(),
accountType,
}).catch((error) => {
console.error('Failed to add new user', user, 'due to', error)
})
} else {
console.error('Unable to create new user', user, 'due to missing id')
}
} else if (
typeof profile !== 'undefined' &&
user.image !== profile.image
) {
if (typeof user.id !== 'undefined') {
// update new discord image on login
const db = (await dbClient).db('index')
await db
.collection('nextauth_users')
.updateOne(
{ _id: new ObjectId(user.id) },
{
$set: {
image: profile.image,
},
}
)
.catch((error) => {
console.error(
'Unable to update profile image of user',
user,
'due to',
error
)
})
} else {
console.log(
'Unable to update user profile picutre',
user,
'due to missing id'
)
}
}
},
},

// A database is optional, but required to persist accounts in a database
adapter: MongoDBAdapter(dbClient, {
collections: {
Users: 'nextauth_users',
Sessions: 'nextauth_sessions',
Accounts: 'nextauth_accounts',
},
}),
secret: process.env.NEXTAUTH_SECRET,
}

export const { auth, handlers, signIn, signOut } = NextAuth(authOptions)
Binary file removed bun.lockb
Binary file not shown.
48 changes: 32 additions & 16 deletions components/CardRowView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,38 @@ import UserCard from './cards/UserCard'
import UserRow from './rows/UserRow'
import ListCard from './cards/ListCard'
import ListRow from './rows/ListRow'
import { Column } from '../types/Column'
import { User } from '../types/User'
import { Item } from '../types/Item'
import { Collection } from '../types/Collection'
import { Library } from '../types/Library'
import { List } from '../types/List'
import { Types } from '../types/Components'

type Props = {
cardView: boolean,
type: Types,
content: User | Item | List | Collection | Column | Library
columns: Column[]
move?: (order: number) => void
add?: () => void
remove?: () => void
}

const CardRowView = ({
cardView = true,
type,
content,
add = null,
move = null,
remove = null,
add,
move,
remove,
columns = [],
}) => {
}: Props) => {
if (type === Types.item) {
if (cardView) {
return (
<ItemCard
item={content}
item={content as Item}
columns={columns}
add={add}
move={move}
Expand All @@ -36,7 +52,7 @@ const CardRowView = ({
}
return (
<ItemRow
item={content}
item={content as Item}
columns={columns}
add={add}
move={move}
Expand All @@ -46,15 +62,15 @@ const CardRowView = ({
} else if (type === Types.column) {
if (cardView) {
return (
<ColumnCard column={content} add={add} move={move} remove={remove} />
<ColumnCard column={content as Column} add={add} move={move} remove={remove} />
)
}
return <ColumnRow column={content} add={add} move={move} remove={remove} />
return <ColumnRow column={content as Column} add={add} move={move} remove={remove} />
} else if (type === Types.collection) {
if (cardView) {
return (
<CollectionCard
collection={content}
collection={content as Collection}
add={add}
move={move}
remove={remove}
Expand All @@ -63,7 +79,7 @@ const CardRowView = ({
}
return (
<CollectionRow
collection={content}
collection={content as Collection}
add={add}
move={move}
remove={remove}
Expand All @@ -72,22 +88,22 @@ const CardRowView = ({
} else if (type === Types.library) {
if (cardView) {
return (
<LibraryCard library={content} add={add} move={move} remove={remove} />
<LibraryCard library={content as Library} add={add} move={move} remove={remove} />
)
}
return (
<LibraryRow library={content} add={add} move={move} remove={remove} />
<LibraryRow library={content as Library} add={add} move={move} remove={remove} />
)
} else if (type === Types.user) {
if (cardView) {
return <UserCard user={content} add={add} move={move} remove={remove} />
return <UserCard user={content as User} add={add} move={move} remove={remove} />
}
return <UserRow user={content} add={add} move={move} remove={remove} />
return <UserRow user={content as User} add={add} move={move} remove={remove} />
} else if (type === Types.list) {
if (cardView) {
return <ListCard list={content} add={add} move={move} remove={remove} />
return <ListCard list={content as List} add={add} move={move} remove={remove} />
}
return <ListRow list={content} add={add} move={move} remove={remove} />
return <ListRow list={content as List} add={add} move={move} remove={remove} />
} else {
console.error('Unknown type of content:', type)
}
Expand Down
12 changes: 7 additions & 5 deletions components/boards/Board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ const Board: FC<Props> = ({
)
updateContent(newContent, newUnselectedContent)
}
: null
: undefined
}
move={
moveAllowed
Expand All @@ -231,7 +231,7 @@ const Board: FC<Props> = ({
updateContent(copy, unselectedContent)
}
}
: null
: undefined
}
remove={
removeAllowed
Expand Down Expand Up @@ -263,7 +263,7 @@ const Board: FC<Props> = ({
updateContent(newContent, newUnselectedContent)
}
}
: null
: undefined
}
columns={compactView ? [] : columns}
/>
Expand Down Expand Up @@ -365,8 +365,10 @@ const Board: FC<Props> = ({
(option) => option.name === event.target.value
)
console.log('Changed sorting to', newSortOption)
setSortOption(newSortOption)
setContent(content.sort(newSortOption.sort))
if (typeof newSortOption !== 'undefined') {
setSortOption(newSortOption)
setContent(content.sort(newSortOption.sort))
}
}}
/>
)}
Expand Down
1 change: 1 addition & 0 deletions components/cards/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ const Card: FC<Props> = ({
alt='...'
width={128}
height={128}
unoptimized
/>
</Link>
</div>
Expand Down
6 changes: 3 additions & 3 deletions components/cards/CollectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ type Props = {

const CollectionCard: FC<Props> = ({
collection,
add = null,
remove = null,
move = null,
add,
remove,
move,
}) => {
return (
<Card
Expand Down
Loading

0 comments on commit 0c632da

Please sign in to comment.