Setting user role on sign up

Is it possible to set a users role when they sign up or just when an admin creates them?
Solution:
You can not set role on signup but you can use admin for that
Jump to solution
8 Replies
Solution
KiNFiSH
KiNFiSH4mo ago
You can not set role on signup but you can use admin for that
Joseph
Joseph3mo ago
how about implementing default role like "staff" rather than user
Ping
Ping3mo ago
In admin plugin config you can set the default role.
Serhii
Serhii3mo ago
Hey everyone, I saw this thread and I need some help. I have multiple roles, student, teacher, support, admin. I want to enable sign up for students and teachers, so that they have correct role assigned by default after sign up. I've tried many things, even directly updating the db on after hook, unfortunately still no luck. From what I see, it looks like admin plugin is not really suitable for RBAC, am I correct, or maybe I'm missing some trivial solution? oh, and when I try to update it using admin api:
await auth.api.setRole({
body: {
userId: user.id,
role: "teacher",
},
});
await auth.api.setRole({
body: {
userId: user.id,
role: "teacher",
},
});
I get unauthorized... ok, I was able to do that making a direct DB change... which doesn't seem right. anyway if there is a cleaner solution I'd like to learn it.
battlesheep123
battlesheep1233mo ago
If you don't need all the functionality of the admin plugin, but just need roles. Then I'd go for a custom field "role" on the user object.
import { betterAuth } from "better-auth";

export const auth = betterAuth({
user: {
additionalFields: {
role: {
type: "string",
required: false,
defaultValue: "user",
},
},
},
});
import { betterAuth } from "better-auth";

export const auth = betterAuth({
user: {
additionalFields: {
role: {
type: "string",
required: false,
defaultValue: "user",
},
},
},
});
Whenever someone signs up, the user automatically gets the role "user" set.
Serhii
Serhii3mo ago
the thing is that I think I need admin plugin, since I will need more from it's functionality e.g. managing other users, since some might abuse the system and I'd want to ban them. but it feels like I'm battling this plugin..
Omar-7ioo
Omar-7ioo3mo ago
What happens if you enable the plugin and add additionalFields? It is not the cleanest but this way you can assign a role on signup. Make sure to use zod validation so you don't mess things up You might get a typescript error but you can ignore it. Not sure if this approach will mess something up.
sebastian
sebastian3mo ago
use a database hook

Did you find this page helpful?