@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());
    }
  }
  /**
   * 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));
    }
  }
Beispiel #3
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)));
  }
  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());
    }
  }
Beispiel #5
0
  /**
   * {@code posting}에 {@code original} 정보를 채우고 갱신한다.
   *
   * <p>when: 게시물이나 이슈를 수정할 떄 사용한다.
   *
   * @param original
   * @param posting
   * @param postingForm
   * @param redirectTo
   * @param updatePosting
   * @return
   */
  protected static Result editPosting(
      AbstractPosting original,
      AbstractPosting posting,
      Form<? extends AbstractPosting> postingForm,
      Call redirectTo,
      Callback updatePosting) {
    if (postingForm.hasErrors()) {
      return badRequest(postingForm.errors().toString());
    }

    if (!AccessControl.isAllowed(UserApp.currentUser(), original.asResource(), Operation.UPDATE)) {
      return forbidden(views.html.error.forbidden.render(original.project));
    }

    posting.id = original.id;
    posting.createdDate = original.createdDate;
    posting.authorId = original.authorId;
    posting.authorLoginId = original.authorLoginId;
    posting.authorName = original.authorName;
    posting.project = original.project;
    updatePosting.run();
    posting.update();

    // Attach the files in the current user's temporary storage.
    Attachment.moveAll(UserApp.currentUser().asResource(), original.asResource());

    return redirect(redirectTo);
  }
Beispiel #6
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()));
      }
    }
  }
Beispiel #7
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();
  }
Beispiel #8
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");
  }
Beispiel #9
0
  /**
   * 로그인 처리 시스템 설정에서 가입승인 기능이 활성화 되어 있고 사용자 상태가 잠금상태(미승인?)라면 계정이 잠겼다는 메시지를 노출하고 로그인 폼으로 돌아감 시스템 설정에서
   * 가입승인 기능이 활성화 되어 있지 않다면, 사용자 상태가 잠금상태라도 로그인이 가능하다 (스펙확인 필요) 요청의 정보로 사용자 인증에 성공하면 로그인쿠키를 생성하고
   * 로그인유지하기가 선택되었다면, 로그인유지를 위한 쿠키를 별도로 생성한다 인증에 실패하면 관련된 메시지를 노출하고 로그인 폼으로 돌아간다
   *
   * @return
   */
  public static Result login() {
    Form<User> userForm = form(User.class).bindFromRequest();
    if (userForm.hasErrors()) {
      return badRequest(login.render("title.login", userForm));
    }
    User sourceUser = form(User.class).bindFromRequest().get();

    if (isUseSignUpConfirm()) {
      if (User.findByLoginId(sourceUser.loginId).state == UserState.LOCKED) {
        flash(Constants.WARNING, "user.locked");
        return redirect(routes.UserApp.loginForm());
      }
    }

    if (User.findByLoginId(sourceUser.loginId).state == UserState.DELETED) {
      flash(Constants.WARNING, "user.deleted");
      return redirect(routes.UserApp.loginForm());
    }

    User authenticate = authenticateWithPlainPassword(sourceUser.loginId, sourceUser.password);

    if (authenticate != null) {
      addUserInfoToSession(authenticate);
      if (sourceUser.rememberMe) {
        setupRememberMe(authenticate);
      }
      return redirect(routes.Application.index());
    }

    flash(Constants.WARNING, "user.login.failed");
    return redirect(routes.UserApp.loginForm());
  }
  /** 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());
    }
  }
  @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"));
    }
  }
  /**
   * 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());
      }
    }
  }
  /** 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));
  }
Beispiel #14
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);
    }
  }
  /** 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));
  }
  /** 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));
  }
Beispiel #17
0
  /**
   * 사용자 비밀번호 변경 비밀번호 변경에 성공하면 로그인 화면으로 이동 비밀번호 변경에 실패하면 수정화면으로 돌아간다
   *
   * @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());
  }
  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));
    }
  }
  /**
   * 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())));
    }
  }
Beispiel #20
0
  /**
   * 이메일 추가
   *
   * @return
   */
  @Transactional
  public static Result addEmail() {
    Form<Email> emailForm = form(Email.class).bindFromRequest();
    String newEmail = emailForm.data().get("email");

    if (emailForm.hasErrors()) {
      flash(Constants.WARNING, emailForm.error("email").message());
      return redirect(routes.UserApp.editUserInfoForm());
    }

    User currentUser = currentUser();
    if (currentUser == null || currentUser.isAnonymous()) {
      return forbidden(ErrorViews.NotFound.render());
    }

    if (User.isEmailExist(newEmail) || Email.exists(newEmail, true) || currentUser.has(newEmail)) {
      flash(Constants.WARNING, Messages.get("user.email.duplicate"));
      return redirect(routes.UserApp.editUserInfoForm());
    }

    Email email = new Email();
    User user = currentUser();
    email.user = user;
    email.email = newEmail;
    email.valid = false;

    user.addEmail(email);

    return redirect(routes.UserApp.editUserInfoForm());
  }
  // TODO change to use Contact.create() method
  @Security.Authenticated(Secured.class)
  public static Result newContact() {

    Form<Contact> filledForm = contactForm.bindFromRequest();

    String name = filledForm.data().get("name");
    String firstName = filledForm.data().get("firstName");
    String title = filledForm.data().get("title");
    String email = filledForm.data().get("email");
    String street = filledForm.data().get("street");
    String appendix1 = filledForm.data().get("appendix1");
    String appendix2 = filledForm.data().get("appendix2");
    String zipcode = filledForm.data().get("zipcode");
    String country = filledForm.data().get("country");
    String city = filledForm.data().get("city");
    String phone = filledForm.data().get("phone");
    String yearbook = filledForm.data().get("yearbookSubscription");
    String memberCategory = filledForm.data().get("memberCategory");
    String membershipSince = filledForm.data().get("membershipSince");

    Contact newContact = new Contact();
    newContact.name = name;
    newContact.firstName = firstName;
    newContact.title = title;
    newContact.email = email;
    newContact.street = street;
    newContact.appendix1 = appendix1;
    newContact.appendix2 = appendix2;
    newContact.zipcode = zipcode;
    newContact.city = city;
    newContact.country = country;
    newContact.phone = phone;

    if (yearbook.equals("true")) newContact.yearbookSubscription = true;
    newContact.memberCategory = memberCategory;

    for (int j = 0; j < ContactGroup.options().size(); j++) {
      String item = "belongsTo[" + j + "]";
      if (filledForm.data().get(item) != null) {
        ContactGroup cg =
            ContactGroup.find.byId((long) Integer.parseInt(filledForm.data().get(item)));
        newContact.belongsTo.add(cg);
      }
    }

    if (newContact.belongsTo.isEmpty())
      filledForm.reject("belongsTo[]", "Keine Sektion ausgewählt");

    // TODO Check fields for errors

    if (filledForm.hasErrors()) System.out.println(filledForm.errors().toString());

    newContact.membershipSince = membershipSince;
    newContact.createdAt = new Timestamp(new Date().getTime());
    newContact.lastEditedAt = newContact.createdAt;
    newContact.save();
    flash("success", "Kontakt " + newContact + " erstellt und gespeichert.");
    return redirect(routes.Application.contacts());
  }
 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());
   }
 }
Beispiel #23
0
 public static Result registerNewUser() {
   Form<Register> regForm = Form.form(Register.class).bindFromRequest();
   if (regForm.hasErrors()) {
     return badRequest(register.render(regForm));
   } else {
     return redirect(routes.Application.login());
   }
 }
  /** 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));
    }
  }
  /**
   * Do forgot password.
   *
   * @return the result
   */
  public static Result doForgotPassword() {
    Logger.debug("Account doForgotPassword");
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    final Form<EmailUserIdentity> filledForm = FORGOT_PASSWORD_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not fill in his/her email
      return badRequest(password_forgot.render(filledForm));
    } else {
      // The email address given *BY AN UNKNWON PERSON* to the form - we
      // should find out if we actually have a user with this email
      // address and whether password login is enabled for him/her. Also
      // only send if the email address of the user has been verified.
      final String email = filledForm.get().email;

      final User user = User.findByEmail(email);
      if (user == null) {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_WARNING_KEY,
            "Your email address doesn't match our records. Please try again.");
      } else {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_INFO_KEY,
            Messages.get("playauthenticate.reset_password.message.instructions_sent", email));

        // yep, we have a user with this email that is active - we do
        // not know if the user owning that account has requested this
        // reset, though.
        final EmailAuthProvider provider = EmailAuthProvider.getProvider();
        // User exists
        if (user.emailValidated) {
          provider.sendPasswordResetMailing(user, ctx());
          // In case you actually want to let (the unknown person)
          // know whether a user was found/an email was sent, use,
          // change the flash message
        } else {
          // We need to change the message here, otherwise the user
          // does not understand whats going on - we should not verify
          // with the password reset, as a "bad" user could then sign
          // up with a fake email via OAuth and get it verified by an
          // a unsuspecting user that clicks the link.
          flash(
              ControllerUtil.FLASH_INFO_KEY,
              Messages.get("playauthenticate.reset_password.message.email_not_verified"));

          // You might want to re-send the verification email here...
          provider.sendVerifyEmailMailingAfterSignup(user, ctx());
        }
      }

      return redirect(routes.Signup.login());
    }
  }
  public static Result doRegistrieren() {

    Map<String, String[]> parameters = request().body().asFormUrlEncoded();

    Form<User> form = Form.form(User.class);

    form = form.bindFromRequest();

    if (form.hasErrors()) {
      return badRequest(views.html.registrieren.render("war nix. Fehler: " + form.errors()));
    } else {
      User user = form.get();

      if (!user.password.equals(parameters.get("password2")[0])) {
        return badRequest(views.html.registrieren.render("Passwörter stimmen nicht überein"));
      }
      // UserDB.init();
      //
      DBUser users = DBUser.get();
      // TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
      Date date = new Date();
      Date d = new Date();
      try {
        //  30-07-1987
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
        Logger.info("date from js " + parameters.get("datepicker")[0]);
        String datefromForm = parameters.get("datepicker")[0];
        // String datefromForm = "2013-05-04";
        date = sdf.parse(datefromForm);

        Logger.info(date.toString());
      } catch (Exception e) {
        Logger.info("Fehler beim Date \n" + e);
      }

      if (date == null) {
        return badRequest(views.html.registrieren.render("Date geht noch nicht...oder war leer!"));
      }

      // Date date = sdf.parse(user.date);

      User newUser =
          users.create(new User(user.email, user.password, user.nickname, user.fahrer, date));

      // +" remember: " +user.remember);
      // UserDB userDB = UserDB.get();
      // User userDB = UserDB.get().validateUser(user.email,
      // user.password);
      if (newUser != null) {

        return ok(views.html.loginform.render(""));
      } else {
        // return badRequest("falsche Angaben");
        return badRequest(views.html.registrieren.render("E-Mail existiert bereits"));
      }
    }
  }
Beispiel #27
0
 /** Handle login form submission. */
 public static Result authenticate() {
   Form<Login> filledLogin = form(Application.Login.class).bindFromRequest();
   if (filledLogin.hasErrors()) {
     return badRequest(login.render(filledLogin));
   } else {
     session("email", filledLogin.get().email);
     return redirect(routes.JobOffers.index());
   }
 }
 /** Handle login form submission. */
 public static Result authenticate() {
   Form<Login> loginForm = form(Login.class).bindFromRequest();
   if (loginForm.hasErrors()) {
     return badRequest(login.render(loginForm));
   } else {
     session("email", loginForm.get().email);
     return redirect(controllers.routes.Application.index());
   }
 }
Beispiel #29
0
 public Result doLogin() {
   com.feth.play.module.pa.controllers.Authenticate.noCache(response());
   final Form<MyLogin> filledForm = MyUsernamePasswordAuthProvider.LOGIN_FORM.bindFromRequest();
   if (filledForm.hasErrors()) {
     // User did not fill everything properly
     return badRequest(login.render(filledForm));
   } else {
     return UsernamePasswordAuthProvider.handleLogin(ctx());
   }
 }
Beispiel #30
0
 public static Result authenticate() {
   Form<User> loginForm = Form.form(User.class).bindFromRequest();
   if (loginForm.hasErrors()) {
     return badRequest(login.render(loginForm));
   } else {
     session().clear();
     session("name", loginForm.get().name);
     return redirect(routes.Application.index());
   }
 }