Kotlin – Use EnumSet For RBAC

kotlin

Deprecated: get_the_author_email is deprecated since version 2.8.0! Use get_the_author_meta('email') instead. in /home/cloudber/public_html/wp-includes/functions.php on line 4713

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

User.kt
import java.util.*

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

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

UserTest.kt
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

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.