com.lightningkite.ktordb.ModelPermissions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of db Show documentation
Show all versions of db Show documentation
An abstract tool for communicating with different types of databases.
The newest version!
package com.lightningkite.ktordb
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlin.reflect.KProperty1
data class ModelPermissions(
val create: Condition,
val read: Condition,
val readFields: Map, Read> = mapOf(),
val update: Condition,
val updateFields: Map, Update> = mapOf(),
val delete: Condition,
val maxQueryTimeMs: Long = 1_000L
) {
data class Read(
val property: KProperty1,
val condition: Condition,
val mask: Field
) {
@Suppress("UNCHECKED_CAST")
fun mask(model: Model): Model {
return if(condition(model)) model
else property.setCopy(model, mask)
}
}
data class Update(
val property: KProperty1,
val condition: Condition
)
fun allowed(modification: Modification<*>): Condition {
return when(modification) {
is Modification.Assign<*> -> Condition.And(updateFields.values.map { it.condition })
is Modification.Chain<*> -> Condition.And(modification.modifications.map { allowed(it) })
is Modification.IfNotNull<*> -> allowed(modification.modification)
is Modification.OnField<*, *> -> allowedInner(modification)
else -> Condition.Always()
}
}
private fun allowedInner(modification: Modification<*>): Condition {
return when(modification) {
is Modification.OnField<*, *> -> updateFields[modification.key]?.condition ?: Condition.Always()
is Modification.Chain<*> -> Condition.And(modification.modifications.map { allowedInner(it) })
is Modification.IfNotNull<*> -> allowed(modification.modification)
else -> Condition.Always()
}
}
fun mask(model: Model): Model {
var current = model
for(f in readFields.values) {
current = f.mask(current)
}
return current
}
}