com.pubnub.api.models.server.access_manager.v3.GrantTokenRequestBody.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pubnub-kotlin Show documentation
Show all versions of pubnub-kotlin Show documentation
PubNub is a cross-platform client-to-client (1:1 and 1:many) push service in the cloud, capable of
broadcasting real-time messages to millions of web and mobile clients simultaneously, in less than a quarter
second!
package com.pubnub.api.models.server.access_manager.v3
import com.pubnub.api.PubNubException
import com.pubnub.api.models.TokenBitmask
import com.pubnub.api.models.consumer.access_manager.v3.ChannelGrant
import com.pubnub.api.models.consumer.access_manager.v3.ChannelGroupGrant
import com.pubnub.api.models.consumer.access_manager.v3.PNGrant
import com.pubnub.api.models.consumer.access_manager.v3.PNPatternGrant
import com.pubnub.api.models.consumer.access_manager.v3.UUIDGrant
data class GrantTokenRequestBody(
val ttl: Int,
val permissions: GrantTokenPermissions
) {
data class GrantTokenPermissions(
val resources: GrantTokenPermission,
val patterns: GrantTokenPermission,
val meta: Any? = null,
val uuid: String? = null
)
data class GrantTokenPermission(
val channels: Map = emptyMap(),
val groups: Map = emptyMap(),
val uuids: Map = emptyMap(),
val spaces: Map = emptyMap(),
val users: Map = emptyMap()
)
companion object {
@Throws(PubNubException::class)
fun of(
ttl: Int,
channels: List,
groups: List,
uuids: List,
meta: Any?,
uuid: String?
): GrantTokenRequestBody {
val resources = GrantTokenPermission(
getResources(channels),
getResources(groups), getResources(uuids)
)
val patterns = GrantTokenPermission(
getPatterns(channels),
getPatterns(groups), getPatterns(uuids)
)
val permissions = GrantTokenPermissions(resources, patterns, meta ?: emptyMap(), uuid)
return GrantTokenRequestBody(ttl, permissions)
}
private fun getResources(resources: List): Map {
return resources
.filter { it !is PNPatternGrant }
.associate { it.id to calculateBitmask(it) }
}
private fun getPatterns(resources: List): Map {
return resources
.filterIsInstance(PNPatternGrant::class.java)
.associate { it.id to calculateBitmask(it) }
}
private fun calculateBitmask(resource: PNGrant): Int {
var sum = 0
if (resource.read) {
sum = sum or TokenBitmask.READ
}
if (resource.write) {
sum = sum or TokenBitmask.WRITE
}
if (resource.manage) {
sum = sum or TokenBitmask.MANAGE
}
if (resource.delete) {
sum = sum or TokenBitmask.DELETE
}
if (resource.create) {
sum = sum or TokenBitmask.CREATE
}
if (resource.get) {
sum = sum or TokenBitmask.GET
}
if (resource.join) {
sum = sum or TokenBitmask.JOIN
}
if (resource.update) {
sum = sum or TokenBitmask.UPDATE
}
return sum
}
}
}