H
H
hckn2018-09-11 19:35:18
Node.js
hckn, 2018-09-11 19:35:18

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
  }
})

Various tutorials and articles cover only basic authorization, and do not touch at all on such a topic as user roles. And I need, for example, admins and just users.
Of course I can add just this
role: {
    type :String,
    default: 'reader'
  }

And just write admin or reader in the line. But it looks too primitive. and I am sure that there are some practices how everything should be arranged. Please give me a link or tell me how?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
planc, 2018-09-12
@planc

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

D
Dimonchik, 2018-09-11
@dimonchik2013

https://django-role-permissions.readthedocs.io/en/...

R
ru-soft, 2018-09-12
@ru-soft

https://aspnetboilerplate.com/ Sample implementation and documentation For Node.Js, you can borrow the model structure and validation logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question