Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added endpoints for manage organizations #426

Merged
merged 6 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import com.xebia.functional.xef.server.db.psql.Migrate
import com.xebia.functional.xef.server.db.psql.XefVectorStoreConfig
import com.xebia.functional.xef.server.db.psql.XefVectorStoreConfig.Companion.getVectorStoreService
import com.xebia.functional.xef.server.http.routes.genAIRoutes
import com.xebia.functional.xef.server.http.routes.organizationRoutes
import com.xebia.functional.xef.server.http.routes.userRoutes
import com.xebia.functional.xef.server.services.OrganizationRepositoryService
import com.xebia.functional.xef.server.services.RepositoryService
import com.xebia.functional.xef.server.services.UserRepositoryService
import io.ktor.client.*
Expand Down Expand Up @@ -78,7 +80,8 @@ object Server {
}
routing {
genAIRoutes(ktorClient, vectorStoreService)
userRoutes(UserRepositoryService())
userRoutes(UserRepositoryService(logger))
organizationRoutes(OrganizationRepositoryService(logger))
}
}
awaitCancellation()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.jetbrains.exposed.sql.ReferenceOption
import org.jetbrains.exposed.sql.kotlin.datetime.CurrentTimestamp
import org.jetbrains.exposed.sql.kotlin.datetime.timestamp

object OrganizationTable : IntIdTable() {
object OrganizationsTable : IntIdTable("organizations") {
val name = varchar("name", 20)
val createdAt = timestamp("created_at").defaultExpression(CurrentTimestamp())
val updatedAt = timestamp("updated_at").defaultExpression(CurrentTimestamp())
Expand All @@ -20,12 +20,12 @@ object OrganizationTable : IntIdTable() {
}

class Organization(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Organization>(OrganizationTable)
companion object : IntEntityClass<Organization>(OrganizationsTable)

var name by OrganizationTable.name
var createdAt by OrganizationTable.createdAt
var updatedAt by OrganizationTable.updatedAt
var ownerId by OrganizationTable.ownerId
var name by OrganizationsTable.name
var createdAt by OrganizationsTable.createdAt
var updatedAt by OrganizationsTable.updatedAt
var ownerId by OrganizationsTable.ownerId

var users by User via UsersOrgsTable
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import org.jetbrains.exposed.sql.ReferenceOption
import org.jetbrains.exposed.sql.kotlin.datetime.CurrentTimestamp
import org.jetbrains.exposed.sql.kotlin.datetime.timestamp

object ProjectsTable: IntIdTable() {
object ProjectsTable: IntIdTable("projects") {
val name = varchar("name", 20)
val createdAt = timestamp("created_at").defaultExpression(CurrentTimestamp())
val updatedAt = timestamp("updated_at").defaultExpression(CurrentTimestamp())
val orgId = reference(
name = "org_id",
refColumn = OrganizationTable.id,
refColumn = OrganizationsTable.id,
onDelete = ReferenceOption.CASCADE
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ package com.xebia.functional.xef.server.db.tables
import org.jetbrains.exposed.sql.ReferenceOption
import org.jetbrains.exposed.sql.Table

object UsersOrgsTable : Table() {
object UsersOrgsTable : Table("users_org") {
val userId = reference(
name = "user_id",
foreign = UsersTable,
onDelete = ReferenceOption.CASCADE
)
val orgId = reference(
name = "org_id",
foreign = OrganizationTable,
foreign = OrganizationsTable,
onDelete = ReferenceOption.CASCADE
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.jetbrains.exposed.sql.kotlin.datetime.CurrentTimestamp
import org.jetbrains.exposed.sql.kotlin.datetime.timestamp


object UsersTable : IntIdTable() {
object UsersTable : IntIdTable("users") {
val name = varchar("name", 20)
val email = varchar("email", 50)
val passwordHash = binary("password_hash")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ data class XefTokens(
@SerialName("providers_config") val providersConfig: ProvidersConfig
)

object XefTokensTable : Table() {
object XefTokensTable : Table("xef_tokens") {
val userId = reference(
name = "user_id",
foreign = UsersTable,
onDelete = ReferenceOption.CASCADE)
onDelete = ReferenceOption.CASCADE
)
val projectId = reference(
name = "project_id",
foreign = ProjectsTable,
Expand All @@ -42,7 +43,7 @@ object XefTokensTable : Table() {
override val primaryKey = PrimaryKey(userId, projectId, name)
}

fun ResultRow.toXefTokens() : XefTokens {
fun ResultRow.toXefTokens(): XefTokens {
return XefTokens(
userId = this[XefTokensTable.userId].value,
projectId = this[XefTokensTable.projectId].value,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package com.xebia.functional.xef.server.http.routes

import com.xebia.functional.xef.server.models.OrganizationRequest
import com.xebia.functional.xef.server.models.OrganizationUpdateRequest
import com.xebia.functional.xef.server.services.OrganizationRepositoryService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.json.Json

fun Routing.organizationRoutes(
orgRepositoryService: OrganizationRepositoryService
) {
authenticate("auth-bearer") {
get("/v1/settings/org") {
try {
val token = call.getToken()
val response = orgRepositoryService.getOrganizations(token)
call.respond(response)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
get("/v1/settings/org/{id}") {
try {
val token = call.getToken()
val id = call.parameters["id"]?.toInt() ?: throw Exception("Invalid id")
val response = orgRepositoryService.getOrganization(token, id)
call.respond(response)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
get("/v1/settings/org/{id}/users"){
try {
val token = call.getToken()
val id = call.parameters["id"]?.toInt() ?: throw Exception("Invalid id")
val response = orgRepositoryService.getUsersInOrganization(token, id)
call.respond(response)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
post("/v1/settings/org") {
try {
val request = Json.decodeFromString<OrganizationRequest>(call.receive<String>())
val token = call.getToken()
val response = orgRepositoryService.createOrganization(request, token)
call.respond(
status = HttpStatusCode.Created,
response
)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
put("/v1/settings/org/{id}") {
try {
val request = Json.decodeFromString<OrganizationUpdateRequest>(call.receive<String>())
val token = call.getToken()
val id = call.parameters["id"]?.toInt() ?: throw Exception("Invalid id")
val response = orgRepositoryService.updateOrganization(token, request, id)
call.respond(
status = HttpStatusCode.NoContent,
response
)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
delete("/v1/settings/org/{id}") {
try {
val token = call.getToken()
val id = call.parameters["id"]?.toInt() ?: throw Exception("Invalid id")
val response = orgRepositoryService.deleteOrganization(token, id)
call.respond(
status = HttpStatusCode.NoContent,
response
)
} catch (e: Exception) {
call.respondText(e.message ?: "Unexpected error", status = HttpStatusCode.BadRequest)
}
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ private fun ApplicationCall.getProvider(): Provider =
request.headers["xef-provider"]?.toProvider()
?: Provider.OPENAI

private fun ApplicationCall.getToken(): String =
fun ApplicationCall.getToken(): String =
principal<UserIdPrincipal>()?.name ?: throw IllegalArgumentException("No token found")


Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,14 @@ data class LoginRequest(
val email: String,
val password: String
)

@Serializable
data class OrganizationRequest(
val name: String
)

@Serializable
data class OrganizationUpdateRequest(
val name: String,
val owner: Int? = null
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.xebia.functional.xef.server.models

import kotlinx.serialization.Serializable

@Serializable
data class LoginResponse(val authToken: String)

@Serializable
data class OrganizationSimpleResponse(val name: String)

@Serializable
data class OrganizationWithIdResponse(val id: Int, val name: String, val users: Long)
@Serializable
data class OrganizationFullResponse(val id: Int, val name: String, val owner: Int, val users: Long)

@Serializable
data class UserResponse(val id: Int, val name: String)
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package com.xebia.functional.xef.server.services

import com.xebia.functional.xef.server.db.tables.Organization
import com.xebia.functional.xef.server.db.tables.User
import com.xebia.functional.xef.server.db.tables.UsersTable
import com.xebia.functional.xef.server.models.*
import kotlinx.datetime.Clock
import org.jetbrains.exposed.sql.SizedCollection
import org.jetbrains.exposed.sql.transactions.transaction
import org.slf4j.Logger

class OrganizationRepositoryService(
private val logger: Logger
) {
fun createOrganization(
data: OrganizationRequest,
token: String
): OrganizationSimpleResponse {
logger.info("Creating organization with name: ${data.name}")
return transaction {
// Getting the user from the token
val user = getUser(token)

// Creating the organization
val organization = Organization.new {
name = data.name
ownerId = user.id
}
// Adding the organization to the user
user.organizations = SizedCollection(user.organizations + organization)
organization.users = SizedCollection(organization.users + user)
OrganizationSimpleResponse(organization.name)
}
}

fun getOrganizations(
token: String
): List<OrganizationWithIdResponse> {
logger.info("Getting organizations")
return transaction {
// Getting the user from the token
val user = getUser(token)

// Getting the organizations from the user
user.organizations.map { OrganizationWithIdResponse(it.id.value, it.name, it.users.count()) }
}
}

fun getOrganization(
token: String,
id: Int
): List<OrganizationFullResponse> {
logger.info("Getting organizations")
return transaction {
// Getting the user from the token
val user = getUser(token)

// Getting the organizations from the user
user.organizations.filter {
it.id.value == id
}.map { OrganizationFullResponse(it.id.value, it.name, it.ownerId.value, it.users.count()) }
}
}

fun getUsersInOrganization(
token: String,
id: Int
): List<UserResponse> {
logger.info("Getting users in organization")
return transaction {
// Getting the user from the token
val user = getUser(token)

// Getting the organizations from the user
user.organizations.filter {
it.id.value == id
}.flatMap { it.users }.map { UserResponse(it.id.value, it.name) }
}
}

fun updateOrganization(
token: String,
data: OrganizationUpdateRequest,
id: Int
): OrganizationFullResponse {
logger.info("Updating organization with name: ${data.name}")
return transaction {
// Getting the user from the token
val user = getUser(token)

val organization = Organization.findById(id)
?: throw Exception("Organization not found")

if (organization.ownerId != user.id) {
throw Exception("User is not the owner of the organization")
}

// Updating the organization
organization.name = data.name
if (data.owner != null) {
val newOwner = User.findById(data.owner)
?: throw Exception("User not found")
organization.ownerId = newOwner.id
}
organization.updatedAt = Clock.System.now()
OrganizationFullResponse(
organization.id.value,
organization.name,
organization.ownerId.value,
organization.users.count()
)
}
}

fun deleteOrganization(
token: String,
id: Int
) {
logger.info("Deleting organization with id: $id")
transaction {
val user = getUser(token)
val organization = Organization.findById(id)
?: throw Exception("Organization not found")
if (organization.ownerId == user.id) {
organization.delete()
}
}
}

private fun getUser(token: String) =
User.find { UsersTable.authToken eq token }.firstOrNull() ?: throw Exception("User not found")
}
Loading