用户名

用户名插件封装了电子邮件和密码认证器,并添加了用户名支持。这允许用户使用他们的用户名而不是电子邮件进行登录和注册。

安装

将插件添加到服务器

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
 
const auth = betterAuth({
    plugins: [ 
        username() 
    ] 
})

迁移数据库

运行迁移或生成schema,以向数据库添加必要的字段和表。

npx @better-auth/cli migrate

查看Schema部分手动添加字段。

添加客户端插件

auth-client.ts
import { createAuthClient } from "better-auth/client"
import { usernameClient } from "better-auth/client/plugins"
 
const authClient = createAuthClient({
    plugins: [ 
        usernameClient() 
    ] 
})

使用方法

使用用户名注册

要使用用户名注册用户,您可以使用客户端提供的现有signUp.email函数。signUp函数应在对象中接收一个新的username属性。

auth-client.ts
const data = await authClient.signUp.email({
    email: "[email protected]",
    name: "Test User",
    password: "password1234",
    username: "test"
})

使用用户名登录

要使用用户名登录用户,您可以使用客户端提供的signIn.username函数。signIn函数接收一个具有以下属性的对象:

  • username:用户的用户名。
  • password:用户的密码。
auth-client.ts
const data = await authClient.signIn.username({
    username: "test",
    password: "password1234",
})

更新用户名

要更新用户的用户名,您可以使用客户端提供的updateUser函数。

auth-client.ts
const data = await authClient.updateUser({
    username: "new-username"
})

Schema

该插件需要向用户表添加1个字段:

Field NameTypeKeyDescription
usernamestring-用户的用户名
displayUsernamestring-用户的非规范化用户名

选项

最小用户名长度

用户名的最小长度。默认为3

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
 
const auth = betterAuth({
    plugins: [
        username({
            minUsernameLength: 5
        })
    ]
})

最大用户名长度

用户名的最大长度。默认为30

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
 
const auth = betterAuth({
    plugins: [
        username({
            maxUsernameLength: 100
        })
    ]
})

用户名验证器

验证用户名的函数。如果用户名无效,该函数应返回false。默认情况下,用户名只能包含字母数字字符、下划线和点。

auth.ts
import { betterAuth } from "better-auth"
import { username } from "better-auth/plugins"
 
const auth = betterAuth({
    plugins: [
        username({
            usernameValidator: (username) => {
                if (username === "admin") {
                    return false
                }
            }
        })
    ]
})

On this page