Kotlin
Kotlin

Enumset is a powerful collection in Java to replace bit fields.

This article will explains how to use EnumSet to create a RBAC (Role-Based Access Control).

import java.util.*

class User (val access: EnumSet<Access>)
enum class Access {
    NONE, VIEW, COMMENT, EDIT
}

Now, let’s see how we can use EnumSet to create a RBAC.

import org.junit.jupiter.api.BeforeEach
import java.util.*
import kotlin.test.assertFalse
import kotlin.test.assertTrue

internal class UserTest {
    var adminRoles       = EnumSet.noneOf(Access::class.java)
    var superUserRoles   = EnumSet.noneOf(Access::class.java)
    var basicUserRoles   = EnumSet.noneOf(Access::class.java)
    var visitorRoles     = EnumSet.noneOf(Access::class.java)

    @BeforeEach
    fun setup(){
        this.adminRoles     = EnumSet.allOf(Access::class.java)
        this.superUserRoles      = EnumSet.complementOf(EnumSet.of(Access.EDIT))
        this.basicUserRoles      = EnumSet.of(Access.VIEW)
        this.visitorRoles        = EnumSet.of(Access.NONE)
    }

    @org.junit.jupiter.api.Test
    fun getAccess() {
        val admin       = User(adminRoles)
        val visitor     = User(visitorRoles)
        val basicUser   = User(basicUserRoles)

        assertTrue(admin.access.containsAll(adminRoles))
        assertFalse(visitor.access.containsAll(adminRoles))
        assertFalse(basicUser.access.containsAll(adminRoles))
        assertTrue(basicUser.access.containsAll(basicUserRoles))
    }
}

Inside the setup method, a series of roles with specific access right in a given system has been defined

In User class, there is a property which its’ type is an EnumSet. This indicates that, every instance of User has its roles.

Use containsAll method of Java Collections to test against, whether an instance of user match a certain roles, with this we can give an instance of user of specific right to access in our system, based on the boolean result returned by containsAll

Source Codes

https://github.com/wuchiachong/kotlin-EnumSet

Last modified: May 27, 2020

Author