Answer the question
In order to leave comments, you need to log in
How to make a model of users with roles? Are there examples/practices of authorization with roles?
For example, there is a User model
const userSchema = new mongoose.Schema ({
email: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true
},
username: {
type: String,
unique: true
},
firstName: String,
lastName: String,
createdAt: {
type: Date,
default: Date.now
}
})
role: {
type :String,
default: 'reader'
}
Answer the question
In order to leave comments, you need to log in
const ADMIN = 0b11111111
const CAN_DELETE = 0b00001000
const CAN_EDIT = 0b00000100
const CAN_WRITE = 0b00000010
const CAN_READ = 0b00000001
const REGULAR_USER = CAN_WRITE | CAN_READ
const ANONYMOUS = CAN_READ
const BANNED = 0b0
const MODERATOR = REGULAR_USER | CAN_EDIT | CAN_DELETE
class User {
constructor(name, mask) {
this.name = name;
this.mask = mask;
}
}
const users = [
new User('admin', ADMIN),
new User('moder', MODERATOR),
new User('regular_user', REGULAR_USER),
new User('anon', ANONYMOUS),
]
users.forEach( u => {
console.log(u.name);
if ((u.mask & ADMIN) === ADMIN) {
console.log('\t ADMIN');
}
if ((u.mask & MODERATOR) === MODERATOR) {
console.log('\t MODERATOR');
}
if ((u.mask & REGULAR_USER) === REGULAR_USER) {
console.log('\t REGULAR_USER');
}
if ((u.mask & CAN_EDIT) === CAN_EDIT) {
console.log('\t CAN_EDIT');
}
if ((u.mask & CAN_DELETE) === CAN_DELETE) {
console.log('\t CAN_DELETE');
}
if ((u.mask & CAN_WRITE) === CAN_WRITE) {
console.log('\t CAN_WRITE');
}
if ((u.mask & CAN_READ) === CAN_READ) {
console.log('\t CAN_READ');
}
});
admin
ADMIN
MODERATOR
REGULAR_USER
CAN_EDIT
CAN_DELETE
CAN_WRITE
CAN_READ
moder
MODERATOR
REGULAR_USER
CAN_EDIT
CAN_DELETE
CAN_WRITE
CAN_READ
regular_user
REGULAR_USER
CAN_WRITE
CAN_READ
anon
CAN_READ
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question