main.pl.setblack.nee.security.UserRealm.kt Maven / Gradle / Ivy
package pl.setblack.nee.security
import io.vavr.collection.HashMap
import io.vavr.collection.Set
import io.vavr.collection.HashSet
import io.vavr.control.Option
import io.vavr.control.Try
import java.io.ByteArrayOutputStream
import java.io.ObjectOutputStream
interface UserRealm {
fun loginUser(userLogin: String, password: CharArray): Option
fun hasRole(user: USERID, role: ROLE): Boolean
}
data class InMemoryUserRealm(
val rolesMap: HashMap> = HashMap.empty(),
val passwords :HashMap = HashMap.empty(),
val userIdMapper: (USERID) ->String = {it.toString()}
) : UserRealm {
fun withRole(userid: USERID, role: ROLE) =
this.copy(rolesMap = rolesMap.put(userIdMapper(userid), HashSet.of(role)) { _, preVal ->
preVal.add(role)
})
fun withPassword(userid: USERID, password: CharArray) =
this.copy(passwords = passwords.put(userid, password) )
override fun loginUser(userLogin: String, password: CharArray): Option =
passwords.iterator().find{
userIdMapper(it._1) == userLogin
}.filter{
it._2.contentEquals(password)
}.map {
it._1
}
override fun hasRole(user: USERID, role: ROLE): Boolean =
rolesMap[userIdMapper(user)].map { roles ->
roles.contains(role)
}.getOrElse(false)
}
fun aTest1(elements: Array): Try =
Try.withResources { ByteArrayOutputStream() }
.of { output ->
Try.withResources { ObjectOutputStream(output) }
.of { someOutput ->
someOutput.writeObject(elements)
output.toByteArray()
}
}.flatMap { it }
fun aTest2(elements: Array): Try = Try.of {
ByteArrayOutputStream().use { output ->
ObjectOutputStream(output).use { someOutput ->
someOutput.writeObject(elements)
output.toByteArray()
}
}
}