4

I'm designing an application where I have users and admins (further down in the future, I can have different sub-ranks, where each one can have access to some area of the application).

Currently, I have a single "User" class with a "type" integer attribute, which is checked when accessing restricted areas.

This feels like "wiring" instead of a proper design, but I cant find a simple way to implement this in OOD: having an Administrator sub-class doesnt feel easy to handle or logic (would need type check for access)...

Am I wrong? What is the proper way to do this?

Andy
  • 10,238
  • 4
  • 25
  • 50
Tiago Duque
  • 317
  • 1
  • 2
  • 8
  • 2
    Look for Access Control Patterns: Roles, ACLs, etc. **Authorization** (not Authentication) – Laiv Oct 23 '16 at 18:00
  • Now, for applying Roles in a OO Architecture, should I use a class per role or a general class and then add permissions for each instance of this role? – Tiago Duque Oct 23 '16 at 18:02
  • 1
    Take a look https://en.m.wikipedia.org/wiki/Role-based_access_control – Laiv Oct 23 '16 at 18:03
  • Also look for Spring Security. If you are using Spring framework, it already has implemented a module for this concern. – Laiv Oct 23 '16 at 18:11

2 Answers2

2

As the system complexity grows it is very likely that you will hit the following limitation of the "level-based" approach (e.g. reader, writer, admin):

User A needs to access feature X but is not allowed to access feature Y, but user B needs to access feature Y but is not allowed to access feature X.

This can be solved by giving users roles. User A, will get role X, and user B will get role Y.

Please have a look at https://en.wikipedia.org/wiki/Role-based_access_control

Some authorisation libraries, e.g. in ASP.NET have support for roles built in.

tymtam
  • 1,703
  • 2
  • 11
  • 11
  • +1: To my knowledge, this is best practice and is necessitated by some industry standards like PCI-DSS (Payment Card Industry) – Maybe_Factor Nov 23 '16 at 00:43
1

This depends on what the functional difference between User and Admin is going to be. The answer may well be that you don't need different user types at all.

For instance, in the Web framework Django, the difference is in permissions -- admins are allowed to do everything. But non-admin Users aren't all the same, different Users are allowed to do different things (but not necessarily everything).

So Django has a Permission system, where users can have some set of permissions, and at appropriate moments user.has_perm(permission) is checked.

The Admin is then simply implemented with a single boolean flag on the User model; if is_admin is True, then has_perm(permission) returns True regardless of the permission being checked.

Admins are mostly just users, they need to be able to login, have an email address, and so on.

RemcoGerlich
  • 3,280
  • 18
  • 22