initial commit
This commit is contained in:
22
backend/src/main/kotlin/com/infendro/account/Application.kt
Normal file
22
backend/src/main/kotlin/com/infendro/account/Application.kt
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.infendro.account
|
||||
|
||||
import com.infendro.account.config.*
|
||||
import com.infendro.account.model.initializeDatabase
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.cio.*
|
||||
|
||||
fun main(
|
||||
args: Array<String>,
|
||||
) = EngineMain.main(args)
|
||||
|
||||
fun Application.module() {
|
||||
configureDatabase()
|
||||
configureDependencyInjection()
|
||||
configureSecurity()
|
||||
configureSerialization()
|
||||
configureValidation()
|
||||
configureRouting()
|
||||
configureException()
|
||||
|
||||
initializeDatabase()
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.server.config.ApplicationConfig
|
||||
|
||||
data class DatabaseConfig(
|
||||
val host: String,
|
||||
val username: String,
|
||||
val password: String,
|
||||
) {
|
||||
val url: String
|
||||
get() = "jdbc:postgresql://${host}/account"
|
||||
}
|
||||
|
||||
data class SecurityConfig(
|
||||
val cookie: CookieConfig,
|
||||
)
|
||||
|
||||
data class CookieConfig(
|
||||
val domain: String,
|
||||
val path: String,
|
||||
val secure: Boolean,
|
||||
)
|
||||
|
||||
val ApplicationConfig.database: DatabaseConfig
|
||||
get() {
|
||||
val host = property("database.host").getString()
|
||||
val username = property("database.username").getString()
|
||||
val password = property("database.password").getString()
|
||||
|
||||
return DatabaseConfig(host, username, password)
|
||||
}
|
||||
|
||||
val ApplicationConfig.security: SecurityConfig
|
||||
get() {
|
||||
return SecurityConfig(cookie)
|
||||
}
|
||||
|
||||
private val ApplicationConfig.cookie: CookieConfig
|
||||
get() {
|
||||
val domain = property("security.cookie.domain").getString()
|
||||
val path = property("security.cookie.path").getString()
|
||||
val secure = property("security.cookie.secure").getString().toBooleanStrict()
|
||||
|
||||
return CookieConfig(domain, path, secure)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import org.flywaydb.core.Flyway
|
||||
import org.jetbrains.exposed.sql.Database
|
||||
|
||||
fun Application.configureDatabase() {
|
||||
val config = environment.config.database
|
||||
|
||||
Database.connect(
|
||||
url = config.url,
|
||||
user = config.username,
|
||||
password = config.password,
|
||||
)
|
||||
|
||||
val flyway = Flyway.configure()
|
||||
.dataSource(config.url, config.username, config.password)
|
||||
.load()
|
||||
flyway.migrate()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.InitializationRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.service.AccessService
|
||||
import com.infendro.account.service.AccountService
|
||||
import com.infendro.account.service.RoleService
|
||||
import com.infendro.account.service.SessionService
|
||||
import io.ktor.server.application.*
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
import org.koin.dsl.module
|
||||
import org.koin.ktor.plugin.koin
|
||||
import org.koin.logger.slf4jLogger
|
||||
|
||||
fun Application.configureDependencyInjection() {
|
||||
koin {
|
||||
slf4jLogger()
|
||||
modules(module)
|
||||
}
|
||||
}
|
||||
|
||||
private val module = module {
|
||||
singleOf(::InitializationRepository)
|
||||
singleOf(::AccessRepository)
|
||||
singleOf(::AccountRepository)
|
||||
singleOf(::SessionRepository)
|
||||
|
||||
singleOf(::AccessService)
|
||||
singleOf(::AccountService)
|
||||
singleOf(::RoleService)
|
||||
singleOf(::SessionService)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.BadRequest
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.statuspages.*
|
||||
import io.ktor.server.response.*
|
||||
|
||||
fun Application.configureException() {
|
||||
install(StatusPages) {
|
||||
exception<StatusException> { call, exception ->
|
||||
call.respond(exception.status)
|
||||
}
|
||||
exception<RequestValidationException> { call, _ ->
|
||||
call.respond(BadRequest)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.routing.access
|
||||
import com.infendro.account.routing.account
|
||||
import com.infendro.account.routing.role
|
||||
import com.infendro.account.routing.session
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.resources.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureRouting() {
|
||||
install(Resources)
|
||||
routing {
|
||||
access()
|
||||
account()
|
||||
role()
|
||||
session()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.auth.Authentication
|
||||
import io.ktor.server.auth.session
|
||||
import io.ktor.server.sessions.*
|
||||
import kotlin.time.Duration.Companion.days
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Serializable
|
||||
data class AuthenticationSession(
|
||||
val token: String,
|
||||
)
|
||||
|
||||
data class AuthenticationPrincipal(
|
||||
val account: AccountEntity,
|
||||
val session: SessionEntity,
|
||||
) {
|
||||
val role: Role
|
||||
get() = account.role
|
||||
}
|
||||
|
||||
fun Application.configureSecurity() {
|
||||
val config = environment.config.security
|
||||
|
||||
install(Sessions) {
|
||||
cookie<AuthenticationSession>(
|
||||
"Authentication",
|
||||
SessionStorageMemory(),
|
||||
) {
|
||||
cookie.domain = config.cookie.domain
|
||||
cookie.path = config.cookie.path
|
||||
cookie.httpOnly = true
|
||||
cookie.secure = config.cookie.secure
|
||||
cookie.extensions["SameSite"] = "Strict"
|
||||
cookie.maxAge = 7.days
|
||||
}
|
||||
}
|
||||
install(Authentication) {
|
||||
session<AuthenticationSession> {
|
||||
validate { authenticationSession ->
|
||||
val sessionRepository by inject<SessionRepository>()
|
||||
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.tokenHash eq Hasher.hash(authenticationSession.token) }
|
||||
?: return@validate null
|
||||
|
||||
sessions.set(authenticationSession)
|
||||
|
||||
AuthenticationPrincipal(session.account(), session)
|
||||
}
|
||||
challenge {
|
||||
call.sessions.clear<AuthenticationSession>()
|
||||
|
||||
throw UnauthorizedException()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
|
||||
fun Application.configureSerialization() {
|
||||
install(ContentNegotiation) {
|
||||
json()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.config
|
||||
|
||||
import com.infendro.account.dto.request.validatePostAccountRequest
|
||||
import com.infendro.account.dto.request.validatePutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.validatePutAccountCurrentUsernameRequest
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
|
||||
fun Application.configureValidation() {
|
||||
install(RequestValidation) {
|
||||
validatePostAccountRequest()
|
||||
validatePutAccountCurrentUsernameRequest()
|
||||
validatePutAccountCurrentPasswordRequest()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_PASSWORD
|
||||
import com.infendro.account.util.REGEX_USERNAME
|
||||
import io.ktor.server.plugins.requestvalidation.RequestValidationConfig
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.Invalid
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.Valid
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccountRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
val access: PostAccountRequestAccess,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PostAccountRequestAccess(
|
||||
val token: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePostAccountRequest() {
|
||||
validate<PostAccountRequest> { request ->
|
||||
when {
|
||||
!REGEX_USERNAME.matches(request.username) -> Invalid("")
|
||||
!REGEX_PASSWORD.matches(request.password) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostSessionRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
val otp: String,
|
||||
)
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_PASSWORD
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountCurrentPasswordRequest(
|
||||
val password: String,
|
||||
val otp: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePutAccountCurrentPasswordRequest() {
|
||||
validate<PutAccountCurrentPasswordRequest> { request ->
|
||||
when {
|
||||
!REGEX_PASSWORD.matches(request.password) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.util.REGEX_USERNAME
|
||||
import io.ktor.server.plugins.requestvalidation.*
|
||||
import io.ktor.server.plugins.requestvalidation.ValidationResult.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountCurrentUsernameRequest(
|
||||
val username: String,
|
||||
val otp: String,
|
||||
)
|
||||
|
||||
fun RequestValidationConfig.validatePutAccountCurrentUsernameRequest() {
|
||||
validate<PutAccountCurrentUsernameRequest> { request ->
|
||||
when {
|
||||
!REGEX_USERNAME.matches(request.username) -> Invalid("")
|
||||
else -> Valid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.infendro.account.dto.request
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PutAccountIdRoleRequest(
|
||||
val role: Role,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.entity.AccessEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AccessResponse(
|
||||
val id: Long,
|
||||
)
|
||||
|
||||
fun AccessEntity.toResponse() = AccessResponse(
|
||||
id = id.value,
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AccountResponse(
|
||||
val id: Long,
|
||||
val username: String,
|
||||
val role: Role,
|
||||
val sessions: List<SessionResponse>,
|
||||
)
|
||||
|
||||
fun AccountEntity.toResponse(): AccountResponse {
|
||||
return AccountResponse(
|
||||
id = id.value,
|
||||
username = username,
|
||||
role = role,
|
||||
sessions = sessions().map(SessionEntity::toResponse),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccessResponse(
|
||||
val token: String,
|
||||
)
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class PostAccountResponse(
|
||||
val secret: String,
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class RoleResponse(
|
||||
val role: Role,
|
||||
val children: List<Role>,
|
||||
)
|
||||
|
||||
fun Role.toResponse() = RoleResponse(
|
||||
role = this,
|
||||
children = children,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.infendro.account.dto.response
|
||||
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class SessionResponse(
|
||||
val id: Long,
|
||||
val accountId: Long,
|
||||
)
|
||||
|
||||
fun SessionEntity.toResponse(): SessionResponse {
|
||||
return SessionResponse(
|
||||
id = id.value,
|
||||
accountId = account().id.value,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.infendro.account.exception
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
|
||||
abstract class StatusException(
|
||||
val status: HttpStatusCode,
|
||||
) : Exception()
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.BadRequest
|
||||
|
||||
class BadRequestException : StatusException(BadRequest)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Conflict
|
||||
|
||||
class ConflictException : StatusException(Conflict)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Forbidden
|
||||
|
||||
class ForbiddenException : StatusException(Forbidden)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.NotFound
|
||||
|
||||
class NotFoundException : StatusException(NotFound)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.client
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.Unauthorized
|
||||
|
||||
class UnauthorizedException : StatusException(Unauthorized)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.server
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.InternalServerError
|
||||
|
||||
class InternalServerErrorException : StatusException(InternalServerError)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.infendro.account.exception.server
|
||||
|
||||
import com.infendro.account.exception.StatusException
|
||||
import io.ktor.http.HttpStatusCode.Companion.NotImplemented
|
||||
|
||||
class NotImplementedException : StatusException(NotImplemented)
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.infendro.account.model
|
||||
|
||||
import com.infendro.account.model.entity.InitializationTable
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.InitializationRepository
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import io.ktor.server.application.Application
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
fun Application.initializeDatabase() {
|
||||
owner()
|
||||
}
|
||||
|
||||
private fun Application.owner() = initialize("owner") {
|
||||
val accountRepository by inject<AccountRepository>()
|
||||
|
||||
accountRepository.insert {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.username = "infendro"
|
||||
this.passwordHash = SecureHasher.hash("password", salt)
|
||||
this.passwordSalt = salt
|
||||
this.secret = "deadbeef"
|
||||
this.role = Role.OWNER
|
||||
}
|
||||
}
|
||||
|
||||
private fun Application.initialize(
|
||||
name: String,
|
||||
block: () -> Unit,
|
||||
) {
|
||||
val initializationRepository by inject<InitializationRepository>()
|
||||
|
||||
initializationRepository
|
||||
.singleOrNull { InitializationTable.name eq name }
|
||||
?.run { return }
|
||||
|
||||
block()
|
||||
|
||||
initializationRepository.insert {
|
||||
this.name = name
|
||||
}
|
||||
}
|
||||
34
backend/src/main/kotlin/com/infendro/account/model/Role.kt
Normal file
34
backend/src/main/kotlin/com/infendro/account/model/Role.kt
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.infendro.account.model
|
||||
|
||||
enum class Role(
|
||||
val children: List<Role> = listOf(),
|
||||
) {
|
||||
USER,
|
||||
OWNER(
|
||||
children = listOf(USER),
|
||||
);
|
||||
|
||||
fun hasChild(
|
||||
role: Role,
|
||||
): Boolean {
|
||||
return children.contains(role)
|
||||
}
|
||||
|
||||
companion object {
|
||||
val ALL = entries.toList()
|
||||
}
|
||||
}
|
||||
|
||||
infix fun List<Role>.except(
|
||||
roles: List<Role>,
|
||||
): List<Role> {
|
||||
return filterNot { it in roles }
|
||||
.toList()
|
||||
}
|
||||
|
||||
infix fun List<Role>.except(
|
||||
role: Role,
|
||||
): List<Role> {
|
||||
return filterNot { it == role }
|
||||
.toList()
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
|
||||
object AccessTable : LongIdTable("access", "id") {
|
||||
val tokenHash = text("token_hash")
|
||||
}
|
||||
|
||||
class AccessEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<AccessEntity>(AccessTable)
|
||||
|
||||
var tokenHash by AccessTable.tokenHash
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import com.infendro.account.model.Role
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
object AccountTable : LongIdTable("account", "id") {
|
||||
val username = text("username")
|
||||
val passwordHash = text("password_hash")
|
||||
val passwordSalt = text("password_salt")
|
||||
val secret = text("secret")
|
||||
val role = customEnumeration(
|
||||
"role",
|
||||
fromDb = {
|
||||
when (it) {
|
||||
is String -> Role.valueOf(it)
|
||||
else -> throw Error()
|
||||
}
|
||||
},
|
||||
toDb = { it.name }
|
||||
)
|
||||
}
|
||||
|
||||
class AccountEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<AccountEntity>(AccountTable)
|
||||
|
||||
var username by AccountTable.username
|
||||
var passwordHash by AccountTable.passwordHash
|
||||
var passwordSalt by AccountTable.passwordSalt
|
||||
var secret by AccountTable.secret
|
||||
var role by AccountTable.role
|
||||
|
||||
val sessions by SessionEntity referrersOn SessionTable.accountId
|
||||
|
||||
fun sessions() = transaction { sessions.toList() }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
|
||||
object InitializationTable : LongIdTable("initialization", "id") {
|
||||
val name = text("name")
|
||||
}
|
||||
|
||||
class InitializationEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<InitializationEntity>(InitializationTable)
|
||||
|
||||
var name by InitializationTable.name
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.infendro.account.model.entity
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.dao.id.EntityID
|
||||
import org.jetbrains.exposed.dao.id.LongIdTable
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
object SessionTable : LongIdTable("session", "id") {
|
||||
val tokenHash = text("token_hash")
|
||||
val accountId = reference("account_id", AccountTable.id)
|
||||
}
|
||||
|
||||
class SessionEntity(id: EntityID<Long>) : LongEntity(id) {
|
||||
companion object : LongEntityClass<SessionEntity>(SessionTable)
|
||||
|
||||
var tokenHash by SessionTable.tokenHash
|
||||
var account by AccountEntity referencedOn SessionTable.accountId
|
||||
|
||||
fun account() = transaction { account }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.AccessEntity
|
||||
|
||||
class AccessRepository : Repository<AccessEntity>(AccessEntity)
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
|
||||
class AccountRepository : Repository<AccountEntity>(AccountEntity)
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.InitializationEntity
|
||||
|
||||
class InitializationRepository : Repository<InitializationEntity>(InitializationEntity)
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import org.jetbrains.exposed.dao.LongEntity
|
||||
import org.jetbrains.exposed.dao.LongEntityClass
|
||||
import org.jetbrains.exposed.sql.Op
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
|
||||
abstract class Repository<ENTITY : LongEntity>(
|
||||
private val entityClass: LongEntityClass<ENTITY>,
|
||||
) {
|
||||
fun all(): List<ENTITY> = transaction {
|
||||
entityClass.all().toList()
|
||||
}
|
||||
|
||||
fun all(
|
||||
where: Op<Boolean>,
|
||||
): List<ENTITY> = transaction {
|
||||
entityClass.find(where).toList()
|
||||
}
|
||||
|
||||
fun all(
|
||||
where: () -> Op<Boolean>,
|
||||
): List<ENTITY> {
|
||||
return all(where())
|
||||
}
|
||||
|
||||
fun single(
|
||||
where: Op<Boolean>,
|
||||
): ENTITY = transaction {
|
||||
entityClass.find(where).single()
|
||||
}
|
||||
|
||||
fun single(
|
||||
where: () -> Op<Boolean>,
|
||||
): ENTITY {
|
||||
return single(where())
|
||||
}
|
||||
|
||||
fun singleOrNull(
|
||||
where: Op<Boolean>,
|
||||
): ENTITY? = transaction {
|
||||
entityClass.find(where).singleOrNull()
|
||||
}
|
||||
|
||||
fun singleOrNull(
|
||||
where: () -> Op<Boolean>,
|
||||
): ENTITY? {
|
||||
return singleOrNull(where())
|
||||
}
|
||||
|
||||
fun exists(
|
||||
where: Op<Boolean>,
|
||||
): Boolean {
|
||||
return all(where).isNotEmpty()
|
||||
}
|
||||
|
||||
fun exists(
|
||||
where: () -> Op<Boolean>,
|
||||
): Boolean {
|
||||
return exists(where())
|
||||
}
|
||||
|
||||
fun insert(
|
||||
block: ENTITY.() -> Unit,
|
||||
): Unit = transaction {
|
||||
entityClass.new(block)
|
||||
}
|
||||
|
||||
fun update(
|
||||
entity: ENTITY,
|
||||
block: ENTITY.() -> Unit,
|
||||
): Unit = transaction {
|
||||
entity.block()
|
||||
}
|
||||
|
||||
fun update(
|
||||
entities: Iterable<ENTITY>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
for (entity in entities) {
|
||||
update(entity, block)
|
||||
}
|
||||
}
|
||||
|
||||
fun update(
|
||||
where: Op<Boolean>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
update(all(where), block)
|
||||
}
|
||||
|
||||
fun update(
|
||||
where: () -> Op<Boolean>,
|
||||
block: ENTITY.() -> Unit,
|
||||
) {
|
||||
update(where(), block)
|
||||
}
|
||||
|
||||
fun delete(
|
||||
entity: ENTITY,
|
||||
): Unit = transaction {
|
||||
entity.delete()
|
||||
}
|
||||
|
||||
fun delete(
|
||||
entities: Iterable<ENTITY>,
|
||||
) {
|
||||
for (entity in entities) {
|
||||
delete(entity)
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(
|
||||
where: Op<Boolean>,
|
||||
) {
|
||||
delete(all(where))
|
||||
}
|
||||
|
||||
fun delete(
|
||||
where: () -> Op<Boolean>,
|
||||
) {
|
||||
delete(where())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.infendro.account.model.repository
|
||||
|
||||
import com.infendro.account.model.entity.SessionEntity
|
||||
|
||||
class SessionRepository : Repository<SessionEntity>(SessionEntity)
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.service.AccessService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/access")
|
||||
private class Access {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Access,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Access,
|
||||
val id: Long,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.access() {
|
||||
val accessService by inject<AccessService>()
|
||||
|
||||
authenticate {
|
||||
post<Access> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accessService.post(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
get<Access.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accessService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Access.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accessService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
153
backend/src/main/kotlin/com/infendro/account/routing/Account.kt
Normal file
153
backend/src/main/kotlin/com/infendro/account/routing/Account.kt
Normal file
@@ -0,0 +1,153 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.request.PostAccountRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentUsernameRequest
|
||||
import com.infendro.account.dto.request.PutAccountIdRoleRequest
|
||||
import com.infendro.account.service.AccountService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.resources.put
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.sessions.sessions
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/account")
|
||||
private class Account {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Account,
|
||||
)
|
||||
|
||||
@Resource("/current")
|
||||
class Current(
|
||||
val parent: Account,
|
||||
) {
|
||||
@Resource("/username")
|
||||
class Username(
|
||||
val parent: Current,
|
||||
)
|
||||
|
||||
@Resource("/password")
|
||||
class Password(
|
||||
val parent: Current,
|
||||
)
|
||||
|
||||
@Resource("/session")
|
||||
class Session(
|
||||
val parent: Current,
|
||||
) {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Session,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Session,
|
||||
val id: Long,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Account,
|
||||
val id: Long,
|
||||
) {
|
||||
@Resource("/role")
|
||||
class Role(
|
||||
val parent: Id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun Routing.account() {
|
||||
val accountService by inject<AccountService>()
|
||||
|
||||
post<Account> {
|
||||
val request = call.receive<PostAccountRequest>()
|
||||
|
||||
accountService.post(request)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
authenticate {
|
||||
get<Account.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
get<Account.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getCurrent(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Account.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.deleteCurrent(principal)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Current.Username> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val request = call.receive<PutAccountCurrentUsernameRequest>()
|
||||
|
||||
accountService.putCurrentUsername(principal, call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Current.Password> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val request = call.receive<PutAccountCurrentPasswordRequest>()
|
||||
|
||||
accountService.putCurrentPassword(principal, call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
get<Account.Current.Session.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
accountService.getCurrentSessionAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Account.Current.Session.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accountService.deleteCurrentSessionId(principal, call.sessions, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
delete<Account.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
accountService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
put<Account.Id.Role> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.parent.id
|
||||
val request = call.receive<PutAccountIdRoleRequest>()
|
||||
|
||||
accountService.putIdRole(principal, id, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
25
backend/src/main/kotlin/com/infendro/account/routing/Role.kt
Normal file
25
backend/src/main/kotlin/com/infendro/account/routing/Role.kt
Normal file
@@ -0,0 +1,25 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.service.RoleService
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/role")
|
||||
private class Role {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Role,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.role() {
|
||||
val roleService by inject<RoleService>()
|
||||
|
||||
get<Role.All> {
|
||||
roleService.getAll()
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.infendro.account.routing
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.request.PostSessionRequest
|
||||
import com.infendro.account.service.SessionService
|
||||
import io.ktor.http.HttpStatusCode.Companion.OK
|
||||
import io.ktor.resources.Resource
|
||||
import io.ktor.server.auth.authenticate
|
||||
import io.ktor.server.auth.principal
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.resources.delete
|
||||
import io.ktor.server.resources.get
|
||||
import io.ktor.server.resources.post
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.sessions.sessions
|
||||
import org.koin.ktor.ext.inject
|
||||
|
||||
@Resource("/session")
|
||||
private class Session {
|
||||
@Resource("/all")
|
||||
class All(
|
||||
val parent: Session,
|
||||
)
|
||||
|
||||
@Resource("/{id}")
|
||||
class Id(
|
||||
val parent: Session,
|
||||
val id: Long,
|
||||
)
|
||||
|
||||
@Resource("/current")
|
||||
class Current(
|
||||
val parent: Session,
|
||||
)
|
||||
}
|
||||
|
||||
fun Routing.session() {
|
||||
val sessionService by inject<SessionService>()
|
||||
|
||||
post<Session> {
|
||||
val request = call.receive<PostSessionRequest>()
|
||||
|
||||
sessionService.post(call.sessions, request)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
authenticate {
|
||||
get<Session.All> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.getAll(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Session.Id> { resource ->
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
val id = resource.id
|
||||
|
||||
sessionService.deleteId(principal, id)
|
||||
call.respond(OK)
|
||||
}
|
||||
|
||||
get<Session.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.getCurrent(principal)
|
||||
.also { call.respond(it) }
|
||||
}
|
||||
|
||||
delete<Session.Current> {
|
||||
val principal = call.principal<AuthenticationPrincipal>()!!
|
||||
|
||||
sessionService.deleteCurrent(principal, call.sessions)
|
||||
call.respond(OK)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.dto.response.AccessResponse
|
||||
import com.infendro.account.dto.response.PostAccessResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.model.Role.OWNER
|
||||
import com.infendro.account.model.entity.AccessTable
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.TokenGenerator
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
|
||||
class AccessService(
|
||||
private val accessRepository: AccessRepository,
|
||||
) {
|
||||
fun post(
|
||||
principal: AuthenticationPrincipal,
|
||||
): PostAccessResponse {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val token = TokenGenerator.generate()
|
||||
accessRepository.insert {
|
||||
this.tokenHash = Hasher.hash(token)
|
||||
}
|
||||
|
||||
return PostAccessResponse(
|
||||
token = token
|
||||
)
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<AccessResponse> {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accessRepository
|
||||
.all()
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val access = accessRepository
|
||||
.singleOrNull { AccessTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
accessRepository.delete(access)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.config.AuthenticationSession
|
||||
import com.infendro.account.dto.request.PostAccountRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentPasswordRequest
|
||||
import com.infendro.account.dto.request.PutAccountCurrentUsernameRequest
|
||||
import com.infendro.account.dto.request.PutAccountIdRoleRequest
|
||||
import com.infendro.account.dto.response.AccountResponse
|
||||
import com.infendro.account.dto.response.PostAccountResponse
|
||||
import com.infendro.account.dto.response.SessionResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ConflictException
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role.OWNER
|
||||
import com.infendro.account.model.Role.USER
|
||||
import com.infendro.account.model.entity.AccessTable
|
||||
import com.infendro.account.model.entity.AccountEntity
|
||||
import com.infendro.account.model.entity.AccountTable
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.AccessRepository
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.OTP
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import io.ktor.server.sessions.CurrentSession
|
||||
import io.ktor.server.sessions.clear
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
|
||||
class AccountService(
|
||||
private val accessRepository: AccessRepository,
|
||||
private val accountRepository: AccountRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
) {
|
||||
fun post(
|
||||
request: PostAccountRequest,
|
||||
): PostAccountResponse {
|
||||
val access = accessRepository
|
||||
.singleOrNull { AccessTable.tokenHash eq Hasher.hash(request.access.token) }
|
||||
?: throw UnauthorizedException()
|
||||
|
||||
accountRepository
|
||||
.singleOrNull { AccountTable.username eq request.username }
|
||||
?.run { throw ConflictException() }
|
||||
|
||||
accessRepository.delete(access)
|
||||
|
||||
val secret = OTP.generateSecret()
|
||||
accountRepository.insert {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.username = request.username
|
||||
this.passwordHash = SecureHasher.hash(request.password, salt)
|
||||
this.passwordSalt = salt
|
||||
this.secret = secret
|
||||
this.role = USER
|
||||
}
|
||||
|
||||
return PostAccountResponse(
|
||||
secret = secret
|
||||
)
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<AccountResponse> {
|
||||
if (principal.role != OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accountRepository
|
||||
.all()
|
||||
.map(AccountEntity::toResponse)
|
||||
}
|
||||
|
||||
fun getCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
): AccountResponse {
|
||||
val (account, _) = principal
|
||||
|
||||
return account.toResponse()
|
||||
}
|
||||
|
||||
fun deleteCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
) {
|
||||
if (principal.role == OWNER)
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.delete(principal.account)
|
||||
}
|
||||
|
||||
fun putCurrentUsername(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
request: PutAccountCurrentUsernameRequest,
|
||||
) {
|
||||
if (!OTP.verify(principal.account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
accountRepository.update(principal.account) {
|
||||
this.username = request.username
|
||||
}
|
||||
sessionRepository.delete(principal.account.sessions())
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
|
||||
}
|
||||
|
||||
fun putCurrentPassword(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
request: PutAccountCurrentPasswordRequest,
|
||||
) {
|
||||
if (!OTP.verify(principal.account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
accountRepository.update(principal.account) {
|
||||
val salt = SecureHasher.generateSalt()
|
||||
|
||||
this.passwordHash = SecureHasher.hash(request.password, salt)
|
||||
this.passwordSalt = salt
|
||||
}
|
||||
sessionRepository.delete(principal.account.sessions())
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
|
||||
fun getCurrentSessionAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<SessionResponse> {
|
||||
return principal.account.sessions()
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteCurrentSessionId(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
id: Long,
|
||||
) {
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (session.account().id != principal.account.id)
|
||||
throw ForbiddenException()
|
||||
|
||||
sessionRepository.delete(session)
|
||||
|
||||
if (session.id == principal.session.id)
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!principal.role.hasChild(account.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.delete(account)
|
||||
}
|
||||
|
||||
fun putIdRole(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
request: PutAccountIdRoleRequest,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!principal.role.hasChild(account.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
if (!principal.role.hasChild(request.role))
|
||||
throw ForbiddenException()
|
||||
|
||||
accountRepository.update(account) {
|
||||
role = request.role
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.dto.response.RoleResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.model.Role
|
||||
|
||||
class RoleService {
|
||||
fun getAll(): List<RoleResponse> {
|
||||
return Role.ALL
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.infendro.account.service
|
||||
|
||||
import com.infendro.account.config.AuthenticationPrincipal
|
||||
import com.infendro.account.config.AuthenticationSession
|
||||
import com.infendro.account.dto.request.PostSessionRequest
|
||||
import com.infendro.account.dto.response.SessionResponse
|
||||
import com.infendro.account.dto.response.toResponse
|
||||
import com.infendro.account.exception.client.ForbiddenException
|
||||
import com.infendro.account.exception.client.NotFoundException
|
||||
import com.infendro.account.exception.client.UnauthorizedException
|
||||
import com.infendro.account.model.Role.USER
|
||||
import com.infendro.account.model.entity.AccountTable
|
||||
import com.infendro.account.model.entity.SessionTable
|
||||
import com.infendro.account.model.repository.AccountRepository
|
||||
import com.infendro.account.model.repository.SessionRepository
|
||||
import com.infendro.account.util.Hasher
|
||||
import com.infendro.account.util.OTP
|
||||
import com.infendro.account.util.SecureHasher
|
||||
import com.infendro.account.util.TokenGenerator
|
||||
import io.ktor.server.sessions.CurrentSession
|
||||
import io.ktor.server.sessions.clear
|
||||
import io.ktor.server.sessions.set
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList
|
||||
|
||||
class SessionService(
|
||||
private val accountRepository: AccountRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
) {
|
||||
fun post(
|
||||
sessions: CurrentSession,
|
||||
request: PostSessionRequest,
|
||||
) {
|
||||
val account = accountRepository
|
||||
.singleOrNull { AccountTable.username eq request.username }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (!OTP.verify(account.secret, request.otp))
|
||||
throw UnauthorizedException()
|
||||
|
||||
if (account.passwordHash != SecureHasher.hash(request.password, account.passwordSalt))
|
||||
throw UnauthorizedException()
|
||||
|
||||
val token = TokenGenerator.generate()
|
||||
sessionRepository.insert {
|
||||
this.tokenHash = Hasher.hash(token)
|
||||
this.account = account
|
||||
}
|
||||
|
||||
sessions.set(AuthenticationSession(token))
|
||||
}
|
||||
|
||||
fun getAll(
|
||||
principal: AuthenticationPrincipal,
|
||||
): List<SessionResponse> {
|
||||
if (principal.role == USER)
|
||||
throw ForbiddenException()
|
||||
|
||||
return accountRepository
|
||||
.all { AccountTable.role inList principal.role.children }
|
||||
.flatMap { it.sessions() }
|
||||
.map { it.toResponse() }
|
||||
}
|
||||
|
||||
fun deleteId(
|
||||
principal: AuthenticationPrincipal,
|
||||
id: Long,
|
||||
) {
|
||||
if (principal.role == USER)
|
||||
throw ForbiddenException()
|
||||
|
||||
val session = sessionRepository
|
||||
.singleOrNull { SessionTable.id eq id }
|
||||
?: throw NotFoundException()
|
||||
|
||||
if (session.account().role !in principal.role.children)
|
||||
throw ForbiddenException()
|
||||
|
||||
sessionRepository.delete(session)
|
||||
}
|
||||
|
||||
fun getCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
): SessionResponse {
|
||||
return principal.session.toResponse()
|
||||
}
|
||||
|
||||
fun deleteCurrent(
|
||||
principal: AuthenticationPrincipal,
|
||||
sessions: CurrentSession,
|
||||
) {
|
||||
sessionRepository.delete(principal.session)
|
||||
|
||||
sessions.clear<AuthenticationSession>()
|
||||
}
|
||||
}
|
||||
13
backend/src/main/kotlin/com/infendro/account/util/Hasher.kt
Normal file
13
backend/src/main/kotlin/com/infendro/account/util/Hasher.kt
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import com.infendro.hash.SHA256
|
||||
|
||||
object Hasher {
|
||||
fun hash(
|
||||
value: String,
|
||||
): String {
|
||||
val bytes = SHA256.hash(value.toByteArray())
|
||||
return Hex.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
31
backend/src/main/kotlin/com/infendro/account/util/OTP.kt
Normal file
31
backend/src/main/kotlin/com/infendro/account/util/OTP.kt
Normal file
@@ -0,0 +1,31 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Base32
|
||||
import com.infendro.hash.SHA256
|
||||
import com.infendro.otp.SecretGenerator
|
||||
import com.infendro.otp.TOTP
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.ExperimentalTime
|
||||
|
||||
@OptIn(ExperimentalTime::class)
|
||||
object OTP {
|
||||
private val totp = TOTP(
|
||||
function = SHA256,
|
||||
length = 8,
|
||||
period = 30.seconds,
|
||||
)
|
||||
|
||||
fun verify(
|
||||
secret: String,
|
||||
otp: String,
|
||||
): Boolean {
|
||||
val bytes = Base32.decode(secret.toByteArray())
|
||||
return totp.verify(bytes, Clock.System.now(), otp)
|
||||
}
|
||||
|
||||
fun generateSecret(): String {
|
||||
val bytes = SecretGenerator.generate(totp.hotp.function)
|
||||
return Base32.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
val REGEX_USERNAME = """^(?=.{1,32}$)[a-z0-9]+([\-._][a-z0-9]+)*$""".toRegex()
|
||||
val REGEX_PASSWORD = """^(?=.{8,}$)[a-zA-Z0-9!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]*$""".toRegex()
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import kotlin.random.Random
|
||||
|
||||
// TODO implement PBKDF2
|
||||
object SecureHasher {
|
||||
private val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
private val random = Random.Default
|
||||
|
||||
fun hash(
|
||||
value: String,
|
||||
salt: String,
|
||||
): String {
|
||||
val spec = PBEKeySpec(value.toCharArray(), Hex.decode(salt.toByteArray()), 100_000, 256)
|
||||
return factory.generateSecret(spec).encoded
|
||||
.let { Hex.encode(it).toString() }
|
||||
}
|
||||
|
||||
fun generateSalt(): String {
|
||||
return ByteArray(16).also { random.nextBytes(it) }
|
||||
.let { Hex.encode(it).toString() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.infendro.account.util
|
||||
|
||||
import com.infendro.encoding.Hex
|
||||
import kotlin.random.Random
|
||||
|
||||
// TODO implement secure random
|
||||
object TokenGenerator {
|
||||
private val random = Random.Default
|
||||
|
||||
fun generate(): String {
|
||||
val bytes = ByteArray(32)
|
||||
.also { random.nextBytes(it) }
|
||||
return Hex.encode(bytes).toString()
|
||||
}
|
||||
}
|
||||
20
backend/src/main/resources/application.conf
Normal file
20
backend/src/main/resources/application.conf
Normal file
@@ -0,0 +1,20 @@
|
||||
ktor {
|
||||
deployment {
|
||||
port = 8080
|
||||
}
|
||||
application {
|
||||
modules = [com.infendro.account.ApplicationKt.module]
|
||||
}
|
||||
}
|
||||
database {
|
||||
host = ${DATABASE_HOST}
|
||||
username = ${DATABASE_USERNAME}
|
||||
password = ${DATABASE_PASSWORD}
|
||||
}
|
||||
security {
|
||||
cookie {
|
||||
domain = ${COOKIE_DOMAIN}
|
||||
path = ${COOKIE_PATH}
|
||||
secure = ${COOKIE_SECURE}
|
||||
}
|
||||
}
|
||||
44
backend/src/main/resources/db/migration/V1__Initial.sql
Normal file
44
backend/src/main/resources/db/migration/V1__Initial.sql
Normal file
@@ -0,0 +1,44 @@
|
||||
CREATE TABLE initialization
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
name TEXT
|
||||
UNIQUE
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE access
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
token_hash TEXT
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE account
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
username TEXT
|
||||
UNIQUE
|
||||
NOT NULL,
|
||||
password_hash TEXT
|
||||
NOT NULL,
|
||||
password_salt TEXT
|
||||
NOT NULL,
|
||||
secret TEXT
|
||||
NOT NULL,
|
||||
role TEXT
|
||||
NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE session
|
||||
(
|
||||
id BIGSERIAL
|
||||
PRIMARY KEY,
|
||||
token_hash TEXT
|
||||
NOT NULL,
|
||||
account_id BIGINT
|
||||
REFERENCES account (id) ON DELETE CASCADE
|
||||
NOT NULL
|
||||
);
|
||||
10
backend/src/main/resources/logback.xml
Normal file
10
backend/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%date{YYYY-MM-dd HH:mm:ss.SSS} %highlight(%level) %logger{0} - %message%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user