├── settings.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── Dockerfile-test ├── src ├── main │ ├── kotlin │ │ └── com │ │ │ └── personia │ │ │ ├── dto │ │ │ ├── Token.kt │ │ │ ├── Exception.kt │ │ │ ├── Node.kt │ │ │ └── User.kt │ │ │ ├── dao │ │ │ ├── user │ │ │ │ ├── UserDaoFacade.kt │ │ │ │ └── UserDaoImpl.kt │ │ │ ├── node │ │ │ │ ├── NodeDaoFacade.kt │ │ │ │ └── NodeDaoImpl.kt │ │ │ └── DatabaseFactory.kt │ │ │ ├── utils │ │ │ ├── RandomString.kt │ │ │ ├── Hasher.kt │ │ │ └── Graph.kt │ │ │ ├── plugins │ │ │ ├── Serialization.kt │ │ │ ├── Routing.kt │ │ │ ├── Authentication.kt │ │ │ └── Exception.kt │ │ │ ├── models │ │ │ ├── Node.kt │ │ │ └── User.kt │ │ │ ├── Application.kt │ │ │ ├── services │ │ │ ├── UserService.kt │ │ │ └── HierarchyService.kt │ │ │ └── routes │ │ │ ├── HierarchyRoutes.kt │ │ │ └── AuthRoutes.kt │ └── resources │ │ ├── logback.xml │ │ ├── application.conf │ │ └── application-test.conf └── test │ └── kotlin │ └── com │ └── personia │ ├── ApplicationTest.kt │ ├── Configuration.kt │ ├── services │ ├── UserServiceTest.kt │ └── NodeServiceTest.kt │ └── integrations │ ├── HierarchyTest.kt │ └── UserTest.kt ├── gradle.properties ├── Dockerfile ├── .github ├── dependabot.yml ├── pull_request_template.md └── workflows │ └── gradle.yml ├── .env-example ├── .gitignore ├── docker-compose.yml ├── docker-compose-test.yml ├── LICENSE.md ├── gradlew.bat ├── postman_collection.json ├── CODE_OF_CONDUCT.md ├── README.md └── gradlew /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "com.personia.hierarchy" -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fractalliter/ktor-postgres-backend/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /Dockerfile-test: -------------------------------------------------------------------------------- 1 | FROM gradle:7-jdk11 AS build 2 | COPY --chown=gradle:gradle . /home/gradle/src 3 | WORKDIR /home/gradle/src 4 | ENTRYPOINT ["gradle","test","--no-daemon"] -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dto/Token.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dto 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | @Serializable 6 | data class Token(val token: String) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dto/Exception.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dto 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | @Serializable 6 | data class Exception(val message: String?, val code: Int) -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dto/Node.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dto 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | @Serializable 6 | data class Node(val id: Int, val name: String, val supervisor: String) -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dto/User.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dto 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | @Serializable 6 | data class User(val id: Int? = 0, val username: String, val password: String) -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dao/user/UserDaoFacade.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dao.user 2 | 3 | import com.personia.dto.User 4 | 5 | interface UserDaoFacade { 6 | suspend fun createUser(user: User): User? 7 | suspend fun findByUsername(username: String): User? 8 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/utils/RandomString.kt: -------------------------------------------------------------------------------- 1 | package com.personia.utils 2 | 3 | fun randomString(length: Int): String { 4 | val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9') 5 | return (1..length) 6 | .map { allowedChars.random() } 7 | .joinToString("") 8 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | ktor_version=2.3.0 2 | kotlin_version=1.6.20 3 | logback_version=1.2.11 4 | kotlin.code.style=official 5 | exposed_version=0.37.3 6 | # Postgresql driver version, it can be any db driver. Also change the equivalent dependency 7 | database_driver_version=42.5.1 8 | jbcrypt_version=0.4 9 | hikaricp_version=5.0.1 10 | redis_version=0.8 -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/plugins/Serialization.kt: -------------------------------------------------------------------------------- 1 | package com.personia.plugins 2 | 3 | import io.ktor.serialization.gson.* 4 | import io.ktor.server.application.* 5 | import io.ktor.server.plugins.contentnegotiation.* 6 | 7 | fun Application.configureSerialization() { 8 | install(ContentNegotiation) { 9 | gson() 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gradle:7-jdk11 AS build 2 | COPY --chown=gradle:gradle . /home/gradle/src 3 | WORKDIR /home/gradle/src 4 | RUN gradle shadowJar --no-daemon 5 | 6 | FROM openjdk:11 7 | EXPOSE 8080:8080 8 | RUN mkdir /app 9 | COPY --from=build /home/gradle/src/build/libs/*.jar /app/ 10 | ENTRYPOINT ["java","-jar","/app/com.personia.hierarchy-0.0.1-all.jar"] -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/models/Node.kt: -------------------------------------------------------------------------------- 1 | package com.personia.models 2 | 3 | import org.jetbrains.exposed.sql.Table 4 | 5 | object Nodes : Table() { 6 | val id = integer("id").autoIncrement() 7 | val name = varchar("name", 128).uniqueIndex() 8 | val supervisor = varchar("supervisor", 128) 9 | override val primaryKey = PrimaryKey(id) 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/models/User.kt: -------------------------------------------------------------------------------- 1 | package com.personia.models 2 | 3 | import org.jetbrains.exposed.sql.Table 4 | 5 | object Users : Table() { 6 | val id = integer("id").autoIncrement() 7 | val username = varchar("username", 128).uniqueIndex() 8 | val password = varchar("password", 128) 9 | override val primaryKey = PrimaryKey(id) 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dao/node/NodeDaoFacade.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dao.node 2 | 3 | import com.personia.dto.Node 4 | 5 | interface NodeDaoFacade { 6 | suspend fun allConnections(): List 7 | suspend fun findByName(name: String): Node? 8 | suspend fun updateSupervisor(name: String, supervisor: String): Boolean 9 | suspend fun addNewNode(name: String, supervisor: String): Node? 10 | suspend fun upsertNode(name: String, supervisor: String): Node? 11 | } -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/utils/Hasher.kt: -------------------------------------------------------------------------------- 1 | package com.personia.utils 2 | 3 | import com.personia.dto.User 4 | import org.mindrot.jbcrypt.BCrypt 5 | 6 | object Hasher { 7 | 8 | /** 9 | * Check if the password matches the User's password 10 | */ 11 | fun checkPassword(attempt: String, user: User) = BCrypt.checkpw(attempt, user.password) 12 | 13 | /** 14 | * Returns the hashed version of the supplied password 15 | */ 16 | fun hashPassword(password: String): String = BCrypt.hashpw(password, BCrypt.gensalt()) 17 | 18 | } -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gradle" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "monthly" 12 | -------------------------------------------------------------------------------- /.env-example: -------------------------------------------------------------------------------- 1 | WEB_PORT=8080 2 | WEB_DB_URL=jdbc:postgresql://db:5432 3 | WEB_DATABASE=personia 4 | WEB_DB_USERNAME=postgres 5 | WEB_DB_PASSWORD=postgres 6 | JWT_SECRET=secret 7 | JWT_ISSUER=http://0.0.0.0:8080/ 8 | JWT_AUDIENCE=http://0.0.0.0:8080/hierarchy 9 | JWT_REALM=hierarchy 10 | JWT_EXPIRATION=31536000 11 | AUTH_DB_VENDOR=POSTGRES 12 | AUTH_DB_ADDRESS=auth-db 13 | AUTH_DB_DATABASE=keycloak 14 | AUTH_DB_USER=keycloak 15 | AUTH_DB_SCHEMA=public 16 | AUTH_DB_PASSWORD=password 17 | AUTH_SERVER_USER=manager 18 | AUTH_SERVER_PASSWORD=manager 19 | AUTH_ADMIN_USER=admin 20 | AUTH_ADMIN_PASSWORD=admin -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /tmp/ 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | .env 39 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/Application.kt: -------------------------------------------------------------------------------- 1 | package com.personia 2 | 3 | import com.personia.dao.DatabaseFactory 4 | import com.personia.plugins.configureAuthentication 5 | import com.personia.plugins.configureException 6 | import com.personia.plugins.configureRouting 7 | import com.personia.plugins.configureSerialization 8 | import io.ktor.server.application.* 9 | import io.ktor.server.netty.* 10 | 11 | fun main(args: Array): Unit = EngineMain.main(args) 12 | 13 | fun Application.module() { 14 | configureAuthentication(environment.config) 15 | DatabaseFactory.init(environment.config) 16 | configureSerialization() 17 | configureRouting(environment.config) 18 | configureException() 19 | } 20 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/plugins/Routing.kt: -------------------------------------------------------------------------------- 1 | package com.personia.plugins 2 | 3 | import com.personia.routes.authRouting 4 | import com.personia.routes.hierarchyRouting 5 | import com.personia.services.nodeService 6 | import com.personia.services.userService 7 | import io.ktor.server.application.* 8 | import io.ktor.server.auth.* 9 | import io.ktor.server.config.* 10 | import io.ktor.server.response.* 11 | import io.ktor.server.routing.* 12 | 13 | fun Application.configureRouting(config: ApplicationConfig) { 14 | 15 | routing { 16 | get("/") { 17 | call.respondText("Hello World!") 18 | } 19 | authenticate("auth-jwt") { 20 | hierarchyRouting(nodeService) 21 | } 22 | authRouting(config, userService) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/ApplicationTest.kt: -------------------------------------------------------------------------------- 1 | package com.personia 2 | 3 | import com.personia.plugins.configureRouting 4 | import io.ktor.client.request.* 5 | import io.ktor.client.statement.* 6 | import io.ktor.http.* 7 | import io.ktor.server.config.* 8 | import io.ktor.server.testing.* 9 | import kotlin.test.Test 10 | import kotlin.test.assertEquals 11 | 12 | class ApplicationTest { 13 | @Test 14 | fun testRoot() = testApplication { 15 | environment { 16 | config = ApplicationConfig("application-test.conf") 17 | } 18 | application { 19 | configureRouting(environment.config) 20 | } 21 | client.get("/").apply { 22 | assertEquals(HttpStatusCode.OK, status) 23 | assertEquals("Hello World!", bodyAsText()) 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### All Submissions: 2 | 3 | - [ ] The commit message follows our guidelines 4 | - [ ] Tests for the changes have been added (for bug fixes/features) 5 | - [ ] Docs have been added / updated (for bug fixes / features) 6 | 7 | 8 | 9 | ### How to test 10 | 11 | 12 | 13 | ### New Feature Submissions: 14 | 15 | 1. [ ] Does your submission pass tests? 16 | 2. [ ] Have you cleaned up your code locally before submission? 17 | 18 | ### Changes to Core Features: 19 | 20 | * [ ] Have you added an explanation of what your changes do and why you'd like us to include them? 21 | * [ ] Have you written new tests for your core changes, as applicable? 22 | * [ ] Have you successfully run tests with your changes locally? -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | 3 | services: 4 | web: 5 | build: . 6 | environment: 7 | PORT: ${WEB_PORT} 8 | JDBC_URL: ${WEB_DB_URL} 9 | DATABASE: ${WEB_DATABASE} 10 | DB_USERNAME: ${WEB_DB_USERNAME} 11 | DB_PASSWORD: ${WEB_DB_PASSWORD} 12 | JWT_SECRET: secret 13 | JWT_ISSUER: ${JWT_ISSUER} 14 | JWT_AUDIENCE: ${JWT_AUDIENCE} 15 | JWT_REALM: ${JWT_REALM} 16 | JWT_EXPIRATION: ${JWT_EXPIRATION} 17 | ports: 18 | - "${WEB_PORT}:${WEB_PORT}" 19 | depends_on: 20 | - db 21 | db: 22 | image: postgres 23 | volumes: 24 | - ./tmp/db:/var/lib/postgresql/data 25 | environment: 26 | POSTGRES_DB: ${WEB_DATABASE} 27 | POSTGRES_USER: ${WEB_DB_USERNAME} 28 | POSTGRES_PASSWORD: ${WEB_DB_PASSWORD} 29 | ports: 30 | - "5432:5432" 31 | healthcheck: 32 | test: [ "CMD-SHELL", "pg_isready -U postgres" ] 33 | interval: 1s -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/Configuration.kt: -------------------------------------------------------------------------------- 1 | package com.personia 2 | 3 | import com.personia.plugins.configureRouting 4 | import io.ktor.client.* 5 | import io.ktor.client.plugins.contentnegotiation.* 6 | import io.ktor.serialization.gson.* 7 | import io.ktor.server.config.* 8 | import io.ktor.server.testing.* 9 | import kotlin.test.assertNotNull 10 | 11 | fun ApplicationTestBuilder.configIntegrationTestApp(): HttpClient { 12 | val client = createClient { 13 | install(ContentNegotiation) { 14 | gson() 15 | } 16 | } 17 | assertNotNull(client) 18 | environment { 19 | config = ApplicationConfig("application-test.conf") 20 | } 21 | application { 22 | configureRouting(environment.config) 23 | } 24 | return client 25 | } 26 | 27 | fun ApplicationTestBuilder.configureUnitTestApp(){ 28 | createClient { } 29 | environment { 30 | config = ApplicationConfig("application-test.conf") 31 | } 32 | } -------------------------------------------------------------------------------- /docker-compose-test.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | 3 | services: 4 | testweb: 5 | build: 6 | context: . 7 | dockerfile: ./Dockerfile-test 8 | environment: 9 | PORT: 8080 10 | JDBC_URL: "jdbc:postgresql://testdb:5432" 11 | DATABASE: personia_test 12 | DB_USERNAME: postgres 13 | DB_PASSWORD: postgres 14 | JWT_SECRET: secret 15 | JWT_ISSUER: "http://0.0.0.0:8080/" 16 | JWT_AUDIENCE: "http://0.0.0.0:8080/hierarchy" 17 | JWT_REALM: "Access to 'hierarchy'" 18 | JWT_EXPIRATION: 31536000 19 | ports: 20 | - "8080:8080" 21 | depends_on: 22 | - testdb 23 | 24 | testdb: 25 | image: postgres 26 | volumes: 27 | - ./tmp/testdb:/var/lib/postgresql/testdata 28 | environment: 29 | POSTGRES_DB: personia_test 30 | POSTGRES_USER: postgres 31 | POSTGRES_PASSWORD: postgres 32 | ports: 33 | - "5432:5432" 34 | healthcheck: 35 | test: [ "CMD-SHELL", "pg_isready -U postgres" ] 36 | interval: 1s 37 | -------------------------------------------------------------------------------- /src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | ktor { 2 | deployment { 3 | port = 3000 4 | port = ${?PORT} 5 | } 6 | application { 7 | modules = [ com.personia.ApplicationKt.module ] 8 | } 9 | database { 10 | driverClassName = "org.postgresql.Driver" 11 | jdbcURL = "jdbc:postgresql://localhost:5432" 12 | jdbcURL = ${?JDBC_URL} 13 | database = "personia" 14 | database = ${?DATABASE} 15 | user ="postgres" 16 | user = ${?DP_USERNAME} 17 | password = "postgres" 18 | password = ${?DB_PASSWORD} 19 | maxPoolSize = 50 20 | maxPoolSize = ${?MAX_DATABASE_POOL_SIZE} 21 | autoCommit = false 22 | autoCommit = ${?DATABASE_AUTO_COMMIT} 23 | } 24 | } 25 | jwt { 26 | secret = "secret" 27 | secret = ${?JWT_SECRET} 28 | issuer = "http://0.0.0.0:3000/" 29 | issuer = ${?JWT_ISSUER} 30 | audience = "http://0.0.0.0:3000/hierarchy" 31 | audience = ${?JWT_AUDIENCE} 32 | realm = "Access to 'hierarchy'" 33 | realm = ${?JWT_REALM} 34 | expiration = 31536000 35 | expiration = ${?JWT_EXPIRATION} 36 | } -------------------------------------------------------------------------------- /src/main/resources/application-test.conf: -------------------------------------------------------------------------------- 1 | ktor { 2 | deployment { 3 | port = 3000 4 | port = ${?PORT} 5 | } 6 | application { 7 | modules = [ com.personia.ApplicationKt.module ] 8 | } 9 | database { 10 | driverClassName = "org.postgresql.Driver" 11 | jdbcURL = "jdbc:postgresql://localhost:5432" 12 | jdbcURL = ${?JDBC_URL} 13 | database = "personia_test" 14 | database = ${?DATABASE} 15 | user = "postgres" 16 | user = ${?DP_USERNAME} 17 | password = "postgres" 18 | password = ${?DB_PASSWORD} 19 | maxPoolSize = 2 20 | maxPoolSize = ${?MAX_DATABASE_POOL_SIZE} 21 | autoCommit = false 22 | autoCommit = ${?DATABASE_AUTO_COMMIT} 23 | } 24 | } 25 | jwt { 26 | secret = "secret" 27 | secret = ${?JWT_SECRET} 28 | issuer = "http://0.0.0.0:8080/" 29 | issuer = ${?JWT_ISSUER} 30 | audience = "http://0.0.0.0:8080/hierarchy" 31 | audience = ${?JWT_AUDIENCE} 32 | realm = "Access to 'hierarchy'" 33 | realm = ${?JWT_REALM} 34 | expiration = 31536000 35 | expiration = ${?JWT_EXPIRATION} 36 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/services/UserService.kt: -------------------------------------------------------------------------------- 1 | package com.personia.services 2 | 3 | import com.personia.dao.user.UserDaoFacade 4 | import com.personia.dao.user.userDAO 5 | import com.personia.dto.User 6 | import com.personia.utils.Hasher 7 | import io.ktor.server.plugins.* 8 | 9 | class UserService(private val userRepository: UserDaoFacade) { 10 | 11 | suspend fun createUser(user: User): User? { 12 | val hashedPassword = Hasher.hashPassword(user.password) 13 | val newUser = User(username = user.username, password = hashedPassword) 14 | return userRepository.createUser(newUser) 15 | } 16 | 17 | suspend fun loginUser(username: String, password: String): Boolean { 18 | val user = userRepository.findByUsername(username) 19 | if (user != null) { 20 | if (Hasher.checkPassword(password, user)) return true 21 | else { 22 | throw AssertionError("Wrong Password") 23 | } 24 | } else throw NotFoundException("user not found") 25 | } 26 | } 27 | 28 | val userService = UserService(userDAO) -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Elias Rahmani 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dao/user/UserDaoImpl.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dao.user 2 | 3 | import com.personia.dao.DatabaseFactory.dbQuery 4 | import com.personia.dto.User 5 | import com.personia.models.Users 6 | import org.jetbrains.exposed.sql.ResultRow 7 | import org.jetbrains.exposed.sql.insert 8 | import org.jetbrains.exposed.sql.select 9 | 10 | class UserDaoImpl : UserDaoFacade { 11 | 12 | private fun resultRowToNode(row: ResultRow) = User( 13 | id = row[Users.id], 14 | username = row[Users.username], 15 | password = row[Users.password], 16 | ) 17 | 18 | override suspend fun createUser(user: User): User? = dbQuery { 19 | val insertStatement = Users.insert { 20 | it[username] = user.username 21 | it[password] = user.password 22 | } 23 | insertStatement.resultedValues?.singleOrNull()?.let(::resultRowToNode) 24 | } 25 | 26 | override suspend fun findByUsername(username: String): User? = dbQuery { 27 | Users 28 | .select { Users.username eq username } 29 | .map(::resultRowToNode).singleOrNull() 30 | } 31 | } 32 | 33 | val userDAO = UserDaoImpl() -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/services/UserServiceTest.kt: -------------------------------------------------------------------------------- 1 | package com.personia.services 2 | 3 | import com.personia.configureUnitTestApp 4 | import com.personia.dto.User 5 | import com.personia.utils.randomString 6 | import io.ktor.server.testing.* 7 | import org.junit.Test 8 | import kotlin.test.assertEquals 9 | import kotlin.test.assertNotEquals 10 | import kotlin.test.assertNotNull 11 | import kotlin.test.assertTrue 12 | 13 | class UserServiceTest { 14 | private val username = randomString(12) 15 | private val password = randomString(16) 16 | 17 | @Test 18 | fun createUser() = testApplication { 19 | configureUnitTestApp() 20 | val user = userService.createUser( 21 | User( 22 | username = username, 23 | password = password 24 | ) 25 | ) 26 | 27 | assertNotNull(user) 28 | assertNotNull(user.id) 29 | assertEquals(username, user.username) 30 | assertNotEquals(password, user.password) 31 | } 32 | 33 | @Test 34 | fun loginUser() = testApplication { 35 | configureUnitTestApp() 36 | userService.createUser( 37 | User( 38 | username = username, 39 | password = password 40 | ) 41 | ) 42 | val res = userService.loginUser(username, password) 43 | assertTrue(res) 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/plugins/Authentication.kt: -------------------------------------------------------------------------------- 1 | package com.personia.plugins 2 | 3 | import com.auth0.jwt.JWT 4 | import com.auth0.jwt.algorithms.Algorithm 5 | import io.ktor.http.* 6 | import io.ktor.server.application.* 7 | import io.ktor.server.auth.* 8 | import io.ktor.server.auth.jwt.* 9 | import io.ktor.server.config.* 10 | import io.ktor.server.response.* 11 | 12 | fun Application.configureAuthentication(config: ApplicationConfig) { 13 | val issuer = config.property("jwt.issuer").getString() 14 | val myRealm = config.property("jwt.realm").getString() 15 | val secret = config.property("jwt.secret").getString() 16 | val audience = config.property("jwt.audience").getString() 17 | 18 | install(Authentication) { 19 | jwt("auth-jwt") { 20 | realm = myRealm 21 | verifier( 22 | JWT 23 | .require(Algorithm.HMAC256(secret)) 24 | .withAudience(audience) 25 | .withIssuer(issuer) 26 | .build() 27 | ) 28 | validate { credential -> 29 | if (!credential.payload.getClaim("username").asString().isNullOrEmpty()) { 30 | JWTPrincipal(credential.payload) 31 | } else { 32 | null 33 | } 34 | } 35 | challenge { _, _ -> 36 | call.respond(HttpStatusCode.Unauthorized, "Token is not valid or has expired") 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/routes/HierarchyRoutes.kt: -------------------------------------------------------------------------------- 1 | package com.personia.routes 2 | 3 | import com.personia.services.NodeService 4 | 5 | import io.ktor.http.* 6 | import io.ktor.server.application.* 7 | import io.ktor.server.request.* 8 | import io.ktor.server.response.* 9 | import io.ktor.server.routing.* 10 | 11 | fun Route.hierarchyRouting(nodeService: NodeService) { 12 | route("hierarchy") { 13 | get { 14 | call.respond(nodeService.getHierarchy()) 15 | } 16 | get("{name?}") { 17 | val name = call.parameters["name"] ?: return@get call.respondText( 18 | "Missing name", 19 | status = HttpStatusCode.BadRequest 20 | ) 21 | val employee = 22 | nodeService.findByName(name) ?: return@get call.respondText( 23 | "No employee with name $name", 24 | status = HttpStatusCode.NotFound 25 | ) 26 | call.respond(employee) 27 | } 28 | 29 | get("{name?}/supervisors") { 30 | val name = call.parameters["name"] ?: return@get call.respondText( 31 | "Missing name", 32 | status = HttpStatusCode.BadRequest 33 | ) 34 | val level = call.request.queryParameters["level"]?.toInt() ?: 2 35 | 36 | val response = nodeService.retrieveSupervisors(name, level) 37 | call.respond(response) 38 | } 39 | post { 40 | val hierarchy = call.receive>() 41 | val response = nodeService.createHierarchy(hierarchy) 42 | call.respond(response) 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/routes/AuthRoutes.kt: -------------------------------------------------------------------------------- 1 | package com.personia.routes 2 | 3 | import com.auth0.jwt.JWT 4 | import com.auth0.jwt.algorithms.Algorithm 5 | import com.personia.dto.Token 6 | import com.personia.dto.User 7 | import com.personia.services.UserService 8 | import io.ktor.http.* 9 | import io.ktor.server.application.* 10 | import io.ktor.server.config.* 11 | import io.ktor.server.request.* 12 | import io.ktor.server.response.* 13 | import io.ktor.server.routing.* 14 | import java.util.* 15 | 16 | fun Route.authRouting(config: ApplicationConfig, userService: UserService) { 17 | val secret = config.property("jwt.secret").getString() 18 | val issuer = config.property("jwt.issuer").getString() 19 | val audience = config.property("jwt.audience").getString() 20 | val expiration: Int = config.property("jwt.expiration").getString().toInt() 21 | 22 | post("/login") { 23 | val user = call.receive() 24 | val userStatus = userService.loginUser(user.username, user.password) 25 | if (userStatus) { 26 | val token = JWT.create() 27 | .withAudience(audience) 28 | .withIssuer(issuer) 29 | .withClaim("username", user.username) 30 | .withExpiresAt(Date(System.currentTimeMillis() + expiration)) 31 | .sign(Algorithm.HMAC256(secret)) 32 | val response = Token(token) 33 | call.respond(response) 34 | } else call.respond(HttpStatusCode.Unauthorized, "username/password is wrong") 35 | } 36 | 37 | 38 | post("/signup") { 39 | val user = call.receive() 40 | userService.createUser(user) 41 | call.respond(HttpStatusCode.Created, "User singed up") 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dao/node/NodeDaoImpl.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dao.node 2 | 3 | import com.personia.dao.DatabaseFactory.dbQuery 4 | import com.personia.dto.Node 5 | import com.personia.models.Nodes 6 | import org.jetbrains.exposed.sql.* 7 | 8 | class NodeDaoFacadeImp : NodeDaoFacade { 9 | 10 | private fun resultRowToNode(row: ResultRow) = Node( 11 | id = row[Nodes.id], 12 | name = row[Nodes.name], 13 | supervisor = row[Nodes.supervisor], 14 | ) 15 | 16 | override suspend fun allConnections(): List = dbQuery { 17 | Nodes.selectAll().map(::resultRowToNode) 18 | } 19 | 20 | override suspend fun addNewNode(name: String, supervisor: String): Node? = dbQuery { 21 | val insertStatement = Nodes.insert { 22 | it[Nodes.name] = name 23 | it[Nodes.supervisor] = supervisor 24 | } 25 | insertStatement.resultedValues?.singleOrNull()?.let(::resultRowToNode) 26 | } 27 | 28 | override suspend fun findByName(name: String): Node? = dbQuery { 29 | Nodes 30 | .select { Nodes.name eq name } 31 | .map(::resultRowToNode) 32 | .singleOrNull() 33 | } 34 | 35 | override suspend fun updateSupervisor(name: String, supervisor: String): Boolean = dbQuery { 36 | Nodes.update({ Nodes.name eq name }) { 37 | it[Nodes.supervisor] = supervisor 38 | } > 0 39 | } 40 | 41 | override suspend fun upsertNode(name: String, supervisor: String): Node? = dbQuery { 42 | val node: Node? = Nodes.select { Nodes.name eq name }.map(::resultRowToNode) 43 | .singleOrNull() 44 | if (node != null) { 45 | updateSupervisor(name, supervisor) 46 | findByName(name) 47 | } else addNewNode(name, supervisor) 48 | } 49 | } 50 | 51 | val nodeDAO: NodeDaoFacade = NodeDaoFacadeImp() -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/services/NodeServiceTest.kt: -------------------------------------------------------------------------------- 1 | package com.personia.services 2 | 3 | import com.personia.configureUnitTestApp 4 | import io.ktor.server.testing.* 5 | import org.junit.Test 6 | import kotlin.test.assertNotEquals 7 | import kotlin.test.assertNotNull 8 | 9 | class NodeServiceTest { 10 | 11 | @Test 12 | fun getHierarchy() = testApplication { 13 | configureUnitTestApp() 14 | val hierarchy = nodeService.getHierarchy() 15 | assertNotNull(hierarchy) 16 | } 17 | 18 | @Test 19 | fun findByName() = testApplication { 20 | configureUnitTestApp() 21 | nodeService.createHierarchy( 22 | mapOf( 23 | "Pete" to "Nick", 24 | "Barbara" to "Nick", 25 | "Nick" to "Sophie", 26 | "Sophie" to "Jonas" 27 | ) 28 | ) 29 | 30 | val node = nodeService.findByName("Pete") 31 | assertNotNull(node) 32 | } 33 | 34 | @Test 35 | fun createHierarchy() = testApplication { 36 | configureUnitTestApp() 37 | val response = nodeService.createHierarchy( 38 | mapOf( 39 | "Pete" to "Nick", 40 | "Barbara" to "Nick", 41 | "Nick" to "Sophie", 42 | "Sophie" to "Jonas" 43 | ) 44 | ) 45 | assertNotNull(response) 46 | } 47 | 48 | @Test 49 | fun retrieveSupervisors() = testApplication { 50 | configureUnitTestApp() 51 | nodeService.createHierarchy( 52 | mapOf( 53 | "Pete" to "Nick", 54 | "Barbara" to "Nick", 55 | "Nick" to "Sophie", 56 | "Sophie" to "Jonas" 57 | ) 58 | ) 59 | val supervisors = nodeService.retrieveSupervisors("Pete", 1) 60 | assertNotNull(supervisors) 61 | assertNotEquals(supervisors.size, 0) 62 | } 63 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/services/HierarchyService.kt: -------------------------------------------------------------------------------- 1 | package com.personia.services 2 | 3 | import com.personia.dao.node.NodeDaoFacade 4 | import com.personia.dao.node.nodeDAO 5 | import com.personia.dto.Node 6 | import com.personia.utils.Graph 7 | import io.ktor.server.plugins.* 8 | 9 | class NodeService(private val nodeRepository: NodeDaoFacade) { 10 | suspend fun getHierarchy(): HashMap> { 11 | val graph = Graph() 12 | val hierarchy = nodeRepository.allConnections() 13 | hierarchy.forEach { (_, node, supervisor) -> graph.connect(supervisor, node) } 14 | val root = graph.findRoot().root 15 | val dfs = root?.let { graph.dfs(it) }!! 16 | val tempMap = graph.transformToNestedMap(dfs) 17 | val rootValue = tempMap[root] ?: mapOf() 18 | return hashMapOf(root to rootValue) 19 | } 20 | 21 | suspend fun findByName(name: String): Node? = nodeRepository.findByName(name) 22 | 23 | @kotlin.jvm.Throws(java.lang.AssertionError::class) 24 | suspend fun createHierarchy(hierarchy: Map): HashMap> { 25 | val graph = Graph() 26 | hierarchy.forEach { (node, supervisor) -> graph.connect(supervisor, node) } 27 | val root = graph.findRoot().root 28 | val dfs = root?.let { graph.dfs(it) }!! 29 | hierarchy.forEach { (node, supervisor) -> nodeRepository.upsertNode(node, supervisor) } 30 | val tempMap = graph.transformToNestedMap(dfs) 31 | val rootValue = tempMap[root] ?: mapOf() 32 | return hashMapOf(root to rootValue) 33 | } 34 | 35 | suspend fun retrieveSupervisors(name: String, level: Int): HashMap?> { 36 | findByName(name) ?: throw NotFoundException("User not found") 37 | val graph = Graph() 38 | nodeRepository.allConnections().forEach { graph.connect(it.name, it.supervisor) } 39 | val visited = graph.dfs(name, level) 40 | val tmpMap = graph.transformToNestedMap(visited) 41 | return hashMapOf(name to tmpMap[name]) 42 | } 43 | 44 | } 45 | 46 | val nodeService = NodeService(nodeDAO) -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/integrations/HierarchyTest.kt: -------------------------------------------------------------------------------- 1 | package com.personia.integrations 2 | 3 | import com.personia.configIntegrationTestApp 4 | import com.personia.dto.Token 5 | import com.personia.utils.randomString 6 | import io.ktor.client.* 7 | import io.ktor.client.call.* 8 | import io.ktor.client.request.* 9 | import io.ktor.client.statement.* 10 | import io.ktor.http.* 11 | import io.ktor.server.testing.* 12 | import kotlin.test.Test 13 | import kotlin.test.assertEquals 14 | import kotlin.test.assertTrue 15 | 16 | class HierarchyTest { 17 | @Test 18 | fun testHierarchy() = testApplication { 19 | val client = configIntegrationTestApp() 20 | val token = authenticate(client) 21 | val responseHierarchy = client.post("/hierarchy") { 22 | contentType(ContentType.Application.Json) 23 | header("Authorization", "Bearer $token") 24 | setBody(mapOf("Nick" to "Sophie", "Sophie" to "Jonas", "Pete" to "Nick", "Barbara" to "Nick")) 25 | } 26 | assertEquals(HttpStatusCode.OK, responseHierarchy.status) 27 | assertTrue(responseHierarchy.bodyAsText().contains("Jonas")) 28 | } 29 | 30 | @Test 31 | fun testSupervisor() = testApplication { 32 | val client = configIntegrationTestApp() 33 | val token = authenticate(client) 34 | val response = client.get("hierarchy/Nick/supervisors") { 35 | contentType(ContentType.Application.Json) 36 | header("Authorization", "Bearer $token") 37 | } 38 | assertEquals(HttpStatusCode.OK, response.status) 39 | assertTrue(response.bodyAsText().contains("Jonas")) 40 | } 41 | 42 | private suspend fun authenticate(client: HttpClient): String?{ 43 | val credential = mapOf( 44 | "username" to randomString(10), 45 | "password" to randomString(10) 46 | ) 47 | client.post("/signup") { 48 | contentType(ContentType.Application.Json) 49 | setBody(credential) 50 | } 51 | val responseLogin = client.post("/login") { 52 | contentType(ContentType.Application.Json) 53 | setBody(credential) 54 | } 55 | return responseLogin.body()?.token 56 | 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/dao/DatabaseFactory.kt: -------------------------------------------------------------------------------- 1 | package com.personia.dao 2 | 3 | import com.personia.models.Nodes 4 | import com.personia.models.Users 5 | import com.zaxxer.hikari.HikariConfig 6 | import com.zaxxer.hikari.HikariDataSource 7 | import io.ktor.server.config.* 8 | import kotlinx.coroutines.Dispatchers 9 | import org.jetbrains.exposed.sql.Database 10 | import org.jetbrains.exposed.sql.SchemaUtils 11 | import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction 12 | import org.jetbrains.exposed.sql.transactions.transaction 13 | 14 | object DatabaseFactory { 15 | fun init(config: ApplicationConfig) { 16 | val driverClassName = config.property("ktor.database.driverClassName").getString() 17 | val jdbcURL = config.property("ktor.database.jdbcURL").getString() 18 | val maxPoolSize = config.property("ktor.database.maxPoolSize").getString() 19 | val autoCommit = config.property("ktor.database.autoCommit").getString() 20 | val username = config.property("ktor.database.user").getString() 21 | val password = config.property("ktor.database.password").getString() 22 | val defaultDatabase = config.property("ktor.database.database").getString() 23 | val connectionPool = createHikariDataSource( 24 | url = "$jdbcURL/$defaultDatabase?user=$username&password=$password", 25 | driver = driverClassName, 26 | maxPoolSize.toInt(), 27 | autoCommit.toBoolean() 28 | ) 29 | val database = Database.connect(connectionPool) 30 | transaction(database) { 31 | SchemaUtils.create(Nodes) 32 | SchemaUtils.create(Users) 33 | } 34 | } 35 | 36 | private fun createHikariDataSource( 37 | url: String, 38 | driver: String, 39 | maxPoolSize: Int, 40 | autoCommit: Boolean 41 | ) = HikariDataSource(HikariConfig().apply { 42 | driverClassName = driver 43 | jdbcUrl = url 44 | maximumPoolSize = maxPoolSize 45 | isAutoCommit = autoCommit 46 | transactionIsolation = "TRANSACTION_REPEATABLE_READ" 47 | validate() 48 | }) 49 | 50 | suspend fun dbQuery(block: suspend () -> T): T = 51 | newSuspendedTransaction(Dispatchers.IO) { block() } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/plugins/Exception.kt: -------------------------------------------------------------------------------- 1 | package com.personia.plugins 2 | 3 | import com.personia.dto.Exception 4 | import io.ktor.http.* 5 | import io.ktor.server.application.* 6 | import io.ktor.server.plugins.* 7 | import io.ktor.server.plugins.statuspages.* 8 | import io.ktor.server.response.* 9 | import java.sql.SQLException 10 | 11 | fun Application.configureException() { 12 | install(StatusPages) { 13 | exception { call, cause -> 14 | 15 | val log = call.application.environment.log 16 | when (cause) { 17 | is AssertionError -> { 18 | log.info(cause.message) 19 | call.response.status(HttpStatusCode.BadRequest) 20 | call.respond( 21 | Exception(cause.message, HttpStatusCode.BadRequest.value) 22 | ) 23 | } 24 | 25 | is SecurityException -> { 26 | log.info(cause.message) 27 | call.response.status(HttpStatusCode.Forbidden) 28 | call.respond( 29 | Exception("You are a bad guy", HttpStatusCode.Forbidden.value), 30 | ) 31 | } 32 | 33 | is SQLException -> { 34 | log.info(cause.message) 35 | call.response.status(HttpStatusCode.BadRequest) 36 | call.respond( 37 | Exception( 38 | "duplicate key value violates unique constraint.", 39 | HttpStatusCode.BadRequest.value 40 | ), 41 | ) 42 | } 43 | 44 | is NotFoundException -> { 45 | log.error(cause.message) 46 | call.response.status(HttpStatusCode.NotFound) 47 | call.respond( 48 | Exception(cause.message, HttpStatusCode.NotFound.value), 49 | ) 50 | } 51 | 52 | is java.lang.Exception -> { 53 | log.error(cause.message) 54 | call.response.status(HttpStatusCode.InternalServerError) 55 | call.respond( 56 | Exception(cause.message, HttpStatusCode.InternalServerError.value), 57 | ) 58 | } 59 | } 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time 6 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 7 | 8 | name: Java CI with Gradle 9 | 10 | on: 11 | push: 12 | branches: [ "main" ] 13 | pull_request: 14 | branches: [ "main" ] 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | build: 21 | 22 | runs-on: ubuntu-latest 23 | services: 24 | postgres: 25 | image: postgres 26 | ports: 27 | - 5432:5432 28 | env: 29 | POSTGRES_DB: personia_test 30 | POSTGRES_USER: postgres 31 | POSTGRES_PASSWORD: postgres 32 | options: >- 33 | --health-cmd pg_isready 34 | --health-interval 10s 35 | --health-timeout 5s 36 | --health-retries 5 37 | steps: 38 | - uses: actions/checkout@v4 39 | - name: Set up JDK 17 40 | uses: actions/setup-java@v4 41 | with: 42 | java-version: '17' 43 | distribution: 'temurin' 44 | - name: Setup Gradle 45 | uses: gradle/actions/setup-gradle@417ae3ccd767c252f5661f1ace9f835f9654f2b5 # v3.1.0 46 | - name: Build with Gradle 47 | run: ./gradlew build 48 | env: 49 | POSTGRES_DB: personia_test 50 | POSTGRES_USER: postgres 51 | POSTGRES_PASSWORD: postgres 52 | JDBC_URL: jdbc:postgresql://localhost:5432 53 | DATABASE: personia_test 54 | DB_USERNAME: postgres 55 | DB_PASSWORD: postgres 56 | JWT_SECRET: secret 57 | JWT_ISSUER: http://0.0.0.0:8080/ 58 | JWT_AUDIENCE: http://0.0.0.0:8080/hierarchy 59 | JWT_REALM: Access to 'hierarchy' 60 | JWT_EXPIRATION: 31536000 61 | - name: Test with Gradle 62 | run: ./gradlew test jacocoTestReport 63 | env: 64 | POSTGRES_DB: personia_test 65 | POSTGRES_USER: postgres 66 | POSTGRES_PASSWORD: postgres 67 | JDBC_URL: jdbc:postgresql://localhost:5432 68 | DATABASE: personia_test 69 | DB_USERNAME: postgres 70 | DB_PASSWORD: postgres 71 | JWT_SECRET: secret 72 | JWT_ISSUER: http://0.0.0.0:8080/ 73 | JWT_AUDIENCE: http://0.0.0.0:8080/hierarchy 74 | JWT_REALM: Access to 'hierarchy' 75 | JWT_EXPIRATION: 31536000 76 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/kotlin/com/personia/integrations/UserTest.kt: -------------------------------------------------------------------------------- 1 | package com.personia.integrations 2 | 3 | import com.personia.configIntegrationTestApp 4 | import com.personia.utils.randomString 5 | import io.ktor.client.request.* 6 | import io.ktor.client.statement.* 7 | import io.ktor.http.* 8 | import io.ktor.server.testing.* 9 | import kotlin.test.Test 10 | import kotlin.test.assertEquals 11 | import kotlin.test.assertTrue 12 | 13 | class UserTest { 14 | 15 | private val credentials = mapOf( 16 | "username" to randomString(10), 17 | "password" to randomString(10) 18 | ) 19 | @Test 20 | fun testSignUp() = testApplication { 21 | val client = configIntegrationTestApp() 22 | 23 | val responseSignUp = client.post("/signup") { 24 | contentType(ContentType.Application.Json) 25 | setBody(credentials) 26 | } 27 | assertEquals(HttpStatusCode.Created, responseSignUp.status) 28 | assertEquals("User singed up", responseSignUp.bodyAsText()) 29 | } 30 | 31 | @Test 32 | fun testDuplicateSignup() = testApplication{ 33 | val client = configIntegrationTestApp() 34 | client.post("/signup") { 35 | contentType(ContentType.Application.Json) 36 | setBody(credentials) 37 | } 38 | val responseDupSignUp = client.post("/signup") { 39 | contentType(ContentType.Application.Json) 40 | setBody(credentials) 41 | } 42 | assertEquals(HttpStatusCode.BadRequest, responseDupSignUp.status) 43 | assertTrue(responseDupSignUp.bodyAsText().contains("duplicate key value violates unique constraint.")) 44 | } 45 | 46 | @Test 47 | fun testLogin() = testApplication { 48 | val client = configIntegrationTestApp() 49 | client.post("/signup") { 50 | contentType(ContentType.Application.Json) 51 | setBody(credentials) 52 | } 53 | val responseLogin = client.post("/login") { 54 | contentType(ContentType.Application.Json) 55 | setBody(credentials) 56 | } 57 | assertEquals(HttpStatusCode.OK, responseLogin.status) 58 | assertTrue(responseLogin.bodyAsText().contains("token")) 59 | } 60 | 61 | @Test 62 | fun testLoginWrongPass()= testApplication { 63 | val client = configIntegrationTestApp() 64 | client.post("/signup") { 65 | contentType(ContentType.Application.Json) 66 | setBody(credentials) 67 | } 68 | val wrongPasswordCredential = credentials + mapOf("password" to randomString(15)) 69 | val responseWrongPassword = client.post("/login") { 70 | contentType(ContentType.Application.Json) 71 | setBody(wrongPasswordCredential) 72 | } 73 | assertEquals(HttpStatusCode.BadRequest, responseWrongPassword.status) 74 | assertTrue(responseWrongPassword.bodyAsText().contains("Wrong Password")) 75 | } 76 | 77 | @Test 78 | fun testLoginForNonExistingUser() = testApplication { 79 | val client = configIntegrationTestApp() 80 | val wrongUsernameCredential = credentials + mapOf("username" to randomString(12)) 81 | val responseUserNotFound = client.post("/login") { 82 | contentType(ContentType.Application.Json) 83 | setBody(wrongUsernameCredential) 84 | } 85 | assertEquals(HttpStatusCode.NotFound, responseUserNotFound.status) 86 | assertTrue(responseUserNotFound.bodyAsText().contains("user not found")) 87 | } 88 | } -------------------------------------------------------------------------------- /postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "e61731c6-57ac-6f68-7c5e-6de0f1ffe57d", 4 | "name": "Personio", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "personio-create-hierarchy", 10 | "request": { 11 | "auth": { 12 | "type": "bearer", 13 | "bearer": [ 14 | { 15 | "key": "token", 16 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwMTkwMzE1LCJ1c2VybmFtZSI6ImpvaG4ifQ.G-x2Tlbf5gX1hrgrAjfPBx9rKMyDuFuIekvcMB4QPiI", 17 | "type": "string" 18 | } 19 | ] 20 | }, 21 | "method": "POST", 22 | "header": [], 23 | "body": { 24 | "mode": "raw", 25 | "raw": "{\n \"Pete\": \"Nick\",\n \"Barbara\": \"Nick\",\n \"Nick\": \"Sophie\",\n \"Sophie\": \"Jonas\"\n}", 26 | "options": { 27 | "raw": { 28 | "language": "json" 29 | } 30 | } 31 | }, 32 | "url": { 33 | "raw": "localhost:8080/hierarchy", 34 | "host": [ 35 | "localhost" 36 | ], 37 | "port": "8080", 38 | "path": [ 39 | "hierarchy" 40 | ] 41 | } 42 | }, 43 | "response": [] 44 | }, 45 | { 46 | "name": "personio-login", 47 | "request": { 48 | "method": "POST", 49 | "header": [], 50 | "body": { 51 | "mode": "raw", 52 | "raw": "{\n \"username\":\"john\",\n \"password\":\"doe\"\n}", 53 | "options": { 54 | "raw": { 55 | "language": "json" 56 | } 57 | } 58 | }, 59 | "url": { 60 | "raw": "localhost:8080/login", 61 | "host": [ 62 | "localhost" 63 | ], 64 | "port": "8080", 65 | "path": [ 66 | "login" 67 | ] 68 | } 69 | }, 70 | "response": [] 71 | }, 72 | { 73 | "name": "personio-signup", 74 | "request": { 75 | "method": "POST", 76 | "header": [], 77 | "body": { 78 | "mode": "raw", 79 | "raw": "{\n \"username\":\"john\",\n \"password\":\"doe\"\n}", 80 | "options": { 81 | "raw": { 82 | "language": "json" 83 | } 84 | } 85 | }, 86 | "url": { 87 | "raw": "localhost:8080/signup", 88 | "host": [ 89 | "localhost" 90 | ], 91 | "port": "8080", 92 | "path": [ 93 | "signup" 94 | ] 95 | } 96 | }, 97 | "response": [] 98 | }, 99 | { 100 | "name": "personio-get-supervisors", 101 | "request": { 102 | "auth": { 103 | "type": "bearer", 104 | "bearer": [ 105 | { 106 | "key": "token", 107 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwMTkwMzE1LCJ1c2VybmFtZSI6ImpvaG4ifQ.G-x2Tlbf5gX1hrgrAjfPBx9rKMyDuFuIekvcMB4QPiI", 108 | "type": "string" 109 | } 110 | ] 111 | }, 112 | "method": "GET", 113 | "header": [], 114 | "url": { 115 | "raw": "localhost:8080/hierarchy/Nick/supervisors?level=1", 116 | "host": [ 117 | "localhost" 118 | ], 119 | "port": "8080", 120 | "path": [ 121 | "hierarchy", 122 | "Nick", 123 | "supervisors" 124 | ], 125 | "query": [ 126 | { 127 | "key": "level", 128 | "value": "1" 129 | } 130 | ] 131 | } 132 | }, 133 | "response": [] 134 | } 135 | ] 136 | } -------------------------------------------------------------------------------- /src/main/kotlin/com/personia/utils/Graph.kt: -------------------------------------------------------------------------------- 1 | package com.personia.utils 2 | 3 | import java.util.* 4 | 5 | 6 | /** 7 | * Create a directional Graph and travers over it with help of Depth First Search algorithm 8 | */ 9 | class Graph { 10 | var root: String? = null 11 | private val adjacent: MutableMap> = LinkedHashMap() 12 | 13 | /** 14 | * Creates a directional graph 15 | */ 16 | fun connect(source: String, dest: String) { 17 | val sourceNeighbours = adjacent[source] ?: mutableSetOf() 18 | sourceNeighbours.add(dest) 19 | adjacent[source] = sourceNeighbours 20 | } 21 | 22 | /** 23 | * First checks if the Graph is a Tree 24 | * Second checks if it's unified Tree 25 | * At the end sets the root to the Tree and return the Tree 26 | */ 27 | @Throws(AssertionError::class) 28 | fun findRoot(): Graph { 29 | val values = adjacent.values.flatten().toSet() 30 | val roots = adjacent.keys.filter { !values.contains(it) } 31 | if (roots.isEmpty()) { 32 | throw AssertionError("There is no root. there might be loops in the hierarchy.") 33 | } 34 | if (roots.size > 1) { 35 | throw AssertionError("Too many roots [$roots]") 36 | } 37 | this.root = roots.first() 38 | return this 39 | } 40 | 41 | /** 42 | * Converts the adjacent nodes of a node form Set to Map 43 | */ 44 | private fun convertToHashMap(): MutableMap> { 45 | val tempMap = mutableMapOf>() 46 | for (k in adjacent.keys) { 47 | val t = mutableMapOf() 48 | adjacent[k]?.forEach { t[it] = emptyMap() } 49 | tempMap[k] = t 50 | } 51 | return tempMap 52 | } 53 | 54 | /** 55 | * Transforms the Graph adjacent from Map to a Nested Map 56 | */ 57 | fun transformToNestedMap(dfsVisited: Set): Map> { 58 | val tempMap = convertToHashMap() 59 | val visited = ArrayDeque(dfsVisited) 60 | for (i in 1..visited.size) { 61 | val node = visited.pop() 62 | val supervisor = tempMap.filterValues { it.containsKey(node) }.keys.toList() 63 | if (supervisor.isNotEmpty()) { 64 | val s1 = supervisor.first() 65 | val supValues = tempMap[s1] ?: mutableMapOf() 66 | supValues[node] = tempMap[node] ?: mutableMapOf>() 67 | tempMap[s1] = supValues 68 | } 69 | } 70 | return tempMap 71 | } 72 | 73 | /** 74 | * Traverse the Graph from a starting node 75 | * @exception AssertionError If Graph contains a cycle will throw an assertion error 76 | */ 77 | @Throws(AssertionError::class) 78 | fun dfs(start: String): MutableSet { 79 | val visited = mutableSetOf() 80 | dfsRecursive(start, visited) 81 | return visited 82 | } 83 | 84 | /** 85 | * Traverse the Graph from a starting node to a specified depth 86 | */ 87 | fun dfs(start: String, depth: Int): Set { 88 | val visited = mutableSetOf() 89 | dfsRecursive(start, visited, depth) 90 | return visited 91 | } 92 | 93 | /** 94 | * Recursively traverse the Graph from a starting point 95 | * @exception AssertionError If Graph contains a cycle will throw an assertion error 96 | */ 97 | @Throws(AssertionError::class) 98 | private fun dfsRecursive(current: String, visited: MutableSet) { 99 | visited.add(current) 100 | for (sub in adjacent[current] ?: setOf()) { 101 | if (visited.add(sub)) { 102 | dfsRecursive(sub, visited) 103 | } else { 104 | val culprit = adjacent[sub]?.first { adjacent[it]?.contains(sub) ?: false } 105 | throw AssertionError("there is a loop in the hierarchy.$sub is already supervisor of $culprit") 106 | } 107 | } 108 | } 109 | 110 | /** 111 | * Recursively traverse the Graph from a starting point to a specified depth 112 | */ 113 | private fun dfsRecursive(current: String, visited: MutableSet, depth: Int) { 114 | visited.add(current) 115 | for (sub in adjacent[current] ?: setOf()) { 116 | if (visited.add(sub) && visited.size < depth) { 117 | dfsRecursive(sub, visited, depth) 118 | } 119 | } 120 | } 121 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin Ktor and postgres backend 2 | 3 | Here lays a Kotlin web project with Ktor framework, Postgres database, and JWT Authentication. 4 | 5 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=fractalliter_ktor-postgres-backend&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=fractalliter_ktor-postgres-backend) 6 | [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=fractalliter_ktor-postgres-backend&metric=bugs)](https://sonarcloud.io/summary/new_code?id=fractalliter_ktor-postgres-backend) 7 | [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=fractalliter_ktor-postgres-backend&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=fractalliter_ktor-postgres-backend) 8 | [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=fractalliter_ktor-postgres-backend&metric=duplicated_lines_density)](https://sonarcloud.io/summary/new_code?id=fractalliter_ktor-postgres-backend) 9 | [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=fractalliter_ktor-postgres-backend&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=fractalliter_ktor-postgres-backend) 10 | 11 | The project comprises the following ingredients: 12 | 13 | - [Ktor](https://ktor.io/) server 14 | includes [JSON serializers](https://ktor.io/docs/serialization.html), [Authentication](https://ktor.io/docs/authentication.html), 15 | and [Testing](https://ktor.io/docs/testing.html) 16 | - [Netty](https://netty.io/) web server 17 | - [Postgres](https://www.postgresql.org/) as database 18 | - [Exposed](https://github.com/JetBrains/Exposed) as ORM 19 | - [Hikari Connection Pool](https://github.com/brettwooldridge/HikariCP) 20 | - [Logback](https://logback.qos.ch/) for logging purposes 21 | - [JBCrypt](https://www.mindrot.org/projects/jBCrypt/) for hashing passwords (No salting yet) 22 | 23 | There is a simple implementation of DFS algorithm, but if you aim for a solid solution, 24 | better go for [GUAVA Graph](https://github.com/google/guava/wiki/GraphsExplained) from Google. 25 | 26 | Project is SQL DB agnostic. You are able to dynamically change Postgres to any other databases that Exposed JDBC 27 | supports by changing a couple of variables: 28 | 29 | - the database driver version in `gradle.properties` 30 | - the database driver dependency in `build.gradle.kts` 31 | - the **WEB_DB_URL** variable in `.env` file 32 | 33 | ## Flow 34 | 35 | 1. deploy the docker compose with `docker compose up -d` command 36 | 2. sign up to `/signup` route providing a username and password(not hardened enough) 37 | 3. log in to with your username and password to get access token `/login` 38 | 4. send `POST` request with payload and token to `/hirearchy` to create the hierarchy of the organization 39 | 5. send get request with token to `/hierarchy/{name}/supervisors` to fetch the supervisors of the current user 40 | 41 | ## How to use 42 | 43 | > You need **root access** for docker 44 | 45 | Go to the root directory of the project where `docker-compose.yml` is and change the environment variables in 46 | `.env-example` with yours and rename the file to `.env` then deploy the application with the following command: 47 | 48 | ```bash 49 | docker-compose up -d 50 | ``` 51 | 52 | for shutting down the deployment run following command where the `docker-compose.yml` file resides: 53 | 54 | ```bash 55 | docker-compose down -v 56 | ``` 57 | 58 | ### What it does? 59 | 60 | We have REST API to post the JSON below. This JSON represents a Person -> Person relationship that looks like this: 61 | 62 | ```json 63 | { 64 | "Pete": "Nick", 65 | "Barbara": "Nick", 66 | "Nick": "Sophie", 67 | "Sophie": "Jonas" 68 | } 69 | ``` 70 | 71 | In this case, Nick is a supervisor of Pete and Barbara, Sophie supervises Nick. The supervisor list is 72 | not always in order. 73 | 74 | ```bash 75 | curl --request POST -sLv \ 76 | --url 'http://localhost:8080/hierarchy' \ 77 | --header "Content-Type: application/json" \ 78 | --header "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwNDkwNzUwLCJ1c2VybmFtZSI6ImphbmUifQ.Xfn4JEOHo-Px7vy0TVyo3malCFlj3eFvzAJejqlefPM" \ 79 | --data '{"Nick":"Barbara","Barbara":"Nick","Elias":"Levi"}' 80 | 81 | ``` 82 | 83 | The response to querying the endpoint where the root is at the top of the JSON nested dictionary. 84 | For instance, previous input would result in: 85 | 86 | ```bash 87 | curl --request GET -sLv \ 88 | --url 'http://localhost:8080/hierarchy' \ 89 | --header "Content-Type: application/json" \ 90 | --header "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwNDkwNzUwLCJ1c2VybmFtZSI6ImphbmUifQ.Xfn4JEOHo-Px7vy0TVyo3malCFlj3eFvzAJejqlefPM" 91 | ``` 92 | 93 | the response will be: 94 | 95 | ```json 96 | { 97 | "Jonas": { 98 | "Sophie": { 99 | "Nick": { 100 | "Pete": {}, 101 | "Barbara": {} 102 | } 103 | } 104 | } 105 | } 106 | ``` 107 | 108 | Query for a specific Person it's the hierarchy: 109 | 110 | ```bash 111 | curl --request GET -sLv \ 112 | --url 'http://localhost:8080/hierarchy/Nick/supervisors'\ 113 | --header "Content-Type: application/json" \ 114 | --header "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwNDkwNzUwLCJ1c2VybmFtZSI6ImphbmUifQ.Xfn4JEOHo-Px7vy0TVyo3malCFlj3eFvzAJejqlefPM" 115 | ``` 116 | 117 | the response of the query will be: 118 | 119 | ```json 120 | { 121 | "Nick": { 122 | "Sophie": { 123 | "Jonas": {} 124 | } 125 | } 126 | } 127 | ``` 128 | 129 | Sophie is the supervisor of the Nick, and Jonas is a supervisor of the supervisor of the Nick 130 | 131 | ## It's secured by JWT authentication 132 | 133 | Sign up to the system 134 | 135 | ```bash 136 | curl --request POST -sL \ 137 | --url 'http://localhost:8080/signup'\ 138 | --header "Content-Type: application/json" \ 139 | --data '{"username":"jane","password":"doe"}' 140 | ``` 141 | 142 | login to the system 143 | 144 | ```bash 145 | curl --request POST -sL \ 146 | --url 'http://localhost:8080/login'\ 147 | --header "Content-Type: application/json" \ 148 | --data '{"username":"jane","password":"doe"}' 149 | ``` 150 | 151 | The response will be the access token 152 | 153 | ```json 154 | { 155 | "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJodHRwOi8vMC4wLjAuMDo4MDgwL2hpZXJhcmNoeSIsImlzcyI6Imh0dHA6Ly8wLjAuMC4wOjgwODAvIiwiZXhwIjoxNjUwMTU3NjIxLCJ1c2VybmFtZSI6ImpvaG4ifQ.LSJUte7oy9Kv7qkozI3APBzPxHVZ56GID-n0lRIKvdY" 156 | } 157 | ``` 158 | 159 | ## How to run tests locally 160 | 161 | To run the tests locally, you should run docker compose with `docker-compose-test.yml` file. 162 | It will run the tests against the test database. 163 | 164 | ```bash 165 | docker-compose --file docker-compose-test.yml up 166 | ``` 167 | 168 | After finishing the tests, you can clean test data nd shut the containers down with the following command: 169 | 170 | ```bash 171 | docker-compose --file docker-compose-test.yml down -v 172 | ``` 173 | 174 | ## Continues Integration 175 | 176 | CI workflow prepares the database, runs the Gradle build with tests, 177 | and generates a good quality report to [Codacy](https://www.codacy.com/). 178 | 179 | ## Todo 180 | 181 | - [ ] Increase test coverage 182 | - [ ] Add caching 183 | - [ ] E2E testing 184 | - [ ] OpenAPI specifications 185 | - [ ] Change to GUAVA 186 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | --------------------------------------------------------------------------------