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

Migrate to HttpServer #76

Merged
merged 11 commits into from
Apr 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Binary file added data/404.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 4 additions & 3 deletions src/main/scala/lc/background/taskThread.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import java.util.concurrent.{ScheduledThreadPoolExecutor, TimeUnit}
import lc.core.Captcha
import lc.core.{Parameters, Size}

class BackgroundTask(captcha: Captcha, throttle: Int, timeLimit: Int) {
class BackgroundTask(throttle: Int, timeLimit: Int) {

val captcha = new Captcha()
rr83019 marked this conversation as resolved.
Show resolved Hide resolved

private val task = new Runnable {
def run(): Unit = {
try {

val mapIdGCPstmt = Statements.tlStmts.get.mapIdGCPstmt
mapIdGCPstmt.setInt(1, timeLimit)
mapIdGCPstmt.executeUpdate()
Expand All @@ -26,7 +27,7 @@ class BackgroundTask(captcha: Captcha, throttle: Int, timeLimit: Int) {
captcha.generateChallenge(Parameters("medium", "image/png", "text", Option(Size(0, 0))))
throttleIn -= 1
}
} catch { case e: Exception => println(e) }
} catch { case exception: Exception => println(exception.getStackTrace) }
}
}

Expand Down
124 changes: 57 additions & 67 deletions src/main/scala/lc/core/captcha.scala
Original file line number Diff line number Diff line change
@@ -1,38 +1,42 @@
package lc.core

import java.sql.{Blob, ResultSet}
import java.sql.ResultSet
import java.util.UUID
import java.io.ByteArrayInputStream
import lc.database.Statements
import lc.core.CaptchaProviders
import lc.captchas.interfaces.ChallengeProvider
import java.nio.file.{Files, Paths}


class Captcha {

def getCaptcha(id: Id): Array[Byte] = {
var image: Array[Byte] = null
var blob: Blob = null
try {
val imagePath = "data/404.jpg"
val imagePstmt = Statements.tlStmts.get.imagePstmt
imagePstmt.setString(1, id.id)
val rs: ResultSet = imagePstmt.executeQuery()
if (rs.next()) {
blob = rs.getBlob("image")
if (blob != null) {
image = blob.getBytes(1, blob.length().toInt)
val image = if (rs.next()) {
val blob = rs.getBlob("image")
val imageBytes = if (blob != null) {
blob.getBytes(1, blob.length().toInt)
} else {
Files.readAllBytes(Paths.get(imagePath))
rr83019 marked this conversation as resolved.
Show resolved Hide resolved
}
imageBytes
} else {
Files.readAllBytes(Paths.get(imagePath))
rr83019 marked this conversation as resolved.
Show resolved Hide resolved
}
image
} catch {
case e: Exception =>
println(e)
image
case exception: Exception =>
println(exception.getStackTrace)
throw new Exception(exception.getMessage)
}
}

def generateChallenge(param: Parameters): Int = {
val provider = CaptchaProviders.getProvider(param)
if (!provider.isInstanceOf[ChallengeProvider]) return -1
val providerId = provider.getId()
val challenge = provider.returnChallenge()
val blob = new ByteArrayInputStream(challenge.content)
Expand All @@ -57,49 +61,28 @@ class Captcha {
val allowedLevels = Config.allowedLevels
val allowedMedia = Config.allowedMedia

private def validateParam(param: Parameters): Boolean = {
if (
allowedLevels.contains(param.level) &&
allowedMedia.contains(param.media) &&
allowedInputType.contains(param.input_type)
)
return true
else
return false
}

def getChallenge(param: Parameters): ChallengeResult = {
def getChallenge(param: Parameters): Id = {
try {
val validParam = validateParam(param)
if (validParam) {
val tokenPstmt = Statements.tlStmts.get.tokenPstmt
tokenPstmt.setString(1, param.level)
tokenPstmt.setString(2, param.media)
tokenPstmt.setString(3, param.input_type)
val rs = tokenPstmt.executeQuery()
val tokenOpt = if (rs.next()) {
Some(rs.getInt("token"))
} else {
None
}
val updateAttemptedPstmt = Statements.tlStmts.get.updateAttemptedPstmt
val token = tokenOpt.getOrElse(generateChallenge(param))
val result = if (token != -1) {
val uuid = getUUID(token)
updateAttemptedPstmt.setString(1, uuid)
updateAttemptedPstmt.executeUpdate()
Id(uuid)
} else {
Error(ErrorMessageEnum.NO_CAPTCHA.toString)
}
result
val tokenPstmt = Statements.tlStmts.get.tokenPstmt
tokenPstmt.setString(1, param.level)
tokenPstmt.setString(2, param.media)
tokenPstmt.setString(3, param.input_type)
val rs = tokenPstmt.executeQuery()
val tokenOpt = if (rs.next()) {
Some(rs.getInt("token"))
} else {
Error(ErrorMessageEnum.INVALID_PARAM.toString)
None
}
val updateAttemptedPstmt = Statements.tlStmts.get.updateAttemptedPstmt
val token = tokenOpt.getOrElse(generateChallenge(param))
val uuid = getUUID(token)
updateAttemptedPstmt.setString(1, uuid)
updateAttemptedPstmt.executeUpdate()
Id(uuid)
} catch {
case e: Exception =>
println(e)
Error(ErrorMessageEnum.SMW.toString)
case exception: Exception =>
println(exception.getStackTrace)
throw new Exception(exception.getMessage)
}
}

Expand All @@ -113,23 +96,30 @@ class Captcha {
}

def checkAnswer(answer: Answer): Result = {
val selectPstmt = Statements.tlStmts.get.selectPstmt
selectPstmt.setInt(1, Config.captchaExpiryTimeLimit)
selectPstmt.setString(2, answer.id)
val rs: ResultSet = selectPstmt.executeQuery()
val psOpt = if (rs.first()) {
val secret = rs.getString("secret")
val provider = rs.getString("provider")
val check = CaptchaProviders.getProviderById(provider).checkAnswer(secret, answer.answer)
val result = if (check) ResultEnum.TRUE.toString else ResultEnum.FALSE.toString
result
} else {
ResultEnum.EXPIRED.toString
try{
val selectPstmt = Statements.tlStmts.get.selectPstmt
selectPstmt.setInt(1, Config.captchaExpiryTimeLimit)
selectPstmt.setString(2, answer.id)
val rs: ResultSet = selectPstmt.executeQuery()
val psOpt = if (rs.first()) {
val secret = rs.getString("secret")
val provider = rs.getString("provider")
val check = CaptchaProviders.getProviderById(provider).checkAnswer(secret, answer.answer)
val result = if (check) ResultEnum.TRUE.toString else ResultEnum.FALSE.toString
result
} else {
ResultEnum.EXPIRED.toString
}
val deleteAnswerPstmt = Statements.tlStmts.get.deleteAnswerPstmt
deleteAnswerPstmt.setString(1, answer.id)
deleteAnswerPstmt.executeUpdate()
Result(psOpt)
} catch {
case exception: Exception => {
println(exception.getStackTrace)
throw new Exception(exception.getMessage)
rr83019 marked this conversation as resolved.
Show resolved Hide resolved
}
}
val deleteAnswerPstmt = Statements.tlStmts.get.deleteAnswerPstmt
deleteAnswerPstmt.setString(1, answer.id)
deleteAnswerPstmt.executeUpdate()
Result(psOpt)
}

def display(): Unit = {
Expand Down
1 change: 1 addition & 0 deletions src/main/scala/lc/core/captchaProviders.scala
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ object CaptchaProviders {

def getProvider(param: Parameters): ChallengeProvider = {
val providerConfig = filterProviderByParam(param).toList
if (providerConfig.length == 0) throw new NoSuchElementException(ErrorMessageEnum.NO_CAPTCHA.toString)
val randomIndex = getNextRandomInt(providerConfig.length)
val providerIndex = providerConfig(randomIndex)._1
val selectedProvider = providers(providerIndex)
Expand Down
7 changes: 6 additions & 1 deletion src/main/scala/lc/core/config.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ object Config {
configFile.close
configFileContent
} catch {
case _: FileNotFoundException =>
case _: FileNotFoundException => {
val configFileContent = getDefaultConfig()
val configFile = new PrintWriter(new File(configFilePath))
configFile.write(configFileContent)
configFile.close
configFileContent
}
case exception: Exception => {
println(exception.getStackTrace)
throw new Exception(exception.getMessage)
}
}

private val configJson = parse(configString)
Expand Down