跳到內容
從 NextAuth.js v4 遷移嗎?請閱讀 我們的遷移指南.

TypeORM 轉接器

資源

設定

安裝

npm install @auth/typeorm-adapter typeorm

環境變數

AUTH_TYPEORM_CONNECTION=postgres://postgres:adminadmin@0.0.0.0:5432/db

組態設定

./auth.ts
import NextAuth from "next-auth"
import { TypeORMAdapter } from "@auth/typeorm-adapter"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: TypeORMAdapter(process.env.AUTH_TYPEORM_CONNECTION),
})

TypeORMAdapter 接受連線字串或 ConnectionOptions 物件作為其第一個參數。

進階用法

自訂模型

TypeORM 轉接器使用 Entity 類別來定義您的資料形狀。

您可以使用自訂實體檔案覆寫預設實體並新增額外欄位。

  1. 建立一個包含修改後實體的檔案
lib/entities.ts
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  OneToMany,
  ValueTransformer,
} from "typeorm"
 
const transformer: Record<"date" | "bigint", ValueTransformer> = {
  date: {
    from: (date: string | null) => date && new Date(parseInt(date, 10)),
    to: (date?: Date) => date?.valueOf().toString(),
  },
  bigint: {
    from: (bigInt: string | null) => bigInt && parseInt(bigInt, 10),
    to: (bigInt?: number) => bigInt?.toString(),
  },
}
 
@Entity({ name: "users" })
export class UserEntity {
  @PrimaryGeneratedColumn("uuid")
  id!: string
 
  @Column({ type: "varchar", nullable: true })
  name!: string | null
 
  @Column({ type: "varchar", nullable: true, unique: true })
  email!: string | null
 
  @Column({ type: "varchar", nullable: true, transformer: transformer.date })
  emailVerified!: string | null
 
  @Column({ type: "varchar", nullable: true })
  image!: string | null
 
+ @Column({ type: "varchar", nullable: true })
+ role!: string | null
 
  @OneToMany(() => SessionEntity, (session) => session.userId)
  sessions!: SessionEntity[]
 
  @OneToMany(() => AccountEntity, (account) => account.userId)
  accounts!: AccountEntity[]
}
 
@Entity({ name: "accounts" })
export class AccountEntity {
  @PrimaryGeneratedColumn("uuid")
  id!: string
 
  @Column({ type: "uuid" })
  userId!: string
 
  @Column()
  type!: string
 
  @Column()
  provider!: string
 
  @Column()
  providerAccountId!: string
 
  @Column({ type: "varchar", nullable: true })
  refresh_token!: string | null
 
  @Column({ type: "varchar", nullable: true })
  access_token!: string | null
 
  @Column({
    nullable: true,
    type: "bigint",
    transformer: transformer.bigint,
  })
  expires_at!: number | null
 
  @Column({ type: "varchar", nullable: true })
  token_type!: string | null
 
  @Column({ type: "varchar", nullable: true })
  scope!: string | null
 
  @Column({ type: "varchar", nullable: true })
  id_token!: string | null
 
  @Column({ type: "varchar", nullable: true })
  session_state!: string | null
 
  @Column({ type: "varchar", nullable: true })
  oauth_token_secret!: string | null
 
  @Column({ type: "varchar", nullable: true })
  oauth_token!: string | null
 
  @ManyToOne(() => UserEntity, (user) => user.accounts, {
    createForeignKeyConstraints: true,
  })
  user!: UserEntity
}
 
@Entity({ name: "sessions" })
export class SessionEntity {
  @PrimaryGeneratedColumn("uuid")
  id!: string
 
  @Column({ unique: true })
  sessionToken!: string
 
  @Column({ type: "uuid" })
  userId!: string
 
  @Column({ transformer: transformer.date })
  expires!: string
 
  @ManyToOne(() => UserEntity, (user) => user.sessions)
  user!: UserEntity
}
 
@Entity({ name: "verification_tokens" })
export class VerificationTokenEntity {
  @PrimaryGeneratedColumn("uuid")
  id!: string
 
  @Column()
  token!: string
 
  @Column()
  identifier!: string
 
  @Column({ transformer: transformer.date })
  expires!: string
}
  1. 將它們傳遞給 TypeORMAdapter
./auth.ts
import NextAuth from "next-auth"
import { TypeORMAdapter } from "@auth/typeorm-adapter"
import * as entities from "lib/entities"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: TypeORMAdapter("yourconnectionstring", { entities }),
})

TypeORM 中的 synchronize: true 選項將產生與實體完全匹配的 SQL。這會自動套用在實體模型中找到的任何變更。這是開發中有用的選項。

⚠️

不應在生產資料庫上啟用 synchronize: true,因為如果設定的結構描述與預期的結構描述不符,可能會導致資料遺失!我們建議您在建置時同步/遷移您的生產資料庫。

命名慣例

如果混合使用蛇底式 (snake_case) 和駝峰式 (camelCase) 欄位名稱對您和/或您底層的資料庫系統造成問題,我們建議使用 TypeORM 的命名策略功能來變更目標欄位名稱。有一個名為 typeorm-naming-strategies 的套件,其中包括一個 snake_case 策略,它會將 Auth.js 預期的欄位轉換為實際資料庫中的 snake_case。

例如,您可以將命名慣例選項新增至 NextAuth 組態中的連線物件。

./auth.ts
import NextAuth from "next-auth"
import { TypeORMAdapter } from "@auth/typeorm-adapter"
import { SnakeNamingStrategy } from "typeorm-naming-strategies"
import { ConnectionOptions } from "typeorm"
 
const connection: ConnectionOptions = {
  type: "mysql",
  host: "localhost",
  port: 3306,
  username: "test",
  password: "test",
  database: "test",
  namingStrategy: new SnakeNamingStrategy(),
}
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: TypeORMAdapter(connection),
})
Auth.js © Balázs Orbán 和團隊 -2024