跳至内容
从 NextAuth.js v4 迁移?阅读 我们的迁移指南.

TypeORM 适配器

资源

设置

安装

npm install @auth/typeorm-adapter typeorm

环境变量

AUTH_TYPEORM_CONNECTION=postgres://postgres:[email protected]: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