https://kotlinlang.org logo
Title
a

Allen Eubank

01/29/2021, 4:48 PM
Hi, friends. I’m working on a ktor server and am having trouble refactoring this bit of code. I want to move this bit of Authentication code into another file/class, specifically the validate credentials call. But I’m having a bit of trouble with the kotlin syntax. Any tips to point me in the right direction? Or more generally, is there a way to move the install features calls into separate files?
/** Application.main() */
val db: SqlDelightDatabase by inject()
val orgDb: OrgDb by inject()

install(Authentication) {
    basic(name = "orgtoken") {
        validate { credentials ->
            if (credentials.name.isEmpty() or credentials.name.isEmpty()) return@validate null
            val org = db.organizationQueries.selectByHttpAuthUsername(credentials.name)
                .executeAsOneOrNull() ?: return@validate null
            val orgQueries = orgDb.instance(org) ?: return@validate null
            val activeToken = orgQueries.tokenQueries.validToken(credentials.password).executeAsOne()

            if (activeToken) {
                return@validate OrganizationPrincipal(org)
            } else {
                return@validate null
            }
        }
    }
}
Oh wow, sorry, it came to me after I wrote my prompt. It really is as simple as the following.
/** OrgAuth.kt */
fun Application.orgAuth() {
    val db: SqlDelightDatabase by inject()
    val orgDb: OrgDb by inject()

    install(Authentication) {
        basic(name = "orgtoken") {
            validate { credentials ->
                if (credentials.name.isEmpty() or credentials.name.isEmpty()) return@validate null
                val org = db.organizationQueries.selectByHttpAuthUsername(credentials.name)
                    .executeAsOneOrNull() ?: return@validate null
                val orgQueries = orgDb.instance(org) ?: return@validate null
                val activeToken = orgQueries.tokenQueries.validToken(credentials.password).executeAsOne()

                if (activeToken) {
                    return@validate OrganizationPrincipal(org)
                } else {
                    return@validate null
                }
            }
        }
    }
}
Then, you can just call
orgAuth
to install the feature.