Example usage for io.vertx.core.http HttpServerRequest formAttributes

List of usage examples for io.vertx.core.http HttpServerRequest formAttributes

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerRequest formAttributes.

Prototype

@CacheReturn
MultiMap formAttributes();

Source Link

Document

Returns a map of all form attributes in the request.

Usage

From source file:de.braintags.netrelay.controller.authentication.FormLoginHandlerBt.java

License:Open Source License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {/*  ww w  .  ja v a 2 s  .c o m*/
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - did you forget to include a BodyHandler?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(usernameParam);
        String password = params.get(passwordParam);
        if (username == null || password == null) {
            LOGGER.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else {
            JsonObject authInfo = new JsonObject().put("username", username).put("password", password);
            authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    User user = res.result();
                    LOGGER.info("Login success, found user " + user);
                    MemberUtil.setContextUser(context, user);
                    if (redirectBySession(context)) {
                        return;
                    }
                    // Either no session or no return url
                    if (!redirectByDirectLoginUrl(context)) {
                        // Just show a basic page
                        req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
                    }
                } else {
                    LOGGER.info("authentication failed: " + res.cause());
                    handleAuthenticationError(context, res.cause());
                }
            });
        }
    }
}

From source file:de.braintags.netrelay.model.PasswordLostClaim.java

License:Open Source License

/**
 * @param email/*w w  w  .ja  v  a2 s . c  o m*/
 * @param password
 * @param request
 */
public PasswordLostClaim(String email, HttpServerRequest request) {
    this.email = email;
    transfer(request.formAttributes(), requestParameter);
    transfer(request.params(), requestParameter);
}

From source file:fr.wseduc.rack.controllers.RackController.java

License:Open Source License

/**
 * Post a new document to other people's rack folder.
 * @param request Client request containing a list of user ids belonging to the receivers and the file.
 *///from   w w  w. j a  v a 2s . c o  m
@Post("")
@SecuredAction(send)
public void postRack(final HttpServerRequest request) {
    UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
        @Override
        public void handle(final UserInfos userInfos) {

            if (userInfos == null) {
                badRequest(request);
                return;
            }

            request.setExpectMultipart(true);
            final Buffer fileBuffer = Buffer.buffer();
            final JsonObject metadata = new JsonObject();

            /* Upload file */
            request.uploadHandler(getUploadHandler(fileBuffer, metadata, request));

            /* After upload */
            request.endHandler(new Handler<Void>() {
                @Override
                public void handle(Void v) {
                    String users = request.formAttributes().get("users");
                    if (users == null) {
                        badRequest(request);
                        return;
                    }

                    String[] userIds = users.split(",");

                    final AtomicInteger countdown = new AtomicInteger(userIds.length);
                    final AtomicInteger success = new AtomicInteger(0);
                    final AtomicInteger failure = new AtomicInteger(0);

                    /* Final handler - called after each attempt */
                    final Handler<Boolean> finalHandler = new Handler<Boolean>() {
                        @Override
                        public void handle(Boolean event) {
                            if (event == null || !event)
                                failure.addAndGet(1);
                            else
                                success.addAndGet(1);
                            if (countdown.decrementAndGet() == 0) {
                                JsonObject result = new JsonObject();
                                result.put("success", success.get());
                                result.put("failure", failure.get());
                                renderJson(request, result);
                            }
                        }
                    };

                    for (final String to : userIds) {
                        /* Query user and check existence */
                        String query = "MATCH (n:User) " + "WHERE n.id = {id} "
                                + "RETURN count(n) as nb, n.displayName as username";
                        Map<String, Object> params = new HashMap<>();
                        params.put("id", to);

                        Handler<Message<JsonObject>> existenceHandler = new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> res) {
                                JsonArray result = res.body().getJsonArray("result");

                                if (!"ok".equals(res.body().getString("status")) || 1 != result.size()
                                        || 1 != result.getJsonObject(0).getInteger("nb")) {
                                    finalHandler.handle(false);
                                    return;
                                }

                                /* Pre write rack document fields */
                                final JsonObject doc = new JsonObject();
                                doc.put("to", to);
                                doc.put("toName", result.getJsonObject(0).getString("username"));
                                doc.put("from", userInfos.getUserId());
                                doc.put("fromName", userInfos.getUsername());
                                String now = dateFormat.format(new Date());
                                doc.put("sent", now);

                                /* Rack collection saving */
                                final Handler<JsonObject> rackSaveHandler = new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject uploaded) {
                                        if (uploaded == null || !"ok".equals(uploaded.getString("status"))) {
                                            finalHandler.handle(false);
                                        } else {
                                            addAfterUpload(uploaded.put("metadata", metadata), doc,
                                                    request.params().get("name"),
                                                    request.params().get("application"),
                                                    request.params().getAll("thumbnail"),
                                                    new Handler<Message<JsonObject>>() {
                                                        @Override
                                                        public void handle(Message<JsonObject> res) {
                                                            if ("ok".equals(res.body().getString("status"))) {
                                                                JsonObject params = new JsonObject()
                                                                        .put("uri",
                                                                                "/userbook/annuaire#"
                                                                                        + doc.getString("from"))
                                                                        .put("resourceUri", pathPrefix)
                                                                        .put("username",
                                                                                doc.getString("fromName"))
                                                                        .put("documentName",
                                                                                doc.getString("name"));
                                                                List<String> receivers = new ArrayList<>();
                                                                receivers.add(doc.getString("to"));

                                                                JsonObject pushNotif = new JsonObject()
                                                                        .put("title",
                                                                                "rack.push.notif.rack-post")
                                                                        .put("body",
                                                                                I18n.getInstance().translate(
                                                                                        "rack.push.notif.rack-post.body",
                                                                                        getHost(request),
                                                                                        I18n.acceptLanguage(
                                                                                                request),
                                                                                        doc.getString(
                                                                                                "fromName"),
                                                                                        doc.getString("name")));
                                                                params.put("pushNotif", pushNotif);

                                                                timelineHelper.notifyTimeline(request,
                                                                        "rack.rack-post", userInfos, receivers,
                                                                        userInfos.getUserId()
                                                                                + System.currentTimeMillis()
                                                                                + "postrack",
                                                                        null, params, true);
                                                                finalHandler.handle(true);
                                                            } else {
                                                                finalHandler.handle(false);
                                                            }
                                                        }
                                                    });
                                        }
                                    }
                                };

                                /* Get user quota & check */
                                getUserQuota(to, new Handler<JsonObject>() {
                                    @Override
                                    public void handle(JsonObject j) {
                                        if (j == null || "error".equals(j.getString("status"))) {
                                            finalHandler.handle(false);
                                            return;
                                        }

                                        long emptySize = 0l;
                                        long quota = j.getLong("quota", 0l);
                                        long storage = j.getLong("storage", 0l);
                                        emptySize = quota - storage;
                                        if (emptySize < metadata.getLong("size", 0l)) {
                                            finalHandler.handle(false);
                                            return;
                                        }
                                        //Save file
                                        RackController.this.storage.writeBuffer(fileBuffer,
                                                metadata.getString("content-type"), metadata.getString("name"),
                                                rackSaveHandler);
                                    }
                                });

                            }
                        };
                        Neo4j.getInstance().execute(query, params, existenceHandler);
                    }
                }
            });
        }
    });
}

From source file:io.advantageous.qbit.vertx.http.server.VertxServerUtils.java

License:Apache License

private void buildParams(final HttpRequestBuilder httpRequestBuilder, final HttpServerRequest request,
        final String contentType) {

    if (request.params().size() == 0) {
        httpRequestBuilder.setParams(MultiMap.empty());
    } else {//w w  w  . java  2  s. c  om
        httpRequestBuilder.setParams(new MultiMapWrapper(request.params()));
    }

    if (HttpContentTypes.isFormContentType(contentType)) {
        httpRequestBuilder.setFormParamsSupplier(() -> new MultiMapWrapper(request.formAttributes()));
    }

}

From source file:io.gravitee.am.gateway.handler.vertx.auth.handler.impl.FormLoginHandlerImpl.java

License:Apache License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest req = context.request();
    if (req.method() != HttpMethod.POST) {
        context.fail(405); // Must be a POST
    } else {/*from   w  w w  . j  a  va 2s . co m*/
        if (!req.isExpectMultipart()) {
            throw new IllegalStateException("Form body not parsed - do you forget to include a BodyHandler?");
        }
        MultiMap params = req.formAttributes();
        String username = params.get(usernameParam);
        String password = params.get(passwordParam);
        String clientId = params.get(OAuth2Constants.CLIENT_ID);
        if (username == null || password == null) {
            log.warn("No username or password provided in form - did you forget to include a BodyHandler?");
            context.fail(400);
        } else if (clientId == null) {
            log.warn("No client id in form - did you forget to include client_id query parameter ?");
            context.fail(400);
        } else {
            Session session = context.session();
            JsonObject authInfo = new JsonObject().put("username", username).put("password", password)
                    .put(OAuth2Constants.CLIENT_ID, clientId);
            authProvider.authenticate(authInfo, res -> {
                if (res.succeeded()) {
                    User user = res.result();
                    context.setUser(user);
                    if (session != null) {
                        // the user has upgraded from unauthenticated to authenticated
                        // session should be upgraded as recommended by owasp
                        session.regenerateId();

                        // Note : keep returnURLParam in session in case the user go to previous page
                        // String returnURL = session.remove(returnURLParam);
                        String returnURL = session.get(returnURLParam);
                        if (returnURL != null) {
                            // Now redirect back to the original url
                            doRedirect(req.response(), returnURL);
                            return;
                        }
                    }
                    // Either no session or no return url
                    if (directLoggedInOKURL != null) {
                        // Redirect to the default logged in OK page - this would occur
                        // if the user logged in directly at this URL without being redirected here first from another
                        // url
                        doRedirect(req.response(), directLoggedInOKURL);
                    } else {
                        // Just show a basic page
                        req.response().end(DEFAULT_DIRECT_LOGGED_IN_OK_PAGE);
                    }
                } else {
                    try {
                        Map<String, String> parameters = new HashMap<>();
                        parameters.put(OAuth2Constants.CLIENT_ID, clientId);
                        parameters.put("error", "login_failed");
                        String uri = UriBuilderRequest.resolveProxyRequest(
                                new io.vertx.reactivex.core.http.HttpServerRequest(req), req.uri(), parameters,
                                false, false);

                        doRedirect(context.response(), uri);
                    } catch (URISyntaxException e) {
                        context.fail(503);
                    }
                }
            });
        }
    }
}

From source file:io.servicecomb.transport.rest.vertx.RestBodyHandler.java

License:Apache License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest request = context.request();
    // we need to keep state since we can be called again on reroute
    Boolean handled = context.get(BODY_HANDLED);
    if (handled == null || !handled) {
        BHandler handler = new BHandler(context);
        request.handler(handler);/*from   w  ww  .j  ava2 s. c  om*/
        request.endHandler(v -> handler.end());
        context.put(BODY_HANDLED, true);
    } else {
        // on reroute we need to re-merge the form params if that was desired
        if (mergeFormAttributes && request.isExpectMultipart()) {
            request.params().addAll(request.formAttributes());
        }

        context.next();
    }
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@Post("/login")
public void loginSubmit(final HttpServerRequest request) {
    request.setExpectMultipart(true);/*www .ja v a2s  .  com*/
    request.endHandler(new io.vertx.core.Handler<Void>() {
        @Override
        public void handle(Void v) {
            String c = request.formAttributes().get("callBack");
            final StringBuilder callBack = new StringBuilder();
            if (c != null && !c.trim().isEmpty()) {
                try {
                    callBack.append(URLDecoder.decode(c, "UTF-8"));
                } catch (UnsupportedEncodingException ex) {
                    log.error(ex.getMessage(), ex);
                    callBack.append(config.getJsonObject("authenticationServer").getString("loginCallback"));
                }
            } else {
                callBack.append(config.getJsonObject("authenticationServer").getString("loginCallback"));
            }
            DataHandler data = oauthDataFactory.create(new HttpServerRequestAdapter(request));
            final String login = request.formAttributes().get("email");
            final String password = request.formAttributes().get("password");
            data.getUserId(login, password, new Handler<String>() {

                @Override
                public void handle(final String userId) {
                    final String c = callBack.toString();
                    if (userId != null && !userId.trim().isEmpty()) {
                        handleGetUserId(login, userId, request, c);
                    } else {
                        // try activation with login
                        userAuthAccount.matchActivationCode(login, password,
                                new io.vertx.core.Handler<Boolean>() {
                                    @Override
                                    public void handle(Boolean passIsActivationCode) {
                                        if (passIsActivationCode) {
                                            handleMatchActivationCode(login, password, request);
                                        } else {
                                            // try activation with loginAlias
                                            userAuthAccount.matchActivationCodeByLoginAlias(login, password,
                                                    new io.vertx.core.Handler<Boolean>() {
                                                        @Override
                                                        public void handle(Boolean passIsActivationCode) {
                                                            if (passIsActivationCode) {
                                                                handleMatchActivationCode(login, password,
                                                                        request);
                                                            } else {
                                                                // try reset with login
                                                                userAuthAccount.matchResetCode(login, password,
                                                                        new io.vertx.core.Handler<Boolean>() {
                                                                            @Override
                                                                            public void handle(
                                                                                    Boolean passIsResetCode) {
                                                                                if (passIsResetCode) {
                                                                                    handleMatchResetCode(login,
                                                                                            password, request);
                                                                                } else {
                                                                                    // try reset with loginAlias
                                                                                    userAuthAccount
                                                                                            .matchResetCodeByLoginAlias(
                                                                                                    login,
                                                                                                    password,
                                                                                                    new io.vertx.core.Handler<Boolean>() {
                                                                                                        @Override
                                                                                                        public void handle(
                                                                                                                Boolean passIsResetCode) {
                                                                                                            if (passIsResetCode) {
                                                                                                                handleMatchResetCode(
                                                                                                                        login,
                                                                                                                        password,
                                                                                                                        request);
                                                                                                            } else {
                                                                                                                trace.info(
                                                                                                                        "Erreur de connexion pour l'utilisateur "
                                                                                                                                + login);
                                                                                                                loginResult(
                                                                                                                        request,
                                                                                                                        "auth.error.authenticationFailed",
                                                                                                                        c);
                                                                                                            }
                                                                                                        }
                                                                                                    });
                                                                                }
                                                                            }
                                                                        });
                                                            }
                                                        }
                                                    });
                                        }
                                    }
                                });

                    }
                }
            });

        }
    });
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

private void createSession(String userId, final HttpServerRequest request, final String callBack) {
    UserUtils.createSession(eb, userId, new io.vertx.core.Handler<String>() {

        @Override/*from   w  w w  . j  av  a2s .c  o  m*/
        public void handle(String sessionId) {
            if (sessionId != null && !sessionId.trim().isEmpty()) {
                boolean rememberMe = "true".equals(request.formAttributes().get("rememberMe"));
                long timeout = rememberMe ? 3600l * 24 * 365 : config.getLong("cookie_timeout", Long.MIN_VALUE);
                CookieHelper.getInstance().setSigned("oneSessionId", sessionId, timeout, request);
                CookieHelper.set("authenticated", "true", timeout, request);
                redirect(request,
                        callBack.matches("https?://[0-9a-zA-Z\\.\\-_]+/auth/login/?(\\?.*)?")
                                ? callBack.replaceFirst("/auth/login", "")
                                : callBack,
                        "");
            } else {
                loginResult(request, "auth.error.authenticationFailed", callBack);
            }
        }
    });
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@Post("/activation")
public void activeAccountSubmit(final HttpServerRequest request) {
    request.setExpectMultipart(true);/*from  w  w w .j  av  a 2  s .c om*/
    request.endHandler(new io.vertx.core.Handler<Void>() {

        @Override
        public void handle(Void v) {
            final String login = request.formAttributes().get("login");
            final String activationCode = request.formAttributes().get("activationCode");
            final String email = request.formAttributes().get("mail");
            final String phone = request.formAttributes().get("phone");
            final String theme = request.formAttributes().get("theme");
            String password = request.formAttributes().get("password");
            String confirmPassword = request.formAttributes().get("confirmPassword");
            if (config.getBoolean("cgu", true) && !"true".equals(request.formAttributes().get("acceptCGU"))) {
                trace.info("Invalid cgu " + login);
                JsonObject error = new JsonObject().put("error", new JsonObject().put("message", "invalid.cgu"))
                        .put("cgu", true);
                if (activationCode != null) {
                    error.put("activationCode", activationCode);
                }
                if (login != null) {
                    error.put("login", login);
                }
                renderJson(request, error);
            } else if (login == null || activationCode == null || password == null || login.trim().isEmpty()
                    || activationCode.trim().isEmpty() || password.trim().isEmpty()
                    || !password.equals(confirmPassword) || !passwordPattern.matcher(password).matches()
                    || (config.getJsonObject("mandatory", new JsonObject()).getBoolean("mail", false)
                            && (email == null || email.trim().isEmpty() || invalidEmails.containsKey(email)))
                    || (config.getJsonObject("mandatory", new JsonObject()).getBoolean("phone", false)
                            && (phone == null || phone.trim().isEmpty()))
                    || (email != null && !email.trim().isEmpty() && !StringValidation.isEmail(email))
                    || (phone != null && !phone.trim().isEmpty() && !StringValidation.isPhone(phone))) {
                trace.info("Echec de l'activation du compte utilisateur " + login);
                JsonObject error = new JsonObject().put("error",
                        new JsonObject().put("message",
                                I18n.getInstance().translate("auth.activation.invalid.argument",
                                        getHost(request), I18n.acceptLanguage(request))));
                if (activationCode != null) {
                    error.put("activationCode", activationCode);
                }
                if (login != null) {
                    error.put("login", login);
                }
                if (config.getBoolean("cgu", true)) {
                    error.put("cgu", true);
                }
                renderJson(request, error);
            } else {
                userAuthAccount.activateAccount(login, activationCode, password, email, phone, theme, request,
                        new io.vertx.core.Handler<Either<String, String>>() {

                            @Override
                            public void handle(Either<String, String> activated) {
                                if (activated.isRight() && activated.right().getValue() != null) {
                                    handleActivation(login, request, activated);
                                } else {
                                    // if failed because duplicated user
                                    if (activated.isLeft() && "activation.error.duplicated"
                                            .equals(activated.left().getValue())) {
                                        trace.info("Echec de l'activation : utilisateur " + login
                                                + " en doublon.");
                                        JsonObject error = new JsonObject().put("error",
                                                new JsonObject().put("message",
                                                        I18n.getInstance().translate(
                                                                activated.left().getValue(), getHost(request),
                                                                I18n.acceptLanguage(request))));
                                        error.put("activationCode", activationCode);
                                        renderJson(request, error);
                                    } else {
                                        // else try activation with loginAlias
                                        userAuthAccount.activateAccountByLoginAlias(login, activationCode,
                                                password, email, phone, theme, request,
                                                new io.vertx.core.Handler<Either<String, String>>() {
                                                    @Override
                                                    public void handle(Either<String, String> activated) {
                                                        if (activated.isRight()
                                                                && activated.right().getValue() != null) {
                                                            handleActivation(login, request, activated);
                                                        } else {
                                                            trace.info(
                                                                    "Echec de l'activation : compte utilisateur "
                                                                            + login
                                                                            + " introuvable ou dj activ.");
                                                            JsonObject error = new JsonObject().put("error",
                                                                    new JsonObject().put("message",
                                                                            I18n.getInstance().translate(
                                                                                    activated.left().getValue(),
                                                                                    getHost(request),
                                                                                    I18n.acceptLanguage(
                                                                                            request))));
                                                            error.put("activationCode", activationCode);
                                                            renderJson(request, error);
                                                        }
                                                    }
                                                });
                                    }
                                }
                            }
                        });
            }
        }
    });
}

From source file:org.entcore.auth.controllers.AuthController.java

License:Open Source License

@Post("/sendResetPassword")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@IgnoreCsrf/*from w w w  .j  a va 2  s .c  om*/
public void sendResetPassword(final HttpServerRequest request) {
    String login = request.formAttributes().get("login");
    String email = request.formAttributes().get("email");
    String mobile = request.formAttributes().get("mobile");
    SendPasswordDestination dest = null;

    if (login == null || login.trim().isEmpty()) {
        badRequest(request, "login required");
        return;
    }
    if (StringValidation.isEmail(email)) {
        dest = new SendPasswordDestination();
        dest.setType("email");
        dest.setValue(email);
    } else if (StringValidation.isPhone(mobile)) {
        dest = new SendPasswordDestination();
        dest.setType("mobile");
        dest.setValue(mobile);
    } else {
        badRequest(request, "valid email or valid mobile required");
        return;
    }

    userAuthAccount.sendResetCode(request, login, dest, checkFederatedLogin,
            new io.vertx.core.Handler<Boolean>() {
                @Override
                public void handle(Boolean sent) {
                    if (Boolean.TRUE.equals(sent)) {
                        renderJson(request, new JsonObject());
                    } else {
                        badRequest(request);
                    }
                }
            });
}