0

I was struggling for days on how can I implement a switch between roles with one userAccount within a Spring Boot application via Spring Security. There is an example in my case:

I have a class [UserAccount]{Id,username,password,isActive} and [Role]{Id,roleName,description} with which I'm implementing a successful simple login system with some @Secured RESTful methods.
My roles are: ADMIN, TEACHER & STUDENT

Now, I want to create a class for each role (e.g. StudentUser, TeacherUser, AdminUser) or something like that, to be able to add some new attributes which are not common between all users.
For example:

  • A StudentUser will be related to Grades, Courses, Exams, etc.
  • A TeacherUser will be related to departement, Course, ResearchTeam, etc.
  • Or in some cases, a user with multiple roles (TEACHER & STUDENT) like a PhD student, want to switch between his frontend spaces (different views).

    How can I deal with that in a best and efficient way? Thanks.

  • nikiforovpizza
    • 487
    • 1
    • 7
    • 13
    BELGOUGI
    • 29
    • 1
    • 7

    2 Answers2

    1

    The problem is that you want to bind few entities together - Account, Person, Role. I would suggest you to separate them like this:

    • Person - just basic data such as name
    • Person can have an Account. Person without an Account cannot login.
    • Student/Teacher/Admin has/is a Person - Student/Teacher/Admin contain info specific to each role. When designing this relationship, it's necessary to figure out whether a Person can have more Student/Teacher/Admin profiles of the same type (what if a Person has multiple studies). If you design it as a one-to-one relationship, it can be modeled as inheritance in Java (Student/Teacher/Admin is a Person).

    In Spring Security, assign GrantedAuthority-s (roles) according to what (active) Student/Teacher/Admin relationships the Account's Person has.

    In your frontent, you will see what roles the logged-in Person has and you can allow them to switch between the role based views.

    Update

    For clarification, this is what the class diagram could look like:

    Possible class diagram

    You don't need to have a separate class/table for roles, since roles are determined by the presence of Student/Teacher/Admin objects for a given Person. But if you need it for some reason, you can add it there - probably Account would have 1..n Roles.

    Ján Halaša
    • 8,167
    • 1
    • 36
    • 36
    0

    Thank you all, I solved the problem by : inheriting from the Profile each role has it's own profile class, so the user will've multiple profiles.

    BELGOUGI
    • 29
    • 1
    • 7