MyCodeFlow
08/30/2021, 5:39 AMfun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module(testing: Boolean = false) {
//initialization of the Database
DataBaseFactory.init()
val userDb = UserDataBaseDao() //Users Database
val loveCardDb = LoveCardsDataBaseDao()
val hashFunction = { s: String -> hash(s) }
val jwtService = JwtService()
//installing content receive/respond functionality
install(ContentNegotiation) {
json() //converter for serialization of kotlin classes
}
//installing authentication
install(Authentication){
jwt("jwt") {
verifier(jwtService.varifier)
realm = "Lovecard server"
validate {
val payload = it.payload
val email = payload.getClaim("email").asString()
val user = userDb.findUserByEmail(email)
user
}
}
}
//installing WebSocket
install(WebSockets) {
pingPeriod = Duration.ofSeconds(15)
timeout = Duration.ofSeconds(15)
maxFrameSize = Long.MAX_VALUE
masking = false
}
routing {
//basic route on connection to server
get("/") {
call.respondText("Hello world!", contentType = ContentType.Text.Plain)
}
//echo unit of websocket
webSocket("/echo") {
send("Please enter your name")
for (frame in incoming) {
when (frame) {
is Frame.Text -> {
val receivedText = frame.readText()
if (receivedText.equals("bye", ignoreCase = true)) {
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
} else {
send(Frame.Text("Hi, $receivedText!"))
}
}
}
}
}
//Websocket for data exchange
val connections = Collections.synchronizedSet<Connection?>(LinkedHashSet())
webSocket("/connection") {
val thisConnection = Connection(this)
connections += thisConnection
send("You've logged in as [${thisConnection.name}]")
for (frame in incoming) {
when (frame) {
is Frame.Text -> {
val receivedText = frame.readText()
val textWithUsername = "[${thisConnection.name}]: $receivedText"
connections.forEach {
it.session.send(textWithUsername)
}
}
}
}
}
//register Authentication routes
authRouting(hashFunction, jwtService)
//register User routes
userRouting(userDb, jwtService, hashFunction)
//register LoveCards routes
loveCardsRouting(loveCardDb)
}
class Connection(val session: DefaultWebSocketSession) {
companion object{
var lastId = AtomicInteger(0)
}
val name = "User ${lastId.getAndIncrement()}"
}
}
Aleksei Tirman [JB]
08/30/2021, 1:55 PMMyCodeFlow
08/30/2021, 2:16 PM