47
loading...
This website collects cookies to deliver better user experience
class JwtService {
private const val secret = "cXRIJ57575KKFDJFcmcm"
private const val issuer = "ktor.io"
private val algorithm = Algorithm.HMAC512(secret)
val verifier: JWTVerifier = JWT
.require(algorithm)
.withIssuer(issuer)
.build()
fun generateToken(userId: String): String = JWT.create()
.withSubject("Authentication")
.withIssuer(issuer)
.withClaim("userId", userId)
.withExpiresAt(expiresAt())
.sign(algorithm)
private fun expiresAt() =
Date(System.currentTimeMillis() + 3_600_000 * 24) // 24 hours
}
val jwtService = JwtService()
fun Application.module(testing: Boolean = false) {
install(Authentication) {
jwt{
verifier(jwtService.verifier)
realm = JWT_REALM
validate {
val userId = it.payload.getClaim(CLAIM_USERID).asInt()
val user = mongoDataHandler.finduser(userId) // 4
PrincipalUser(user?.userId!!.toString())
}
}
}
data class PrincipalUser(val userId: String): Principal
version: '3'
services:
mymongo:
image: mongo:latest
ports:
- 27017:27017
implementation "org.mongodb:mongodb-driver:3.12.9"
class MongoDBdata{
val database: MongoDatabase
val userCollection: MongoCollection<User>
init{
val pojoCodecRegistry: CodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build())
val codecRegistry: CodecRegistry = fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
pojoCodecRegistry)
val clientSettings = MongoClientSettings.builder()
.codecRegistry(codecRegistry)
.build()
val mongoClient = MongoClients.create(clientSettings)
database = mongoClient.getDatabase("mydatabase");
userCollection = database.getCollection(User::class.java.name, User::class.java)
userCollection.insertOne(User(userId = null, email= "good", userName = "username", passwordHash = "password"))
}
fun adduser(email: String, username: String, password: String): User? {
userCollection.insertOne(User(userId = null, email = email, userName = username, passwordHash = password))
return userCollection.find(Filters.eq("email", email)).first()
}
fun finduser(id: Int): User?{
return userCollection.find(Filters.eq("_id", id)).first()
}
fun finduserByEmail(email: String): User?{
return userCollection.find(Filters.eq("email",email)).first()
}
}
class User(userId: ObjectId?,
email: String= "email",
userName: String = "username",
passwordHash: String= "password"): Serializable{
@BsonId
var userId: ObjectId?
var email: String
var userName: String
var passwordHash: String
constructor() : this(null, "void", "void"){}
init{
this.userId = userId
this.email = email
this.userName = userName
this.passwordHash = passwordHash
}
}
const val USERLOGIN = "/login"
const val USERCREATE = "/create"
val mongoDBdata= MongoDBdata()
@Location(USERCREATE)
class Register{
}
@Location(USERLOGIN)
class Login{
}
fun Routing.userRoutes(){
post<Register>{
val signupParameters = call.receiveParameters()
val password = signupParameters["password"]
?: return@post call.respond(
HttpStatusCode.Unauthorized, "Missing Fields")
val userName = signupParameters["userName"]
?: return@post call.respond(
HttpStatusCode.Unauthorized, "Missing Fields")
val email = signupParameters["email"]
?: return@post call.respond(
HttpStatusCode.Unauthorized, "Missing Fields")
try {
val user = mongoDBdata.adduser(email, userName, password)
user?.userId?.let{
call.respondText(
jwtService.generateToken(user.userId!!.toString()),
status = HttpStatusCode.Created
)
}
}catch (e: Throwable) {
application.log.error("Failed to register user", e)
call.respond(HttpStatusCode.BadRequest, "Problems creating User")
}
}
post<Login> {
val signinParameters = call.receive<Parameters>()
val password = signinParameters["password"]
?: return@post call.respond(
HttpStatusCode.Unauthorized, "Missing Fields")
val email = signinParameters["email"]
?: return@post call.respond(
HttpStatusCode.Unauthorized, "Missing Fields")
try {
val presentUser = mongoDBdata.finduserByEmail(email)
presentUser?.userId?.let { call.respondText(jwtService.generateToken(presentUser.userId!!.toString()))
if (currentUser.passwordHash == hash) {
call.sessions.set(MySession(it.toString()))
call.respondText(jwtService.generateToken(currentUser.userId!!.toString()))
} else {
call.respond(
HttpStatusCode.BadRequest, "Problems retrieving User")
}
}
} catch (e: Throwable) {
application.log.error("Failed to register user", e)
call.respond(HttpStatusCode.BadRequest, "Problems retrieving User")
}
}
}
data class MySession(val userId: String)
fun Application.module(testing: Boolean = false) {
routing {
userRoutes()
authenticate {
get("/"){
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
}
}
}