Add abstract data source
continuous-integration/drone/push Build is passing Details

pull/8/head
Arthur VALIN 10 months ago
parent 2b3a79bd0f
commit addc40f4bf

4
.gitignore vendored

@ -35,4 +35,6 @@ out/
### VS Code ###
.vscode/
!**/src/target/**
!**/src/target/**
**/src/target/**
/src/target

@ -1,8 +1,10 @@
package allin
import allin.entities.*
import allin.data.AllInDataSource
import allin.data.mock.MockDataSource
import allin.data.postgres.PostgresDataSource
import allin.routing.*
import allin.utils.*
import allin.utils.TokenManager
import com.typesafe.config.ConfigFactory
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
@ -12,14 +14,16 @@ import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import org.ktorm.database.Database
val db_database=System.getenv().get("POSTGRES_DB")
val db_user=System.getenv().get("POSTGRES_USER")
val db_password=System.getenv().get("POSTGRES_PASSWORD")
val db_host=System.getenv().get("POSTGRES_HOST")
val data_source = System.getenv()["DATA_SOURCE"]
val database = Database.connect("jdbc:postgresql://$db_host/$db_database", user = db_user, password = db_password)
private val allInDataSource: AllInDataSource = when (data_source) {
"mock" -> MockDataSource()
"postgres" -> PostgresDataSource()
else -> MockDataSource()
}
val Application.dataSource: AllInDataSource
get() = allInDataSource
fun main() {
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
@ -49,8 +53,4 @@ private fun Application.extracted() {
BetRouter()
ParticipationRouter()
BetDetailRouter()
UsersEntity.createUserTable()
BetsEntity.createBetsTable()
ResponsesEntity.createResponseTable()
ParticipationsEntity.createParticipationTable()
}
}

@ -0,0 +1,7 @@
package allin.data
abstract class AllInDataSource {
abstract val userDataSource: UserDataSource
abstract val betDataSource: BetDataSource
abstract val participationDataSource: ParticipationDataSource
}

@ -0,0 +1,13 @@
package allin.data
import allin.model.Bet
import allin.model.UpdatedBetData
interface BetDataSource {
fun getAllBets(): List<Bet>
fun getBetById(id: String): Bet?
fun getBetsNotFinished(): List<Bet>
fun addBet(bet: Bet)
fun removeBet(id: String): Boolean
fun updateBet(data: UpdatedBetData): Boolean
}

@ -0,0 +1,11 @@
package allin.data
import allin.model.Participation
interface ParticipationDataSource {
fun addParticipation(participation: Participation)
fun getParticipationFromBetId(betid: String): List<Participation>
fun getParticipationFromUserId(username: String, betid: String): List<Participation>
fun deleteParticipation(id: String): Boolean
}

@ -0,0 +1,12 @@
package allin.data
import allin.dto.UserDTO
import allin.model.User
interface UserDataSource {
fun getUserByUsername(username: String): Pair<UserDTO?, String?>
fun addUser(user: User)
fun deleteUser(username: String): Boolean
fun modifyUserCoins(username: String, amount: Int)
fun userExists(username: String, email: String): Boolean
}

@ -0,0 +1,31 @@
package allin.data.mock
import allin.data.BetDataSource
import allin.model.Bet
import allin.model.UpdatedBetData
import java.time.ZonedDateTime
class MockBetDataSource : BetDataSource {
override fun getAllBets(): List<Bet> = bets
override fun getBetById(id: String): Bet? =
bets.find { it.id == id }
override fun removeBet(id: String): Boolean =
bets.removeIf { it.id == id }
override fun updateBet(data: UpdatedBetData): Boolean {
return bets.find { it.id == data.id }?.let {
it.isPrivate = data.isPrivate
} != null
}
override fun getBetsNotFinished(): List<Bet> =
bets.filter { it.endBet >= ZonedDateTime.now() }
override fun addBet(bet: Bet) {
bets += bet
}
private val bets by lazy { mutableListOf<Bet>() }
}

@ -0,0 +1,12 @@
package allin.data.mock
import allin.data.AllInDataSource
import allin.data.BetDataSource
import allin.data.ParticipationDataSource
import allin.data.UserDataSource
class MockDataSource : AllInDataSource() {
override val userDataSource: UserDataSource = MockUserDataSource()
override val betDataSource: BetDataSource = MockBetDataSource()
override val participationDataSource: ParticipationDataSource = MockParticipationDataSource()
}

@ -0,0 +1,22 @@
package allin.data.mock
import allin.data.ParticipationDataSource
import allin.model.Participation
class MockParticipationDataSource : ParticipationDataSource {
override fun addParticipation(participation: Participation) {
participations += participations
}
override fun getParticipationFromBetId(betid: String): List<Participation> =
participations.filter { it.betId == betid }
override fun getParticipationFromUserId(username: String, betid: String): List<Participation> =
participations.filter { it.betId == betid && it.username == username }
override fun deleteParticipation(id: String): Boolean =
participations.removeIf { it.id == id }
private val participations by lazy { mutableListOf<Participation>() }
}

@ -0,0 +1,41 @@
package allin.data.mock
import allin.data.UserDataSource
import allin.dto.UserDTO
import allin.model.User
class MockUserDataSource : UserDataSource {
override fun getUserByUsername(username: String): Pair<UserDTO?, String?> =
users.find { it.username == username }?.let {
Pair(
UserDTO(
id = it.id,
username = it.username,
email = it.email,
nbCoins = it.nbCoins,
token = it.token
),
it.password
)
} ?: Pair(null, null)
override fun addUser(user: User) {
users += user
}
override fun deleteUser(username: String): Boolean =
users.removeIf { it.username == username }
override fun modifyUserCoins(username: String, amount: Int) {
users.find { it.username == username }?.let {
it.nbCoins += amount
}
}
override fun userExists(username: String, email: String): Boolean =
users.any { it.username == username && it.email == email }
private val users by lazy {
mutableListOf<User>()
}
}

@ -0,0 +1,75 @@
package allin.data.postgres
import allin.data.BetDataSource
import allin.entities.BetsEntity
import allin.model.Bet
import allin.model.UpdatedBetData
import allin.utils.Execute
import org.ktorm.database.Database
import org.ktorm.dsl.*
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.*
class PostgresBetDataSource(private val database: Database) : BetDataSource {
private fun QueryRowSet.toBet() =
Bet(
id = this[BetsEntity.id].toString(),
theme = this[BetsEntity.theme].toString(),
sentenceBet = this[BetsEntity.sentenceBet].toString(),
endRegistration = this[BetsEntity.endRegistration]!!.atZone(ZoneId.of("Europe/Paris")),
endBet = this[BetsEntity.endBet]!!.atZone(ZoneId.of("Europe/Paris")),
isPrivate = this[BetsEntity.isPrivate] ?: false,
response = mutableListOf(), // ResponsesEntity.getResponse(UUID.fromString(this[BetsEntity.id].toString())),
createdBy = this[BetsEntity.createdBy].toString()
)
private fun Query.mapToBet() = this.map { it.toBet() }
override fun getAllBets(): List<Bet> =
database.from(BetsEntity).select().mapToBet()
override fun getBetById(id: String): Bet? =
database.from(BetsEntity).select().where {
BetsEntity.id eq UUID.fromString(id)
}.mapToBet().firstOrNull()
override fun getBetsNotFinished(): List<Bet> {
val currentTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"))
return database.from(BetsEntity)
.select()
.where { BetsEntity.endBet greaterEq currentTime.toInstant() }
.mapToBet()
}
override fun addBet(bet: Bet) {
database.insert(BetsEntity) {
set(it.id, UUID.fromString(bet.id))
set(it.endBet, bet.endBet.toInstant())
set(it.endRegistration, bet.endRegistration.toInstant())
set(it.sentenceBet, bet.sentenceBet)
set(it.theme, bet.theme)
set(it.isPrivate, bet.isPrivate)
set(it.createdBy, bet.createdBy)
}
// ResponsesEntity.addResponse(bet.response, UUID.fromString(bet.id))
}
override fun removeBet(id: String): Boolean {
return database.delete(BetsEntity) { it.id eq UUID.fromString(id) } > 0
}
override fun updateBet(data: UpdatedBetData): Boolean {
return database.update(BetsEntity) {
set(BetsEntity.isPrivate, data.isPrivate)
where { BetsEntity.id eq UUID.fromString(data.id) }
} > 0
}
fun createBetsTable() {
val request =
"CREATE TABLE IF not exists bet ( id uuid PRIMARY KEY, theme VARCHAR(255), endregistration timestamp,endbet timestamp,sentencebet varchar(500),isprivate boolean, createdby varchar(250))"
database.Execute(request)
}
}

@ -0,0 +1,34 @@
package allin.data.postgres
import allin.data.AllInDataSource
import allin.data.BetDataSource
import allin.data.ParticipationDataSource
import allin.data.UserDataSource
import org.ktorm.database.Database
class PostgresDataSource : AllInDataSource() {
private val database: Database
init {
val dbDatabase = System.getenv()["POSTGRES_DB"]
val dbUser = System.getenv()["POSTGRES_USER"]
val dbPassword = System.getenv()["POSTGRES_PASSWORD"]
val dbHost = System.getenv()["POSTGRES_HOST"]
database = Database.connect(
url = "jdbc:postgresql://$dbHost/$dbDatabase",
user = dbUser,
password = dbPassword
)
}
override val userDataSource: UserDataSource = PostgresUserDataSource(database)
.also { it.createUserTable() }
override val betDataSource: BetDataSource = PostgresBetDataSource(database)
.also { it.createBetsTable() }
override val participationDataSource: ParticipationDataSource = PostgresParticipationDataSource(database)
.also { it.createParticipationTable() }
}

@ -0,0 +1,64 @@
package allin.data.postgres
import allin.data.ParticipationDataSource
import allin.entities.ParticipationsEntity
import allin.model.Participation
import allin.utils.Execute
import org.ktorm.database.Database
import org.ktorm.dsl.*
import java.util.*
class PostgresParticipationDataSource(private val database: Database) : ParticipationDataSource {
private fun QueryRowSet.toParticipation() =
Participation(
id = this[ParticipationsEntity.id].toString(),
betId = this[ParticipationsEntity.betId].toString(),
username = this[ParticipationsEntity.username].toString(),
answer = this[ParticipationsEntity.answer].toString(),
stake = this[ParticipationsEntity.stake] ?: 0,
)
private fun Query.mapToParticipation() = this.map { it.toParticipation() }
fun createParticipationTable() {
val request =
"CREATE TABLE IF NOT EXISTS participation (id uuid PRIMARY KEY,bet uuid,username varchar(250),answer varchar(250),stake int);"
database.Execute(request)
}
override fun addParticipation(participation: Participation) {
database.insert(ParticipationsEntity) {
set(it.id, UUID.fromString(participation.id))
set(it.betId, UUID.fromString(participation.betId))
set(it.username, participation.username)
set(it.answer, participation.answer)
set(it.stake, participation.stake)
}
}
override fun getParticipationFromBetId(betid: String): List<Participation> {
return database.from(ParticipationsEntity)
.select()
.where { ParticipationsEntity.betId eq UUID.fromString(betid) }
.mapToParticipation()
}
override fun getParticipationFromUserId(username: String, betid: String): List<Participation> {
return database.from(ParticipationsEntity)
.select()
.where { (ParticipationsEntity.betId eq UUID.fromString(betid)) and (ParticipationsEntity.username eq username) }
.mapToParticipation()
}
fun getParticipationEntity(): List<Participation> {
return database.from(ParticipationsEntity).select().mapToParticipation()
}
override fun deleteParticipation(id: String): Boolean {
return database.delete(ParticipationsEntity) {
it.id eq UUID.fromString(id)
} > 0
}
}

@ -0,0 +1,64 @@
package allin.data.postgres
import allin.data.UserDataSource
import allin.dto.UserDTO
import allin.entities.UsersEntity
import allin.model.User
import allin.utils.Execute
import org.ktorm.database.Database
import org.ktorm.dsl.*
import java.util.*
class PostgresUserDataSource(private val database: Database) : UserDataSource {
override fun getUserByUsername(username: String): Pair<UserDTO?, String?> =
database.from(UsersEntity)
.select()
.where { UsersEntity.username eq username }
.map { row ->
Pair(
UserDTO(
row[UsersEntity.id].toString(),
row[UsersEntity.username].toString(),
row[UsersEntity.email].toString(),
row[UsersEntity.nbCoins] ?: 0,
null
),
row[UsersEntity.password].toString()
)
}
.firstOrNull() ?: Pair(null, null)
override fun addUser(user: User) {
database.insert(UsersEntity) {
set(it.id, UUID.fromString(user.id))
set(it.nbCoins, user.nbCoins)
set(it.username, user.username)
set(it.password, user.password)
set(it.email, user.email)
}
}
override fun deleteUser(username: String): Boolean {
val deletedCount = database.delete(UsersEntity) {
it.username eq username
}
return deletedCount > 0
}
override fun userExists(username: String, email: String): Boolean {
return database.from(UsersEntity).select(UsersEntity.username, UsersEntity.email).where {
(UsersEntity.username eq username) and (UsersEntity.email eq email)
}.totalRecords > 0
}
override fun modifyUserCoins(username: String, amount: Int) {
val request = "UPDATE utilisateur SET coins = coins - $amount WHERE username = '$username';"
database.Execute(request)
}
fun createUserTable() {
val request =
"CREATE TABLE IF not exists utilisateur ( id uuid PRIMARY KEY, username VARCHAR(255), password VARCHAR(255),coins double precision,email VARCHAR(255))"
database.Execute(request)
}
}

@ -1,15 +1,8 @@
package allin.entities
import allin.database
import allin.entities.ResponsesEntity.getResponse
import allin.model.Bet
import allin.utils.Execute
import org.ktorm.dsl.*
import org.ktorm.entity.Entity
import org.ktorm.schema.*
import java.time.ZoneId
import java.time.ZonedDateTime
import java.util.UUID.fromString
interface BetEntity : Entity<BetEntity> {
@ -29,56 +22,4 @@ object BetsEntity : Table<BetEntity>("bet") {
val endBet = timestamp("endbet")
val isPrivate = boolean("isprivate")
val createdBy = varchar("createdby")
fun getBets(): MutableList<Bet> {
return database.from(BetsEntity).select().map {
row -> Bet(
row[id].toString(),
row[theme].toString(),
row[sentenceBet].toString(),
row[endRegistration]!!.atZone(ZoneId.of("Europe/Paris")),
row[endBet]!!.atZone(ZoneId.of("Europe/Paris")),
row[isPrivate]?: false,
getResponse(fromString(row[id].toString())),
row[createdBy].toString()
)
}.toMutableList()
}
fun getBetsNotFinished(): MutableList<Bet> {
val currentTime = ZonedDateTime.now(ZoneId.of("Europe/Paris"))
return database.from(BetsEntity)
.select()
.where { endBet greaterEq currentTime.toInstant() }
.map { row ->
Bet(
row[id].toString(),
row[theme].toString(),
row[sentenceBet].toString(),
row[endRegistration]!!.atZone(ZoneId.of("Europe/Paris")),
row[endBet]!!.atZone(ZoneId.of("Europe/Paris")),
row[isPrivate] ?: false,
getResponse(fromString(row[id].toString())),
row[createdBy].toString()
)
}.toMutableList()
}
fun createBetsTable(){
val request="CREATE TABLE IF not exists bet ( id uuid PRIMARY KEY, theme VARCHAR(255), endregistration timestamp,endbet timestamp,sentencebet varchar(500),isprivate boolean, createdby varchar(250))"
database.Execute(request)
}
fun addBetEntity(bet : Bet) {
database.insert(BetsEntity) {
set(it.id, fromString(bet.id))
set(it.endBet,bet.endBet.toInstant())
set(it.endRegistration,bet.endRegistration.toInstant())
set(it.sentenceBet,bet.sentenceBet)
set(it.theme, bet.theme)
set(it.isPrivate, bet.isPrivate)
set(it.createdBy, bet.createdBy)
}
ResponsesEntity.addResponse(bet.response,fromString(bet.id))
}
}

@ -1,12 +1,10 @@
package allin.entities
import allin.database
import allin.model.Participation
import allin.utils.Execute
import org.ktorm.dsl.*
import org.ktorm.entity.Entity
import org.ktorm.schema.*
import java.util.*
import org.ktorm.schema.Table
import org.ktorm.schema.int
import org.ktorm.schema.uuid
import org.ktorm.schema.varchar
interface ParticipationEntity : Entity<ParticipationEntity> {
val id: String
@ -23,68 +21,4 @@ object ParticipationsEntity : Table<BetEntity>("participation") {
val username = varchar("username")
val answer = varchar("answer")
val stake = int("stake")
fun createParticipationTable(){
val request="CREATE TABLE IF NOT EXISTS participation (id uuid PRIMARY KEY,bet uuid,username varchar(250),answer varchar(250),stake int);"
database.Execute(request)
}
fun addParticipationEntity(participation : Participation){
database.insert(ParticipationsEntity){
set(it.id, UUID.fromString(participation.id))
set(it.betId,UUID.fromString(participation.betId))
set(it.username,participation.username)
set(it.answer,participation.answer)
set(it.stake,participation.stake)
}
}
fun getParticipationEntityFromBetId(betid: String): MutableList<Participation> {
return database.from(ParticipationsEntity)
.select()
.where { betId eq UUID.fromString(betid) }
.map { row ->
Participation(
row[id].toString(),
row[betId].toString(),
row[username].toString(),
row[answer].toString(),
row[stake] ?: 0,
)
}.toMutableList()
}
fun getParticipationEntityFromUserId(user: String, betid: String): MutableList<Participation> {
return database.from(ParticipationsEntity)
.select()
.where { (betId eq UUID.fromString(betid)) and (username eq user) }
.map { row ->
Participation(
row[id].toString(),
row[betId].toString(),
row[username].toString(),
row[answer].toString(),
row[stake] ?: 0,
)
}.toMutableList()
}
fun getParticipationEntity(): MutableList<Participation> {
return database.from(ParticipationsEntity).select().map {
row -> Participation(
row[id].toString(),
row[betId].toString(),
row[username].toString(),
row[answer].toString(),
row[stake]?:0,
)
}.toMutableList()
}
fun deleteParticipation(participation: Participation): Boolean {
val deletedCount = database.delete(ParticipationsEntity) {
it.id eq UUID.fromString(participation.id)
}
return deletedCount > 0
}
}

@ -1,8 +1,5 @@
package allin.entities
import allin.database
import allin.utils.Execute
import org.ktorm.dsl.*
import org.ktorm.entity.Entity
import org.ktorm.schema.Table
import org.ktorm.schema.uuid
@ -18,6 +15,8 @@ interface ResponseEntity : Entity<ResponseEntity> {
object ResponsesEntity : Table<ResponseEntity>("response") {
val id = uuid("id").primaryKey()
val response = varchar("response").primaryKey()
/*
fun createResponseTable(){
val request="CREATE TABLE IF NOT EXISTS response (id UUID,response VARCHAR(250),CONSTRAINT pk_response_id PRIMARY KEY (id,response));"
database.Execute(request)
@ -38,4 +37,5 @@ object ResponsesEntity : Table<ResponseEntity>("response") {
}
}
}
*/
}

@ -1,13 +1,10 @@
package allin.entities
import allin.database
import allin.dto.UserDTO
import allin.model.User
import allin.utils.Execute
import org.ktorm.dsl.*
import org.ktorm.entity.*
import org.ktorm.schema.*
import java.util.UUID.fromString
import org.ktorm.entity.Entity
import org.ktorm.schema.Table
import org.ktorm.schema.int
import org.ktorm.schema.uuid
import org.ktorm.schema.varchar
interface UserEntity : Entity<UserEntity> {
val username: String
@ -15,70 +12,13 @@ interface UserEntity : Entity<UserEntity> {
var password: String
var nbCoins: Int
}
object UsersEntity : Table<UserEntity>("utilisateur") {
val id = uuid("id").primaryKey()
val username = varchar("username")
val password = varchar("password")
val nbCoins = int("coins")
val email = varchar("email")
fun getUserToUserDTO(): MutableList<UserDTO> {
return database.from(UsersEntity).select().map {
row -> UserDTO(
row[id].toString(),
row[username].toString(),
row[email].toString(),
row[nbCoins]?:0,
null
)
}.toMutableList()
}
fun createUserTable(){
val request="CREATE TABLE IF not exists utilisateur ( id uuid PRIMARY KEY, username VARCHAR(255), password VARCHAR(255),coins double precision,email VARCHAR(255))"
database.Execute(request)
}
fun modifyCoins(user: String, cost : Int){
val request = "UPDATE utilisateur SET coins = coins - $cost WHERE username = '$user';"
database.Execute(request)
}
fun getUserByUsernameAndPassword(login: String): Pair<UserDTO?, String?> {
return database.from(UsersEntity)
.select()
.where { (username eq login) /*and (password eq passwordParam)*/ }
.map { row ->
Pair(
UserDTO(
row[id].toString(),
row[username].toString(),
row[email].toString(),
row[nbCoins]?:0,
null
),
row[password].toString()
)
}
.firstOrNull() ?: Pair(null, null)
}
fun addUserEntity(user : User){
database.insert(UsersEntity){
set(it.id,fromString(user.id))
set(it.nbCoins,user.nbCoins)
set(it.username,user.username)
set(it.password,user.password)
set(it.email,user.email)
}
}
fun deleteUserByUsername(username: String): Boolean {
val deletedCount = database.delete(UsersEntity) {
it.username eq username
}
return deletedCount > 0
}
}

@ -1,7 +1,7 @@
package allin.ext
import allin.data.UserDataSource
import allin.dto.UserDTO
import allin.entities.UsersEntity
import allin.model.ApiMessage
import io.ktor.http.*
import io.ktor.server.application.*
@ -14,11 +14,12 @@ suspend fun PipelineContext<*, ApplicationCall>.hasToken(content: suspend (princ
call.principal<JWTPrincipal>()?.let { content(it) } ?: call.respond(HttpStatusCode.Unauthorized)
suspend fun PipelineContext<*, ApplicationCall>.verifyUserFromToken(
userDataSource: UserDataSource,
principal: JWTPrincipal,
content: suspend (user: UserDTO, password: String) -> Unit
) {
val username = principal.payload.getClaim("username").asString()
val userPassword = UsersEntity.getUserByUsernameAndPassword(username)
val userPassword = userDataSource.getUserByUsername(username)
userPassword.first?.let { content(it, userPassword.second ?: "") }
?: call.respond(HttpStatusCode.NotFound, ApiMessage.TokenUserNotFound)
}

@ -1,8 +1,6 @@
package allin.routing
import allin.entities.BetsEntity.getBets
import allin.entities.ParticipationsEntity.getParticipationEntityFromBetId
import allin.entities.ParticipationsEntity.getParticipationEntityFromUserId
import allin.dataSource
import allin.ext.hasToken
import allin.ext.verifyUserFromToken
import allin.model.BetDetail
@ -14,14 +12,18 @@ import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.BetDetailRouter() {
val userDataSource = this.dataSource.userDataSource
val betDataSource = this.dataSource.betDataSource
val participationDataSource = this.dataSource.participationDataSource
routing {
authenticate {
get("/betdetail/get/{id}") {
hasToken { principal ->
verifyUserFromToken(principal) { user, _ ->
verifyUserFromToken(userDataSource, principal) { user, _ ->
val id = call.parameters["id"].toString()
val participations = getParticipationEntityFromBetId(id)
val selectedBet = getBets().find { it.id == id }
val participations = participationDataSource.getParticipationFromBetId(id)
val selectedBet = betDataSource.getBetById(id)
if (selectedBet != null) {
call.respond(
HttpStatusCode.Accepted,
@ -29,7 +31,7 @@ fun Application.BetDetailRouter() {
selectedBet,
getBetAnswerDetail(selectedBet, participations),
participations.toList(),
getParticipationEntityFromUserId(user.username, id).lastOrNull()
participationDataSource.getParticipationFromUserId(user.username, id).lastOrNull()
)
)
} else {

@ -1,10 +1,6 @@
package allin.routing
import allin.entities.BetsEntity.addBetEntity
import allin.entities.BetsEntity.getBets
import allin.entities.BetsEntity.getBetsNotFinished
import allin.entities.ParticipationsEntity.getParticipationEntity
import allin.entities.ParticipationsEntity.getParticipationEntityFromUserId
import allin.dataSource
import allin.ext.hasToken
import allin.ext.verifyUserFromToken
import allin.model.ApiMessage
@ -22,34 +18,37 @@ import java.util.*
val tokenManagerBet = AppConfig.tokenManager
fun Application.BetRouter() {
val userDataSource = this.dataSource.userDataSource
val betDataSource = this.dataSource.betDataSource
val participationDataSource = this.dataSource.participationDataSource
routing {
route("/bets/add") {
authenticate {
post {
hasToken { principal ->
val bet = call.receive<Bet>()
val id = UUID.randomUUID().toString()
val username = tokenManagerBet.getUsernameFromToken(principal)
val bets = getBets()
bets.find { it.id == id }?.let {
call.respond(HttpStatusCode.Conflict, ApiMessage.BetAlreadyExist)
} ?: run {
val betWithId = Bet(
id,
bet.theme,
bet.sentenceBet,
bet.endRegistration,
bet.endBet,
bet.isPrivate,
bet.response,
username
)
addBetEntity(betWithId)
call.respond(HttpStatusCode.Created, betWithId)
}
}
post {
hasToken { principal ->
val bet = call.receive<Bet>()
val id = UUID.randomUUID().toString()
val username = tokenManagerBet.getUsernameFromToken(principal)
betDataSource.getBetById(id)?.let {
call.respond(HttpStatusCode.Conflict, ApiMessage.BetAlreadyExist)
} ?: run {
val betWithId = Bet(
id,
bet.theme,
bet.sentenceBet,
bet.endRegistration,
bet.endBet,
bet.isPrivate,
bet.response,
username
)
betDataSource.addBet(betWithId)
call.respond(HttpStatusCode.Created, betWithId)
}
}
}
}
}
}
@ -57,17 +56,15 @@ fun Application.BetRouter() {
route("/bets/gets") {
get {
// if(bets.size>0)
val bets= getBets()
call.respond(HttpStatusCode.Accepted, bets.toList())
call.respond(HttpStatusCode.Accepted, betDataSource.getAllBets())
// else call.respond(HttpStatusCode.NoContent)
}
}
route("/bets/get/{id}") {
get {
val bets= getBets()
val id = call.parameters["id"] ?: ""
bets.find { it.id == id }?.let { bet ->
betDataSource.getBetById(id)?.let { bet ->
call.respond(HttpStatusCode.Accepted, bet)
} ?: call.respond(HttpStatusCode.NotFound, ApiMessage.BetNotFound)
}
@ -75,35 +72,35 @@ fun Application.BetRouter() {
route("/bets/delete") {
post {
val idbet = call.receive<Map<String, String>>()["id"]
val bets= getBets()
bets.find { it.id == idbet }?.let { findbet ->
bets.remove(findbet)
call.respond(HttpStatusCode.Accepted, findbet)
} ?: call.respond(HttpStatusCode.NotFound, ApiMessage.BetNotFound)
val id = call.receive<Map<String, String>>()["id"] ?: ""
if (betDataSource.removeBet(id)) {
call.respond(HttpStatusCode.Accepted)
} else {
call.respond(HttpStatusCode.NotFound, ApiMessage.BetNotFound)
}
}
}
route("bets/update") {
post {
val updatedBetData = call.receive<UpdatedBetData>()
val bets= getBets()
bets.find { it.id == updatedBetData.id }?.let { findbet ->
findbet.endBet = updatedBetData.endBet
findbet.isPrivate = updatedBetData.isPrivate
findbet.response = updatedBetData.response
call.respond(HttpStatusCode.Accepted, findbet)
} ?: call.respond(HttpStatusCode.NotFound, ApiMessage.BetNotFound)
if (betDataSource.updateBet(updatedBetData)) {
call.respond(HttpStatusCode.Accepted)
} else {
call.respond(HttpStatusCode.NotFound, ApiMessage.BetNotFound)
}
}
}
authenticate {
get("/bets/current") {
hasToken { principal ->
verifyUserFromToken(principal) { user, _ ->
val currentBets = getBetsNotFinished()
verifyUserFromToken(userDataSource, principal) { user, _ ->
val currentBets = betDataSource.getBetsNotFinished()
.filter { bet ->
val userParticipation = getParticipationEntityFromUserId(user.username, bet.id)
userParticipation.isNotEmpty() || bet.createdBy == user.username
val userParticipation =
participationDataSource.getParticipationFromUserId(user.username, bet.id)
userParticipation.isNotEmpty()
}
call.respond(HttpStatusCode.OK, currentBets)

@ -1,9 +1,6 @@
package allin.routing
import allin.entities.ParticipationsEntity.addParticipationEntity
import allin.entities.ParticipationsEntity.deleteParticipation
import allin.entities.ParticipationsEntity.getParticipationEntity
import allin.entities.UsersEntity.modifyCoins
import allin.dataSource
import allin.ext.hasToken
import allin.ext.verifyUserFromToken
import allin.model.ApiMessage
@ -18,14 +15,18 @@ import io.ktor.server.routing.*
import java.util.*
fun Application.ParticipationRouter() {
val userDataSource = this.dataSource.userDataSource
val participationDataSource = this.dataSource.participationDataSource
routing {
authenticate {
post("/participations/add") {
hasToken { principal ->
val participation = call.receive<ParticipationRequest>()
verifyUserFromToken(principal) { user, _ ->
verifyUserFromToken(userDataSource, principal) { user, _ ->
if (user.nbCoins >= participation.stake) {
addParticipationEntity(
participationDataSource.addParticipation(
Participation(
id = UUID.randomUUID().toString(),
betId = participation.betId,
@ -34,7 +35,9 @@ fun Application.ParticipationRouter() {
stake = participation.stake
)
)
modifyCoins(user.username,participation.stake)
userDataSource.modifyUserCoins(username = user.username, amount = participation.stake)
call.respond(HttpStatusCode.Created)
} else {
call.respond(HttpStatusCode.Forbidden, ApiMessage.NotEnoughCoins)
@ -43,14 +46,13 @@ fun Application.ParticipationRouter() {
}
}
delete("/participations/delete") {
hasToken { principal ->
hasToken {
val participationId = call.receive<String>()
getParticipationEntity().find { it.id == participationId }?.let { participation ->
verifyUserFromToken(principal) { _, _ ->
deleteParticipation(participation)
call.respond(HttpStatusCode.NoContent)
}
} ?: call.respond(HttpStatusCode.NotFound, ApiMessage.ParticipationNotFound)
if (participationDataSource.deleteParticipation(participationId)) {
call.respond(HttpStatusCode.NoContent)
} else {
call.respond(HttpStatusCode.NotFound, ApiMessage.ParticipationNotFound)
}
}
}
}

@ -1,9 +1,6 @@
package allin.routing
import allin.entities.UsersEntity.addUserEntity
import allin.entities.UsersEntity.deleteUserByUsername
import allin.entities.UsersEntity.getUserByUsernameAndPassword
import allin.entities.UsersEntity.getUserToUserDTO
import allin.dataSource
import allin.ext.hasToken
import allin.ext.verifyUserFromToken
import allin.model.ApiMessage
@ -25,6 +22,8 @@ val tokenManagerUser = AppConfig.tokenManager
const val DEFAULT_COINS = 500
fun Application.UserRouter() {
val userDataSource = this.dataSource.userDataSource
routing {
route("/users/register") {
post {
@ -32,30 +31,29 @@ fun Application.UserRouter() {
if (RegexCheckerUser.isEmailInvalid(tempUser.email)) {
call.respond(HttpStatusCode.Forbidden, ApiMessage.InvalidMail)
}
val users = getUserToUserDTO()
users.find { it.username == tempUser.username || it.email == tempUser.email }?.let { _ ->
if (userDataSource.userExists(tempUser.username, tempUser.email)) {
call.respond(HttpStatusCode.Conflict, ApiMessage.UserAlreadyExist)
} ?: run {
val user = User(
id = UUID.randomUUID().toString(),
username = tempUser.username,
email = tempUser.email,
password = tempUser.password,
nbCoins = DEFAULT_COINS,
token = null
)
CryptManagerUser.passwordCrypt(user)
user.token = tokenManagerUser.generateOrReplaceJWTToken(user)
addUserEntity(user)
call.respond(HttpStatusCode.Created, user)
}
val user = User(
id = UUID.randomUUID().toString(),
username = tempUser.username,
email = tempUser.email,
password = tempUser.password,
nbCoins = DEFAULT_COINS,
token = null
)
CryptManagerUser.passwordCrypt(user)
user.token = tokenManagerUser.generateOrReplaceJWTToken(user)
userDataSource.addUser(user)
call.respond(HttpStatusCode.Created, user)
}
}
route("/users/login") {
post {
val checkUser = call.receive<CheckUser>()
val user = getUserByUsernameAndPassword(checkUser.login)
val user = userDataSource.getUserByUsername(checkUser.login)
if (CryptManagerUser.passwordDecrypt(user.second ?: "", checkUser.password)) {
user.first?.let { userDtoWithToken ->
userDtoWithToken.token = tokenManagerUser.generateOrReplaceJWTToken(userDtoWithToken)
@ -70,11 +68,10 @@ fun Application.UserRouter() {
authenticate {
post("/users/delete") {
hasToken { principal ->
verifyUserFromToken(principal) { _, password ->
verifyUserFromToken(userDataSource, principal) { _, password ->
val checkUser = call.receive<CheckUser>()
if (CryptManagerUser.passwordDecrypt(password, checkUser.password)) {
if (!deleteUserByUsername(checkUser.login)) {
if (!userDataSource.deleteUser(checkUser.login)) {
call.respond(HttpStatusCode.InternalServerError, "This user can't be delete now !")
}
call.respond(HttpStatusCode.Accepted, password)
@ -88,7 +85,7 @@ fun Application.UserRouter() {
get("/users/token") {
hasToken { principal ->
verifyUserFromToken(principal) { userDto, _ ->
verifyUserFromToken(userDataSource, principal) { userDto, _ ->
call.respond(HttpStatusCode.OK, userDto)
}
}

@ -1,11 +1,10 @@
package allin.utils
import allin.database
import org.ktorm.database.Database
fun Database.Execute(request: String){
if(!request.isNullOrEmpty())
database.useTransaction {
fun Database.Execute(request: String) {
if (request.isNotEmpty())
this.useTransaction {
val connection = it.connection
connection.prepareStatement(request).execute()
connection.commit()

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save