https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
i

IsaacMart

09/29/2021, 3:28 AM
Hello guys. Am working on a ktor project where am using sessions to store the current userId. I have followed the docs but anytime i want to get my session for userId i am receiving null. I have seen several pple go through this but i haven't found a solution yet. Here is my code and depedencies am using. My Application Class
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@KtorExperimentalAPI
@KtorExperimentalLocationsAPI
@Suppress("unused") // Referenced in application.conf
fun Application.module() {
    install(Locations) {
    }

    install(Sessions) {
        cookie<MySession>("MY_SESSION") {
            cookie.extensions["SameSite"] = "lax"
        }
    }

    DatabaseFactory.init()
    val userRepository = UserRepositoryImp()
    val taskerRepository = TaskerRepositoryImp()
    val requestRepository = RequestRepositoryImp()
    val messageRepository = MessageRepositoryImp()
    val reviewRepository = ReviewRepositoryImp()
    val jwtService = JwtService()
    val hashFunction = { s: String -> hash(s) }

    install(Authentication) {
        jwt("jwt") {
            verifier(jwtService.verifier)
            realm = "Tasksfy"
            validate {
                val payload = it.payload
                val claim = payload.getClaim("id")
                val claimString = claim.asInt()
                val user = userRepository.getUser(claimString)
                user
            }
        }

    }

}
My userRoute class for login.Where am storing the session id
@KtorExperimentalLocationsAPI
fun Route.users(db: UserRepository, jwtService: JwtService, hashFunction: (String) -> String) {

    post<UserLoginRoute> {
        val signInParameters = call.receive<Parameters>()
        val password =
            signInParameters["password"] ?: return@post call.respond(HttpStatusCode.Unauthorized, "Missing Fields")
        val phoneNumber = signInParameters["phone_number"] ?: return@post call.respond(
            HttpStatusCode.Unauthorized,
            "Missing Fields"
        )

        val hash = hashFunction(password)

        try {
            val currentUser = db.getUserByPhone(phoneNumber)
            currentUser?.user_id?.let {
                if (currentUser.password == hash) {
                    call.sessions.set(MySession(it))  //Storing the user id here
                    val token = jwtService.generateToken(currentUser)
//                    call.respondText(jwtService.generateToken(currentUser))
                    call.respond(
                        ResponseDefault(
                            BaseResponse(true, "Welcome back " + currentUser.first_name, token),
                            currentUser
                        )
                    )
                } else {
                    call.respond(BaseResponse(false, "Invalid Login details!", ""))
                }
            }

        } catch (e: Throwable) {
            application.log.error("Failed to register user", e)
            call.respond(BaseResponse(false, "Problem retrieving User.Try again later! " + e.message,""))
        }
    }
My Session Class
data class MySession(val userId : Int) {
}
Here is my depedencies incase there could be problem
:thread-please: 3
a

Aleksei Tirman [JB]

09/29/2021, 1:17 PM
Could you please check are you able to set data for a session without interaction with a database? Also, I don't see the code for retrieving data from a session.
i

IsaacMart

09/29/2021, 2:07 PM
Here is my code where i am retrieving the session. I have put them in away that i can be able to fetch certain data associated with a specific user.Thats why i need to know the current userId immediately after logging in
get<RequestsRoute> {
            val userId = call.sessions.get<MySession>()?.userId
            try {
                val requests = userId?.let { it1 -> db.getAllRequestsById(it1) }
                call.respond(ResponseDefault(BaseResponse(true, "Requests retrieved successfully", userId.toString()), requests))

            } catch (e: Throwable) {
                application.log.error("Failed to retrieve requests ", e)
                call.respond(BaseResponse(false, "Problems retrieving requests " + e.message, ""))
            }
        }
Here is a link to my depedencies https://kotlinlang.slack.com/archives/C0A974TJ9/p1632886098331100
a

Aleksei Tirman [JB]

09/29/2021, 3:23 PM
When I remove the code that interacts with a database then saving user ID in a session and retrieving it works as expected. I suggest to debug your application to make sure that the
call.sessions.set
call is actually executed. Please share a complete project or remove database dependency, otherwise it's very difficult to troubleshoot your problem.
i

IsaacMart

09/29/2021, 3:51 PM
Thanks @Aleksei Tirman [JB] I have tried setting a value to my session.but it seams that my call.sessions.set isn't executed.let me try fixing it now that i know where the problem is.incase of anything i will reach out
Hey @Aleksei Tirman [JB].My problem is based on a ktor course by @raywenderlich. My objective is to store the userId during logging so that i can be able to fetch requests associated wit that user through relationship. Here is a link to the whole project. I have tried to find a work around on how to set the session but with no avail. Any help will be highly appreciated. https://www.raywenderlich.com/7265034-ktor-rest-api-for-mobile
a

Aleksei Tirman [JB]

09/30/2021, 2:34 PM
I've created a working sample project guided by the article you gave. To test it you need to update environment variables in the run configuration to make a proper connection to a database. Make a POST request to
<http://localhost:8080/v1/users/create>
to create a user, then POST request to
<http://localhost:8080/v1/users/login>
to update the session and a GET request to
<http://localhost:8080/v1/users>
to display greetings for a user.
i

IsaacMart

10/03/2021, 6:27 PM
Hello @Aleksei Tirman [JB] Am very grateful for your assistance. I tried the rest_mobile in ktor that you sent and it works fine. I have changed my depedencies to match with those in your project. I was using ktor_version=1.4.1 to 1.6.3 My server runs fine but when i try accessing routes it issues an error "The server returned an invalid or incomplete HTTP response." Here is the running project with ktor_version=1.4.1 sessions not working. I suspect that i might be missing out on old versions of dependencies. Your assistance will be highly appreciated.
a

Aleksei Tirman [JB]

10/04/2021, 7:46 AM
Could you please explain to me why do you use an outdated version of Ktor? There are probably some bugs that were fixed in newer versions.
i

IsaacMart

10/04/2021, 8:01 AM
I had just started learning ktor to migrate my android app from firebase. The first ktor course a found by https://www.raywenderlich.com was using ktor 1.4.1. Being a novice i feared tampering with dependencies.😅 I would appreciate it if you helped me restructure to latest.Since there are limited resources. and mentors to it.Thanks
a

Aleksei Tirman [JB]

10/12/2021, 2:28 PM
Sorry for being out of touch for quite a while. I've updated dependencies in your project. The problem with an empty response is due to the transitive Netty dependency of
com.github.AfricasTalkingLtd.africastalking-java:core
artifact. As a quick workaround, you can use the Jetty engine (this is already fixed in the attached project).
i

IsaacMart

10/12/2021, 2:37 PM
Thank you very much. Not every one would be king enough to help. The AfricanTalking depedency its for bulk sms provider just like Twillo but its affordable here in africa and also reliable.