예제 #1
0
  // src: 1 = viewAdvertisements
  // src: 2 = viewMyOwnAdvertisements
  @Security.Authenticated(Secured.class)
  public static Result changeStudAdvertisementForm(Long adId, Long src) {

    Form<StudentAdvertisementForm> adForm =
        Form.form(StudentAdvertisementForm.class).bindFromRequest();
    String description = adForm.get().description;
    String studies = adForm.get().studies;
    boolean testAd = adForm.get().test;

    StudentAdvertisement.create(
        Student.find.byId(request().username()), studies, description, adId, testAd);

    if (adForm.hasErrors()) {
      return badRequest(
          changeStudentAdvertisement.render(
              Student.find.byId(request().username()), adForm, null, src));
    } else {
      if (src == 1) {
        return ok(
            viewAdvertisements.render(
                Student.find.byId(request().username()),
                StudentAdvertisement.find.all(),
                TutorAdvertisement.find.all()));
      } else {
        return ok(
            viewOwnAdvertisements.render(
                Student.find.byId(request().username()),
                StudentAdvertisement.find.all(),
                TutorAdvertisement.find.all()));
      }
    }
  }
예제 #2
0
  @Security.Authenticated(Secured.class)
  public static Result newUser() {
    User user = getCurrentUser();
    if (!user.isAdmin) return redirect(routes.Application.contacts());
    Form<User> filledForm = userForm.bindFromRequest();

    if (!filledForm.field("password").valueOr("").isEmpty()) {
      if (!filledForm
          .field("password")
          .valueOr("")
          .equals(filledForm.field("repeatPassword").value())) {
        filledForm.reject("repeatPassword", "Passwörter stimmen nicht überein");
      }
    }

    if (!filledForm.hasErrors()) {
      if (userAlreadyExists(filledForm.get().email)) {
        filledForm.reject("email", "Diese Emailadresse ist bereits vergeben");
      }
    }

    if (filledForm.hasErrors()) {
      flash("error", "Bitte korrigieren sie ihre Eingaben!");
      return badRequest(views.html.addUser.render(filledForm, getCurrentUser(), User.find.all()));
    } else {
      User.create(filledForm.get());
      flash("success", "Benutzer " + filledForm.get().email + " erstellt.");
      return redirect(routes.Application.contacts());
    }
  }
예제 #3
0
  /** Handle the 'new quantity form' submission */
  public static Result save() {
    Form<Quantity> form = form(Quantity.class).bindFromRequest();
    form.get().save();

    flash("success", "quantity  has been created");
    return list(0, "name", "asc", "", form.get().getProfileId());
  }
예제 #4
0
파일: Feed.java 프로젝트: virgilio/mupi-dev
  @Dynamic("editor")
  public static Result publish() {
    Form<utils.Forms.PublicationBinder> bindedForm =
        form(utils.Forms.PublicationBinder.class).bindFromRequest();

    Long l = bindedForm.get().location;
    Long i = bindedForm.get().interest;

    if (i != null && l != null) {
      final User u = Mupi.getLocalUser(session());
      final models.Profile p = u.profile;

      String safeBody =
          Jsoup.clean(
              bindedForm.get().body,
              Whitelist.basicWithImages()
                  .addEnforcedAttribute("a", "target", "_blank")
                  .addTags("h1", "h2"));

      Publication.create(
          p,
          models.Location.find.byId(l),
          models.Interest.find.byId(i),
          PubType.get(bindedForm.get().pub_typ),
          safeBody);
    }
    return selectFeed(getLocalInterest(), getLocalLocation());
  }
예제 #5
0
 public static Result authenticate() {
   Form<Login> loginForm = Form.form(Login.class).bindFromRequest();
   if (loginForm.hasErrors()) {
     return badRequest(views.html.login.render(loginForm, getCurrentUser()));
   } else {
     session().clear();
     session("email", loginForm.get().email);
     flash("success", "Sie haben sich erfolgreich eingeloggt als: " + loginForm.get().email);
     return redirect(routes.Application.contacts());
   }
 }
예제 #6
0
  /**
   * Handle the 'edit form' submission
   *
   * @param id Id of the quantity to edit
   */
  public static Result update(Long id) {
    Form<Quantity> form = form(Quantity.class).bindFromRequest();

    if (form.hasErrors()) {
      System.out.println(form.errorsAsJson());
      return badRequest(editForm.render(id, form));
    }
    form.get().update(id);
    flash("success", "Quantity has been updated");
    return list(0, "name", "asc", "", form.get().getProfileId());
  }
  public Result doResetPassword() {
    com.feth.play.module.pa.controllers.AuthenticateDI.noCache(this.session.response());
    final Form<ModelAuth.PasswordReset> filledForm = getResetPasswordForm().bindFromRequest();
    if (filledForm.hasErrors()) {

      boolean disableIndexing = false;
      ContentInner contentInner = renderResetPasswordView(filledForm);

      return Results.badRequest(this.onRenderListener.onRender(contentInner, disableIndexing));
    } else {
      final String token = filledForm.get().token;
      final String newPassword = filledForm.get().password;

      final EntryTokenAction tokenAction =
          Auth.isTokenValid(token, EntryTokenAction.Type.PASSWORD_RESET);
      if (tokenAction == null) {

        ContentInner contentInner =
            new PageAuthAccount(this.session, this.onRenderListener).renderNoTokenOrInvalidView();
        boolean disableIndexing = false;

        return Results.badRequest(this.onRenderListener.onRender(contentInner, disableIndexing));
      }
      final EntryUser user = tokenAction.targetUser;
      try {
        // Pass true for the second parameter if you want to
        // automatically create a password and the exception never to
        // happen
        user.resetPassword(new ProviderUsernamePasswordAuthUser(newPassword), false);
      } catch (final RuntimeException re) {
        this.session.flash(
            Auth.FLASH_MESSAGE_KEY,
            Messages.get("playauthenticate.reset_password.message.no_password_account"));
      }
      final boolean login = ProviderUsernamePasswordAuth.getProvider().isLoginAfterPasswordReset();
      if (login) {
        // automatically log in
        this.session.flash(
            Auth.FLASH_MESSAGE_KEY,
            Messages.get("playauthenticate.reset_password.message.success.auto_login"));

        return PlayAuthenticate.loginAndRedirect(
            this.session.ctx(), new ProviderLoginUsernamePasswordAuthUser(user.email));
      } else {
        // send the user to the login page
        this.session.flash(
            Auth.FLASH_MESSAGE_KEY,
            Messages.get("playauthenticate.reset_password.message.success.manual_login"));
      }
      return this.onRenderListener.redirectToLogin();
    }
  }
예제 #8
0
  /**
   * Validates fields from the registration form and either creates a new user or communicates any
   * validation errors.
   */
  public static Result submit() {
    Form<User> filledForm = signupForm.bindFromRequest();

    // Check accept conditions
    if (!"true".equals(filledForm.field("accept").value())) {
      filledForm.reject("accept", "You must accept the terms and conditions");
    }

    // Check repeated password
    if (!filledForm.field("password").valueOr("").isEmpty()) {
      if (!filledForm
          .field("password")
          .valueOr("")
          .equals(filledForm.field("repeatPassword").value())) {
        filledForm.reject("repeatPassword", "Passwords do not match");
      }
    }

    // Check if the username and email are valid
    if (!filledForm.hasErrors()) {

      String un = filledForm.get().username;
      String email = filledForm.get().email;

      if (un.equals("admin") || un.equals("guest")) {
        filledForm.reject("username", "This username is already taken");
      }

      try {
        Logger.debug("Finding user " + email);
        User.findByEmail(email);
        filledForm.reject(
            "email", "There is already an account associated with this email address.");
      } catch (Exception e) {
        // continue - the user does not exist
      }
    }

    // Return validation results to user or save user
    if (filledForm.hasErrors()) {
      return badRequest(form.render(filledForm));
    } else {
      User user = filledForm.get(); /* create an object from a form */
      User svUser =
          new User(user.username, user.email, user.password); /* recreate to get save group info */
      svUser.save();
      return ok(summary.render(svUser));
    }
  }
예제 #9
0
  @AccessLevel(level = 2)
  public Result create() {
    Form<ActivityChoice> choiceForm = Form.form(ActivityChoice.class).bindFromRequest();

    if (choiceForm.hasErrors()) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_FORM_HASERROR, Messages.get("activitychoice.failure"));
    }

    try {
      ActivityChoice choice = choiceForm.get();

      choice.id = CodeGenerator.GenerateUUId();

      choice.content = new ActivityContent();
      choice.content.id = choice.id;

      Ebean.save(choice);

      return ok(Json.toJson(choice));
    } catch (Throwable e) {
      return status(
          ErrDefinition.E_ACTIVITY_CHOICE_CREATE_FAILED, Messages.get("activitychoice.failure"));
    }
  }
예제 #10
0
  public static Result submit() {
    District dis = District.find.byId(1L);

    if (dis == null) {
      return redirect("/setup");
    }

    Form<LoginForm> mForm = Form.form(LoginForm.class).bindFromRequest();

    if (mForm.hasErrors())
      return badRequest(
          views.html.login.render(
              "Please enter the username and password provided by your school", dis, mForm));

    LoginForm lForm = mForm.get();

    // TODO: Hash passwords

    List<LoginUser> lookingFor =
        LoginUser.finder
            .where()
            .eq("USER_NAME", lForm.username)
            .eq("PASS_HASH", lForm.password)
            .findList();

    if (lookingFor.size() != 1)
      return badRequest(
          views.html.login.render(
              "Please enter the username and password provided by your school", dis, mForm));

    return ok(views.html.login.render("Logged in!", dis, Form.form(LoginForm.class)));
  }
  /** Process the form to create a new custom and external KPI. */
  public Result processCreate() {

    // bind the form
    Form<CustomExternalKpiFormData> boundForm = customExternalKpiFormTemplate.bindFromRequest();

    // get the object type
    String objectType = boundForm.data().get("objectType");

    if (boundForm.hasErrors()) {
      return ok(views.html.admin.kpi.create.render(objectType, boundForm));
    }

    CustomExternalKpiFormData customExternalKpiFormData = boundForm.get();

    KpiDefinition kpiDefinition = customExternalKpiFormData.constructKpiDefinition();

    kpiDefinition.mainKpiValueDefinition.save();
    kpiDefinition.additional1KpiValueDefinition.save();
    kpiDefinition.additional2KpiValueDefinition.save();
    kpiDefinition.save();

    customExternalKpiFormData.mainName.persist(getI18nMessagesPlugin());
    customExternalKpiFormData.additional1Name.persist(getI18nMessagesPlugin());
    customExternalKpiFormData.additional2Name.persist(getI18nMessagesPlugin());

    reloadKpiDefinition(kpiDefinition.uid);

    Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.create.successful"));

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }
  /** Process the edit form of the scheduler of a KPI definition. */
  public Result saveScheduler() {

    // bind the form
    Form<KpiSchedulerFormData> boundForm = kpiSchedulerFormTemplate.bindFromRequest();

    // get the KPI
    Long kpiDefinitionId = Long.valueOf(boundForm.data().get("id"));
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiDefinitionId);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    if (boundForm.hasErrors()) {
      return ok(views.html.admin.kpi.editScheduler.render(kpiDefinition, kpi, boundForm));
    }

    KpiSchedulerFormData kpiSchedulerFormData = boundForm.get();

    kpiSchedulerFormData.fill(kpiDefinition);
    kpiDefinition.update();

    reloadKpiDefinition(kpiDefinition.uid);

    Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.editscheduler.successful"));

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }
예제 #13
0
파일: Feed.java 프로젝트: virgilio/mupi-dev
  @Dynamic("editor")
  public static Result hostMeetUp() {
    final Form<utils.Forms.MeetUpHosting> filledForm = HOST_MEETUP_FORM.bindFromRequest();
    final User u = Mupi.getLocalUser(session());
    final models.Profile p = u.getProfile();
    String lastName = p.getLastName();
    if (lastName == null) lastName = "";
    String interest = "--desconhecido--";
    String location = "--desconhecida--";

    if (getLocalInterest() != null && getLocalInterest() != -1)
      interest = models.Interest.find.byId(getLocalInterest()).getName();

    if (getLocalLocation() != null && getLocalLocation() != -1)
      location = models.Location.find.byId(getLocalLocation()).getName();

    final String subject =
        "[EventoMupi][Local] "
            + p.getFirstName()
            + " "
            + lastName
            + " quer receber encontros amiguinhos!  Yayyy!!";

    final String body =
        "O usuário "
            + p.getFirstName()
            + " "
            + lastName
            + " ("
            + u.email
            + ") "
            + "quer receber encontros da seguinte comunidade:\n"
            + "\n    Localidade - "
            + location
            + "\n    Interesse - "
            + interest
            + "\n\n Ele redigiu a seguinte descrição:\n"
            + filledForm.get().description;
    final String from = "*****@*****.**";
    final String to = MupiParams.HOST_MEETUP_EMAIL;
    final String replyTo = "*****@*****.**";

    new AssyncEmailSender(subject, body, from, replyTo, to).send();

    final String userSubject = "Receber Evento Mupi";
    final String userBody =
        "Olá "
            + p.getFirstName()
            + ",\n\n"
            + "Recebemos sua mensagem sobre o interesse em receber Eventos Mupi. Em breve entraremos em contato para os próximos passos.\n\n\n"
            + "Atenciosamente,\n"
            + "Equipe Mupi";
    final String userFrom = "*****@*****.**";
    final String userTo = u.email;
    final String userReplyTo = "*****@*****.**";

    new AssyncEmailSender(userSubject, userBody, userFrom, userReplyTo, userTo).send();

    return redirect(routes.Feed.feed());
  }
  /**
   * Returns the player profile page with the submitted info.
   *
   * @return The player profile page, which was just created/edited
   */
  @Security.Authenticated(Secured.class)
  public static Result playerManageSubmit() {
    // adds the new player from the PlayerForm page to the database.
    Form<PlayerFormData> data = Form.form(PlayerFormData.class).bindFromRequest();

    SearchFormData data2 = new SearchFormData();
    Form<SearchFormData> dataForm = Form.form(SearchFormData.class).fill(data2);
    Page<Player> playerPage = Player.find("name asc", 0);
    User user = Secured.getUserInfo(ctx());

    if (data.hasErrors()) {
      Map<String, Boolean> playerSkillMap = PlayerFields.getSkill();
      Map<String, Boolean> playerPosition = PlayerFields.getPosition();
      return badRequest(
          PlayerForm.render(
              "Bad Player Form", data, playerSkillMap, playerPosition, Secured.isLoggedIn(ctx())));
    } else {
      PlayerFormData formData = data.get();
      if (Player.getPlayer(user.getId()) == null) {
        // Player.addPlayer(formData);
      } else {
        Player.updatePlayer(formData, user.getId());
      }

      return ok(
          PlayerList.render(
              playerPage,
              "PlayerList",
              dataForm,
              "none",
              "none",
              Secured.isLoggedIn(ctx()),
              Secured.getUserInfo(ctx())));
    }
  }
예제 #15
0
  /**
   * This handles the login form submission for the Web IDE.
   *
   * @return The result of rendering the page.
   */
  @AddCSRFToken
  @RequireCSRFCheck
  @Transactional
  public CompletionStage<Result> login() {
    Form<LoginForm> userForm = myFormFactory.form(LoginForm.class).bindFromRequest();

    // Perform the basic validation checks.
    if (userForm.hasErrors()) {
      // Render the page with the login form with the errors fields
      String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
      return CompletableFuture.supplyAsync(
          () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
    } else {
      LoginForm form = userForm.get();

      // Check for a registered user with the same email.
      // Note that "connect" expects a JPA entity manager,
      // which is not present if we don't wrap the call using
      // "withTransaction()".
      User user = myJpaApi.withTransaction(() -> User.connect(form.getEmail(), form.getPassword()));
      if (user != null) {
        // Check to see if this account has been authenticated or not.
        boolean hasAuthenticated =
            myJpaApi.withTransaction(() -> User.hasAuthenticated(form.getEmail()));
        if (hasAuthenticated) {
          // Update the login date
          final User updatedUser = myJpaApi.withTransaction(() -> User.lastLogin(form.getEmail()));

          // Add a new user event
          myJpaApi.withTransaction(() -> UserEvent.addRegularEvent("login", "", updatedUser));

          // Stores the email as session value
          session("connected", form.getEmail());

          // Obtain the http context from the configuration file
          String context = myConfiguration.getString("play.http.context");
          if (context == null) {
            context = "";
          }

          // Redirect back to the home page
          final String finalContext = context;
          return CompletableFuture.supplyAsync(
              () -> redirect(finalContext + "/"), myHttpExecutionContext.current());
        } else {
          // Render the not authenticated page
          return CompletableFuture.supplyAsync(
              () -> ok(notAuthenticated.render(form.getEmail())), myHttpExecutionContext.current());
        }
      } else {
        // The email and/or password does not match, so we add a new validation error.
        userForm.reject(new ValidationError("loginError", "Could not login."));

        // Render the page with the login form with the errors fields
        String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token");
        return CompletableFuture.supplyAsync(
            () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current());
      }
    }
  }
  public static Result detallesRecorridos() {

    RecorridoDAO recorridoDAO = new RecorridoDAO();
    // ojo ajustar
    List<Recorrido> lstRecorridos = recorridoDAO.listarRecorridos();

    Form<FormularioConsultaRecorrido> form =
        Form.form(FormularioConsultaRecorrido.class).bindFromRequest();

    if (form.hasErrors()) {
      flash("error", "Se encontraron errores al consultar el recorrido.");
      return badRequest(
          views.html.recorridosConsulta.render(
              Form.form(FormularioConsultaRecorrido.class), lstRecorridos, null, null));

    } else {
      FormularioConsultaRecorrido formularioConsultaRecorrido = form.get();

      Recorrido recorrido =
          recorridoDAO.consultarRecorridoPorId(formularioConsultaRecorrido.idRecorrido);
      FormularioRecorrido formRecorrido = new FormularioRecorrido();
      formRecorrido.tipoRecorrido = String.valueOf(recorrido.getTipo());
      formRecorrido.nombre = recorrido.getNombre();
      formRecorrido.descripcion = recorrido.getDescripcion();
      formRecorrido.horaFrecuente = recorrido.getHoraFrecuente();

      String diasFrecuentes = recorrido.getDiaFrecuente();
      formRecorrido.diaFrecuente = new ArrayList<String>();
      if (diasFrecuentes != null) {
        String[] arrDias = diasFrecuentes.split(",");
        for (int i = 0; i < arrDias.length; i++) {
          formRecorrido.diaFrecuente.add(arrDias[i]);
        }
      }

      formRecorrido.fechaInicioRuta =
          String.valueOf(recorrido.getLstRuta().get(0).getFechaInicioRuta());
      formRecorrido.fechaFinRuta = String.valueOf(recorrido.getLstRuta().get(0).getFechaFinRuta());
      formRecorrido.latitudInicio =
          String.valueOf(recorrido.getLstRuta().get(0).getLatitudInicio());
      formRecorrido.longitudInicio =
          String.valueOf(recorrido.getLstRuta().get(0).getLongitudInicio());
      formRecorrido.latitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLatitudFin());
      formRecorrido.longitudFin = String.valueOf(recorrido.getLstRuta().get(0).getLongitudFin());
      formRecorrido.lugarInicio = recorrido.getLstRuta().get(0).getLugarInicio();
      formRecorrido.lugarFin = recorrido.getLstRuta().get(0).getLugarFin();
      formRecorrido.lstAmigos = new ArrayList<String>();

      Boolean existe = false;
      User usuario = Application.getLocalUser(session());
      for (UsuarioXRecorrido usuarioRecorrido : recorrido.getLstUsuarioXRecorrido()) {
        formRecorrido.lstAmigos.add(usuarioRecorrido.getUsuario().name);
        if (usuario.id == usuarioRecorrido.getUsuario().id) existe = true;
      }

      formRecorrido.idRecorrido = recorrido.getIdRecorrido();

      return ok(views.html.recorridosDetalle.render(formRecorrido, existe));
    }
  }
예제 #17
0
  /**
   * Responds to a request to add an issue label category for the specified project.
   *
   * <p>Adds an issue label category created with values taken from {@link
   * Form#bindFromRequest(java.util.Map, String...)} in the project specified by the {@code
   * ownerName} and {@code projectName}. But if there has already been the same issue label category
   * in name, then this method returns an empty 204 No Content response.
   *
   * <p>When a new category is added, this method encodes the category's fields: {@link
   * IssueLabelCategory#id}, {@link IssueLabelCategory#name}, {@link
   * IssueLabelCategory#isExclusive}, and includes them in the body of the 201 Created response. But
   * if the client cannot accept {@code application/json}, it returns the 201 Created with no
   * response body.
   *
   * @param ownerName the name of a project owner
   * @param projectName the name of a project
   * @return the response to the request to add a new issue label category
   */
  @IsCreatable(ResourceType.ISSUE_LABEL_CATEGORY)
  public static Result newCategory(String ownerName, String projectName) {
    Form<IssueLabelCategory> form = new Form<>(IssueLabelCategory.class).bindFromRequest();

    if (form.hasErrors()) {
      return badRequest();
    }

    IssueLabelCategory category = form.get();

    category.project = Project.findByOwnerAndProjectName(ownerName, projectName);

    if (category.exists()) {
      return noContent();
    }

    category.save();

    if (!request().accepts("application/json")) {
      return created();
    }

    Map<String, String> categoryPropertyMap = new HashMap<>();
    categoryPropertyMap.put("id", "" + category.id);
    categoryPropertyMap.put("name", category.name);
    categoryPropertyMap.put("isExclusive", "" + category.isExclusive);

    return created(toJson(categoryPropertyMap)).as("application/json");
  }
예제 #18
0
  @Authenticated(value = {LoggedIn.class, HasRole.class})
  @Authorized(value = "admin")
  @Transactional
  @RequireCSRFCheck
  public Result postCreateArchive() {
    Form<ArchiveUpsertForm> archiveUpsertForm =
        Form.form(ArchiveUpsertForm.class).bindFromRequest();

    if (formHasErrors(archiveUpsertForm)) {
      return showCreateArchive(0, archiveUpsertForm);
    }

    ArchiveUpsertForm archiveUpsertData = archiveUpsertForm.get();
    if (!archiveUpsertData.parentJid.isEmpty()
        && !archiveService.archiveExistsByJid(archiveUpsertData.parentJid)) {
      archiveUpsertForm.reject(Messages.get("error.archive.notExist"));

      return showCreateArchive(0, archiveUpsertForm);
    }

    long archiveId =
        archiveService.createArchive(
            archiveUpsertData.parentJid,
            archiveUpsertData.name,
            archiveUpsertData.description,
            IdentityUtils.getUserJid(),
            IdentityUtils.getIpAddress());

    return redirect(routes.ArchiveController.viewArchives(archiveId));
  }
예제 #19
0
  public Result sendMail() {
    final Form<MailMe> filledForm = FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      return badRequest(index.render(filledForm));
    } else {
      final String email = filledForm.get().email;
      final Body body =
          new Body(
              views.txt.email.body.render().toString(), views.html.email.body.render().toString());

      {
        // simple usage
        defaultMailer.sendMail("play-easymail | it works!", body, email);
      }

      {
        // advanced usage
        final Mail customMail = new Mail("play-easymail | advanced", body, new String[] {email});
        customMail.addHeader("Reply-To", email);
        customMail.addAttachment("attachment.pdf", env.getFile("conf/sample.pdf"));
        byte[] data = "data".getBytes();
        customMail.addAttachment(
            "data.txt", data, "text/plain", "A simple file", EmailAttachment.INLINE);
        defaultMailer.sendMail(customMail);
      }

      flash("message", "2 mails to '" + email + "' have been sent successfully!");
      return redirect(routes.HomeController.index());
    }
  }
예제 #20
0
파일: UserApp.java 프로젝트: bluemir/hive
  /**
   * 사용자 비밀번호 변경 비밀번호 변경에 성공하면 로그인 화면으로 이동 비밀번호 변경에 실패하면 수정화면으로 돌아간다
   *
   * @return
   */
  @Transactional
  public static Result resetUserPassword() {
    Form<User> userForm = form(User.class).bindFromRequest();

    if (userForm.hasErrors()) {
      return badRequest(ErrorViews.BadRequest.render("error.badrequest"));
    }

    User currentUser = currentUser();
    User user = userForm.get();

    if (!isValidPassword(currentUser, user.oldPassword)) {
      Form<User> currentUserForm = new Form<>(User.class);
      currentUserForm = currentUserForm.fill(currentUser);

      flash(Constants.WARNING, "user.wrongPassword.alert");
      return badRequest(edit.render(currentUserForm, currentUser));
    }

    resetPassword(currentUser, user.password);

    // go to login page
    processLogout();
    flash(Constants.WARNING, "user.loginWithNewPassword");
    return redirect(routes.UserApp.loginForm());
  }
예제 #21
0
  @SubjectPresent
  public Result doMerge() {
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    // this is the currently logged in user
    final AuthUser aUser = PlayAuthenticate.getUser(session());

    // this is the user that was selected for a login
    final AuthUser bUser = PlayAuthenticate.getMergeUser(session());
    if (bUser == null) {
      // user to merge with could not be found, silently redirect to login
      return redirect(routes.Application.index());
    }

    final Form<Accept> filledForm = ACCEPT_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not select whether to merge or not merge
      return badRequest((Content) ask_merge.render("Merge Form"));
    } else {
      // User made a choice :)
      final boolean merge = filledForm.get().accept;
      if (merge) {
        flash(
            Application.FLASH_MESSAGE_KEY, Messages.get("playauthenticate.accounts.merge.success"));
      }
      return PlayAuthenticate.merge(ctx(), merge);
    }
  }
예제 #22
0
파일: CEconomia.java 프로젝트: urkh/lg
  public static Result guardar() {

    Form<Economia> formREconomia = form(Economia.class).bindFromRequest();
    formREconomia.get().save();
    flash("exito", "Solicitud registrada exitosamente!");
    return Inicio;
  }
  /** Send a notification message. */
  public Result sendMessage() {

    try {
      Form<NotificationMessage> boundForm = notificationMessageForm.bindFromRequest();
      if (boundForm.hasErrors()) {

        String loggedUser = getUserSessionManagerPlugin().getUserSessionId(ctx());

        List<MessageListView> messageListViewRows = new ArrayList<>();
        List<Notification> notifications =
            getNotificationManagerPlugin().getMessagesForUid(loggedUser);
        for (Notification notification : notifications) {
          messageListViewRows.add(
              new MessageListView(this.getAccountManagerPlugin(), notification));
        }
        Table<MessageListView> messagesTables =
            this.getTableProvider().get().message.templateTable.fill(messageListViewRows);

        return ok(views.html.messaging.index.render(messagesTables, boundForm));
      }
      NotificationMessage notificationMessage = boundForm.get();
      getNotificationManagerPlugin()
          .sendMessage(
              getUserSessionManagerPlugin().getUserSessionId(ctx()),
              notificationMessage.principalUids,
              notificationMessage.title,
              notificationMessage.message);
      Utilities.sendSuccessFlashMessage(
          getI18nMessagesPlugin().get("messaging.send.success", notificationMessage.title));
      return redirect(routes.MessagingController.index());
    } catch (Exception e) {
      return ControllersUtils.logAndReturnUnexpectedError(
          e, log, getConfiguration(), getI18nMessagesPlugin());
    }
  }
  /** Save the capacity. */
  @With(CheckActorExists.class)
  @Dynamic(IMafConstants.ACTOR_EDIT_DYNAMIC_PERMISSION)
  public Result saveCapacity() {

    // bind the form
    Form<ActorCapacityFormData> boundForm = capacityFormTemplate.bindFromRequest();

    // get the actor
    Long id = Long.valueOf(boundForm.data().get("id"));
    Actor actor = ActorDao.getActorById(id);

    // get the year
    Integer year = Integer.valueOf(boundForm.data().get("year"));

    if (boundForm.hasErrors()) {
      return ok(views.html.core.actor.actor_capacity.render(actor, year, boundForm, true));
    }

    ActorCapacityFormData capacityFormData = boundForm.get();

    for (ActorCapacity capacity : capacityFormData.getFilledCapacities()) {
      capacity.save();
    }

    Utilities.sendSuccessFlashMessage(Msg.get("core.actor.capacity.save.successful"));

    return redirect(
        controllers.core.routes.ActorController.capacity(
            capacityFormData.id, capacityFormData.year));
  }
예제 #25
0
  public Result create() {
    Form<Profit> form = Form.form(Profit.class).bindFromRequest();

    if (form.hasErrors()) {
      return badRequest(form.errorsAsJson());
    }

    Profit profit = form.get();

    if (Profit.existsProfitWithId(profit.getIdProfit())) {
      return Results.status(409, "already exists");
    }

    Integer idAdvisedUser = RequestUtils.getIntegerFromBody(request(), "idAdvisedUser");

    if (idAdvisedUser == null) {
      return badRequest("You need to add the id of the adviseduser");
    }

    AdvisedUser advisedUser = AdvisedUser.findAdvisedUserWithId(idAdvisedUser);

    if (advisedUser == null) {
      return Results.status(409, "there is no adviseduser with this id");
    }

    profit.setUser(advisedUser);

    profit.save();

    return created();
  }
예제 #26
0
 public static Result save() {
   Form<FastSubject> fastSubjectForm = Form.form(FastSubject.class).bindFromRequest();
   FastSubject fastSubject = fastSubjectForm.get();
   if (fastSubject.id == null) Ebean.save(fastSubject);
   else Ebean.update(fastSubject);
   FlashMessage.updateSuccess.send();
   return redirect(routes.FastSubjects.edit(fastSubject.id));
 }
예제 #27
0
 public static Result newTask() {
   Form<Task> filledForm = taskForm.bindFromRequest();
   if (filledForm.hasErrors()) return badRequest(views.html.task.render(Task.all(), filledForm));
   else {
     Task.createTask(filledForm.get());
     return redirect(routes.Application.getTasks());
   }
 }
예제 #28
0
파일: MyAccount.java 프로젝트: jmu/fff
 public static Result edit() {
   Form<User> userForm =
       new Form(User.class)
           .fill(User.findById.byId(Long.valueOf(session(Application.USER_KEY_ID))));
   // clean the sha1 password
   userForm.get().password = null;
   return ok(myAccount.render(userForm));
 }
예제 #29
0
  public static Result salvar() {
    Form<Pedido> form = form(Pedido.class).bindFromRequest();
    Pedido pedido = form.get();
    pedido.save();

    flash("sucesso", "Salvo com sucesso");
    return ok(index.render());
  }
예제 #30
0
  /** Handles the form submission. */
  @Restrict(@Group(AuthApplication.DATA_OWNER_ROLE))
  public static Result processForm() {
    final SysUser user = AuthApplication.getLocalUser(session());
    Form<DeploymentForm> form = Form.form(DeploymentForm.class).bindFromRequest();
    DeploymentForm data = form.get();

    String dateStringFromJs = data.getStartDateTime();
    String dateString = "";
    DateFormat jsFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
    Date dateFromJs;
    try {
      dateFromJs = jsFormat.parse(dateStringFromJs);
      DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
      dateString = isoFormat.format(dateFromJs);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    int triggeringEvent;
    String insert = "";
    String deploymentUri = DataFactory.getNextURI(DataFactory.DEPLOYMENT_ABBREV);
    String dataCollectionUri = DataFactory.getNextURI(DataFactory.DATA_COLLECTION_ABBREV);
    if (data.getType().equalsIgnoreCase("LEGACY")) {
      triggeringEvent = TriggeringEvent.LEGACY_DEPLOYMENT;
    } else {
      triggeringEvent = TriggeringEvent.INITIAL_DEPLOYMENT;
    }

    System.out.println("new deployment: size of detector's array : " + data.getDetector().size());
    if (data.getDetector().size() > 0) {
      for (String detector : data.getDetector()) {
        System.out.println("   -- det uri: " + detector);
      }
    }

    Deployment deployment =
        DataFactory.createDeployment(
            deploymentUri,
            data.getPlatform(),
            data.getInstrument(),
            data.getDetector(),
            dateString,
            data.getType());
    DataAcquisition dataCollection =
        DataFactory.createDataAcquisition(
            dataCollectionUri,
            deploymentUri,
            triggeringEvent,
            UserManagement.getUriByEmail(user.email));
    if (form.hasErrors()) {
      System.out.println("HAS ERRORS");
      return badRequest(
          newDeployment.render(
              form, Platform.find(), Instrument.find(), Detector.find(), data.getType()));
    } else {
      return ok(deploymentConfirm.render("New Deployment", data));
    }
  }