org.jadala.auth.jwt.JsonWebTokenHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.jadala.auth.jwt.JsonWebTokenHandler.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jadala.auth.jwt;

import org.jadala.storage.ElasticClient;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 *
 * @author Jakob Adala
 */
public class JsonWebTokenHandler implements Handler<RoutingContext> {

    private final JsonWebTokenService signer;
    private final Vertx vertx;

    public JsonWebTokenHandler(Vertx vertx, JsonObject config) {
        this.signer = new JsonWebTokenService(vertx, config);
        this.vertx = vertx;
    }

    /**
     * Creates a JWT token for further requests. request params must contain valid 
     * email and password combination.
     * 
     * json request body:
     * {"email":<EMAIL>, "password":<PASSWORD>}
     * 
     * responses with 
     * status BAD_REQUEST: missing parameter
     * or status UNAUTHORIZED: email/password not valid
     * or status CREATED with content-type "application/json" and response body:
     *  {"jwt":<JWT_TOKEN>}
     * 
     * 
     * @param routingContext 
     */
    @Override
    public void handle(RoutingContext routingContext) {
        HttpServerResponse response = routingContext.response();
        JsonObject loginForm = null;
        try {
            loginForm = routingContext.getBodyAsJson();
        } catch (DecodeException de) {
            de.printStackTrace();
            response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
            return;
        }
        String email = loginForm.getString("email");
        String password = loginForm.getString("password");
        if (email == null || email.length() == 0 || password == null || password.length() == 0) {
            response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
            return;
        }
        String query = "{ \"_source\":true," + " \"query\" : " + "{\"filtered\" : " + "{\"filter\" : "
                + "{\"bool\" : " + "{\"must\": [" + "{\"term\":{\"email\":\"" + email + "\"}},"
                + "{\"term\":{ \"password\":\"" + password + "\"}}]}}}}}";
        JsonObject msg = new JsonObject(query);

        vertx.eventBus().send("elastic", msg, ElasticClient.commandOptions("usermanager", "users", "_search"),
                (AsyncResult<Message<JsonObject>> async) -> {

                    if (async.failed() || async.result() == null) {
                        response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                    } else {
                        JsonObject msgBody = async.result().body();
                        JsonObject hits = msgBody.getJsonObject("hits");
                        if (hits == null) {
                            response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                            return;
                        }
                        int total = hits.getInteger("total");
                        switch (total) {
                        case 0:
                            response.setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end();
                            break;
                        case 1:
                            JsonObject hit = hits.getJsonArray("hits").getJsonObject(0);
                            String token = this.signer.sign(hit.getString("_id"), email);
                            String responseBody;
                            if (hit.containsKey("_source")) {
                                JsonObject source = hit.getJsonObject("_source");
                                source.put("jwt", token);
                                responseBody = source.encode();
                            } else {
                                responseBody = "{\"jwt\":\"" + token + "\"}";
                            }
                            response.setStatusCode(HttpResponseStatus.CREATED.code())
                                    .putHeader("content-type", "application/json").end(responseBody);
                            break;
                        default:
                            response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                        }
                    }

                });
    }

}