Improve voter
This commit is contained in:
20
src/main/kotlin/fr/dcproject/security/voter/CheckClass.kt
Normal file
20
src/main/kotlin/fr/dcproject/security/voter/CheckClass.kt
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,13 @@ interface Voter {
|
||||
}
|
||||
|
||||
fun List<Voter>.can(action: ActionI, call: ApplicationCall, subject: Any? = null): Boolean {
|
||||
val votes = this
|
||||
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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user