Add Security to Citizen
This commit is contained in:
42
src/main/kotlin/fr/dcproject/security/voter/CitizenVoter.kt
Normal file
42
src/main/kotlin/fr/dcproject/security/voter/CitizenVoter.kt
Normal file
@@ -0,0 +1,42 @@
|
||||
package fr.dcproject.security.voter
|
||||
|
||||
import fr.dcproject.entity.Citizen
|
||||
import fr.dcproject.entity.User
|
||||
import io.ktor.application.ApplicationCall
|
||||
|
||||
class CitizenVoter: Voter {
|
||||
enum class Action: ActionI {
|
||||
CREATE,
|
||||
UPDATE,
|
||||
VIEW,
|
||||
DELETE
|
||||
}
|
||||
|
||||
override fun supports(action: ActionI, call: ApplicationCall, subject: Any?): Boolean {
|
||||
return action is Action && subject is Citizen?
|
||||
}
|
||||
|
||||
override fun vote(action: ActionI, call: ApplicationCall, subject: Any?): Vote {
|
||||
val user = call.user
|
||||
if (action == Action.CREATE && user != null) {
|
||||
return Vote.GRANTED
|
||||
}
|
||||
|
||||
if (action == Action.VIEW) {
|
||||
return Vote.GRANTED
|
||||
}
|
||||
|
||||
if (action == Action.DELETE) {
|
||||
return Vote.DENIED
|
||||
}
|
||||
|
||||
if (action == Action.UPDATE &&
|
||||
user is User &&
|
||||
subject is Citizen &&
|
||||
subject.user?.id == user.id) {
|
||||
return Vote.GRANTED
|
||||
}
|
||||
|
||||
return Vote.ABSTAIN
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.response.respond
|
||||
import io.ktor.util.AttributeKey
|
||||
import io.ktor.util.KtorExperimentalAPI
|
||||
import io.ktor.util.pipeline.PipelineContext
|
||||
|
||||
interface ActionI
|
||||
|
||||
@@ -39,6 +40,13 @@ fun ApplicationCall.assertCan(action: ActionI, subject: Any? = null) {
|
||||
throw UnauthorizedException(action)
|
||||
}
|
||||
}
|
||||
|
||||
fun PipelineContext<Unit, ApplicationCall>.assertCan(action: ActionI, subject: Any? = null) =
|
||||
context.assertCan(action, subject)
|
||||
|
||||
fun PipelineContext<Unit, ApplicationCall>.can(action: ActionI, subject: Any? = null) =
|
||||
context.can(action, subject)
|
||||
|
||||
fun ApplicationCall.can(action: ActionI, subject: Any? = null): Boolean {
|
||||
val voters = attributes[votersAttributeKey]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user