revert 1374f48ed2
continuous-integration/drone/push Build is passing Details

revert  Add DailyGift route
pull/7/head
Lucas EVARD 10 months ago
parent 1374f48ed2
commit 7692c6b463

@ -0,0 +1,100 @@
package allin.entities
import allin.database
import allin.dto.UserDTO
import allin.model.User
import allin.utils.Execute
import io.ktor.util.date.*
import org.h2.util.DateTimeUtils.currentTimestamp
import org.ktorm.dsl.*
import org.ktorm.entity.*
import org.ktorm.schema.*
import java.time.Duration
import java.util.*
import java.util.UUID.fromString
interface UserEntity : Entity<UserEntity> {
val username: String
var email: String
var password: String
var nbCoins: Double
}
object UsersEntity : Table<UserEntity>("utilisateur") {
val id = uuid("id").primaryKey()
val username = varchar("username")
val password = varchar("password")
val nbCoins = double("coins")
val email = varchar("email")
val lastGift = varchar("lastgift")
fun getUserToUserDTO(): MutableList<UserDTO> {
return database.from(UsersEntity).select().map {
row -> UserDTO(
row[id].toString(),
row[username].toString(),
row[email].toString(),
row[nbCoins]?:0.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), lastgift timestamp)"
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.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
}
fun canHaveDailyGift(username: String): Boolean {
val request = "SELECT CASE WHEN lastgift IS NULL THEN TRUE ELSE lastgift < current_timestamp - interval '1 day' END AS can_have_daily_gift, " +
"CASE WHEN lastgift IS NULL THEN null ELSE current_timestamp - lastgift END AS time_remaining " +
"FROM utilisateur WHERE username = '$username';"
val returnCode= database.Execute(request)
if(returnCode?.next().toString()=="true"){
return true
}
return false
}
}

@ -0,0 +1,105 @@
package allin.routing
import allin.entities.UsersEntity.addUserEntity
import allin.entities.UsersEntity.canHaveDailyGift
import allin.entities.UsersEntity.deleteUserByUsername
import allin.entities.UsersEntity.getUserByUsernameAndPassword
import allin.entities.UsersEntity.getUserToUserDTO
import allin.ext.hasToken
import allin.ext.verifyUserFromToken
import allin.model.*
import allin.utils.AppConfig
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 java.util.*
val RegexCheckerUser = AppConfig.regexChecker
val CryptManagerUser = AppConfig.cryptManager
val tokenManagerUser = AppConfig.tokenManager
const val DEFAULT_COINS = 500
fun Application.UserRouter() {
routing {
route("/users/register") {
post {
val tempUser = call.receive<UserRequest>()
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 { _ ->
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)
}
}
}
route("/users/login") {
post {
val checkUser = call.receive<CheckUser>()
val user = getUserByUsernameAndPassword(checkUser.login)
if (CryptManagerUser.passwordDecrypt(user.second ?: "", checkUser.password)) {
user.first?.let { userDtoWithToken ->
userDtoWithToken.token = tokenManagerUser.generateOrReplaceJWTToken(userDtoWithToken)
call.respond(HttpStatusCode.OK, userDtoWithToken)
} ?: call.respond(HttpStatusCode.NotFound, ApiMessage.UserNotFound)
} else {
call.respond(HttpStatusCode.NotFound, ApiMessage.IncorrectLoginPassword)
}
}
}
authenticate {
post("/users/delete") {
hasToken { principal ->
verifyUserFromToken(principal) { _, password ->
val checkUser = call.receive<CheckUser>()
if (CryptManagerUser.passwordDecrypt(password, checkUser.password)) {
if (!deleteUserByUsername(checkUser.login)) {
call.respond(HttpStatusCode.InternalServerError, "This user can't be delete now !")
}
call.respond(HttpStatusCode.Accepted, password)
} else {
call.respond(HttpStatusCode.NotFound, "Login and/or password incorrect.")
}
}
}
}
get("/users/token") {
hasToken { principal ->
verifyUserFromToken(principal) { userDto, _ ->
call.respond(HttpStatusCode.OK, userDto)
}
}
}
get("/users/gift") {
hasToken { principal ->
verifyUserFromToken(principal) { userDto, _ ->
if(canHaveDailyGift(userDto.username))
call.respond(HttpStatusCode.OK, getDailyGift())
else call.respond(HttpStatusCode.MethodNotAllowed,"Le cadeau ne peut pas être récupéré")
}
}
}
}
}
}

@ -0,0 +1,21 @@
package allin.utils
import allin.database
import org.ktorm.database.Database
import java.sql.ResultSet
fun Database.Execute(request: String): ResultSet? {
try {
if (!request.isNullOrEmpty()) {
return database.useTransaction { transaction ->
val connection = transaction.connection
val resultSet = connection.prepareStatement(request).executeQuery()
resultSet
}
}
} catch (e: Exception){
println(e.message)
return null
}
return null
}
Loading…
Cancel
Save