Improve voter

This commit is contained in:
2020-03-16 02:42:20 +01:00
parent 8ad0281003
commit aa7ca26b51
2 changed files with 27 additions and 4 deletions

View File

@@ -0,0 +1,20 @@
package fr.dcproject.security.voter
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
class WrongClassException(
expected: KClass<*>,
current: KClass<*>?
) : VoterException("Can not define authorization with class $current. Need $expected")
fun Voter.checkClass(
expected: KClass<*>,
subject: Any?
) {
if (subject != null && !subject::class.isSubclassOf(expected)) {
throw WrongClassException(expected, subject::class)
} else if (subject == null) {
throw WrongClassException(expected, null)
}
}

View File

@@ -19,10 +19,13 @@ interface Voter {
}
fun List<Voter>.can(action: ActionI, call: ApplicationCall, subject: Any? = null): Boolean {
val votes = this
.filter { it.supports(action, call, subject) }
.ifEmpty { throw NoVoterException(action) }
.map { it.vote(action, call, subject) }
val listOfSubject: List<Any?> = if (subject !is List<*>) listOf(subject) else subject
val votes: List<Vote> = listOfSubject.flatMap { subject ->
this
.filter { it.supports(action, call, subject) }
.ifEmpty { throw NoVoterException(action) }
.map { it.vote(action, call, subject) }
}
return votes.all { it in listOf(Vote.GRANTED, Vote.ABSTAIN) } and votes.any { it == Vote.GRANTED }
}