Ejemplo n.º 1
0
  public EditRepositoryPage() {
    // create constructor
    super();
    isCreate = true;
    RepositoryModel model = new RepositoryModel();
    String restriction = GitBlit.getString(Keys.git.defaultAccessRestriction, null);
    model.accessRestriction = AccessRestrictionType.fromName(restriction);
    String authorization = GitBlit.getString(Keys.git.defaultAuthorizationControl, null);
    model.authorizationControl = AuthorizationControl.fromName(authorization);

    GitBlitWebSession session = GitBlitWebSession.get();
    UserModel user = session.getUser();
    if (user != null && user.canCreate() && !user.canAdmin()) {
      // personal create permissions, inject personal repository path
      model.name = user.getPersonalPath() + "/";
      model.projectPath = user.getPersonalPath();
      model.addOwner(user.username);
      // personal repositories are private by default
      model.accessRestriction = AccessRestrictionType.VIEW;
      model.authorizationControl = AuthorizationControl.NAMED;
    }

    setupPage(model);
    setStatelessHint(false);
    setOutputMarkupId(true);
  }
Ejemplo n.º 2
0
  /**
   * Unfortunately must repeat part of AuthorizaitonStrategy here because that mechanism does not
   * take PageParameters into consideration, only page instantiation.
   *
   * <p>Repository Owners should be able to edit their repository.
   */
  private void checkPermissions(RepositoryModel model) {
    boolean authenticateAdmin = GitBlit.getBoolean(Keys.web.authenticateAdminPages, true);
    boolean allowAdmin = GitBlit.getBoolean(Keys.web.allowAdministration, true);

    GitBlitWebSession session = GitBlitWebSession.get();
    UserModel user = session.getUser();

    if (allowAdmin) {
      if (authenticateAdmin) {
        if (user == null) {
          // No Login Available
          error(getString("gb.errorAdminLoginRequired"), true);
        }
        if (isCreate) {
          // Create Repository
          if (!user.canCreate() && !user.canAdmin()) {
            // Only administrators or permitted users may create
            error(getString("gb.errorOnlyAdminMayCreateRepository"), true);
          }
        } else {
          // Edit Repository
          if (user.canAdmin()) {
            // Admins can edit everything
            isAdmin = true;
            return;
          } else {
            if (!model.isOwner(user.username)) {
              // User is not an Admin nor Owner
              error(getString("gb.errorOnlyAdminOrOwnerMayEditRepository"), true);
            }
          }
        }
      }
    } else {
      // No Administration Permitted
      error(getString("gb.errorAdministrationDisabled"), true);
    }
  }
Ejemplo n.º 3
0
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      authenticationError("Please login");
      return;
    }

    String projectName = WicketUtils.getProjectName(params);
    if (StringUtils.isEmpty(projectName)) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    ProjectModel project = getProjectModel(projectName);
    if (project == null) {
      throw new GitblitRedirectException(GitBlitWebApp.get().getHomePage());
    }

    add(new Label("projectTitle", project.getDisplayName()));
    add(new Label("projectDescription", project.description));

    String feedLink =
        SyndicationServlet.asLink(
            getRequest().getRelativePathPrefixToContextRoot(), projectName, null, 0);
    add(new ExternalLink("syndication", feedLink));

    add(
        WicketUtils.syndicationDiscoveryLink(
            SyndicationServlet.getTitle(project.getDisplayName(), null), feedLink));

    // project markdown message
    String pmessage = transformMarkdown(project.projectMarkdown);
    Component projectMessage =
        new Label("projectMessage", pmessage)
            .setEscapeModelStrings(false)
            .setVisible(pmessage.length() > 0);
    add(projectMessage);

    // markdown message above repositories list
    String rmessage = transformMarkdown(project.repositoriesMarkdown);
    Component repositoriesMessage =
        new Label("repositoriesMessage", rmessage)
            .setEscapeModelStrings(false)
            .setVisible(rmessage.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    // reset the daysback parameter so that we have a complete project
    // repository list.  the recent activity will be built up by the
    // reflog utils.
    params.remove("db");

    List<RepositoryModel> repositories = getRepositories(params);
    Collections.sort(
        repositories,
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            // reverse-chronological sort
            return o2.lastChange.compareTo(o1.lastChange);
          }
        });

    addActivity(user, repositories, getString("gb.recentActivity"), daysBack);

    if (repositories.isEmpty()) {
      add(new Label("repositoryList").setVisible(false));
    } else {
      FilterableRepositoryList repoList =
          new FilterableRepositoryList("repositoryList", repositories);
      repoList.setAllowCreate(user.canCreate(project.name + "/"));
      add(repoList);
    }
  }
Ejemplo n.º 4
0
  private void setup(PageParameters params) {
    setupPage("", "");
    // check to see if we should display a login message
    boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
    if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
      String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
      String message = readMarkdown(messageSource, "login.mkd");
      Component repositoriesMessage = new Label("repositoriesMessage", message);
      add(repositoriesMessage.setEscapeModelStrings(false));
      add(new Label("activity").setVisible(false));
      add(new Label("repositoryTabs").setVisible(false));
      return;
    }

    // Load the markdown welcome message
    String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
    String message = readMarkdown(messageSource, "welcome.mkd");
    Component repositoriesMessage =
        new Label("repositoriesMessage", message)
            .setEscapeModelStrings(false)
            .setVisible(message.length() > 0);
    add(repositoriesMessage);

    UserModel user = GitBlitWebSession.get().getUser();
    if (user == null) {
      user = UserModel.ANONYMOUS;
    }

    // parameters
    int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
    if (daysBack < 1) {
      daysBack = GitBlit.getInteger(Keys.web.activityDuration, 7);
    }
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -1 * daysBack);
    Date minimumDate = c.getTime();

    // build repo lists
    List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
    List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
    List<RepositoryModel> active = new ArrayList<RepositoryModel>();

    for (RepositoryModel model : getRepositoryModels()) {
      if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
        owned.add(model);
      }

      if (user.getPreferences().isStarredRepository(model.name)) {
        starred.add(model);
      }

      if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
        active.add(model);
      }
    }

    Comparator<RepositoryModel> lastUpdateSort =
        new Comparator<RepositoryModel>() {
          @Override
          public int compare(RepositoryModel o1, RepositoryModel o2) {
            return o2.lastChange.compareTo(o1.lastChange);
          }
        };

    Collections.sort(owned, lastUpdateSort);
    Collections.sort(starred, lastUpdateSort);
    Collections.sort(active, lastUpdateSort);

    String activityTitle;
    Set<RepositoryModel> feed = new HashSet<RepositoryModel>();
    feed.addAll(starred);
    feed.addAll(owned);
    if (feed.isEmpty()) {
      // no starred or owned, go with recent activity
      activityTitle = getString("gb.recentActivity");
      feed.addAll(active);
    } else if (starred.isEmpty()) {
      // no starred, owned repos feed
      activityTitle = getString("gb.owned");
    } else if (owned.isEmpty()) {
      // no owned, starred repos feed
      activityTitle = getString("gb.starred");
    } else {
      // starred and owned repositories
      activityTitle = getString("gb.starredAndOwned");
    }

    addActivity(user, feed, activityTitle, daysBack);

    Fragment repositoryTabs;
    if (UserModel.ANONYMOUS.equals(user)) {
      repositoryTabs = new Fragment("repositoryTabs", "anonymousTabsFragment", this);
    } else {
      repositoryTabs = new Fragment("repositoryTabs", "authenticatedTabsFragment", this);
    }

    add(repositoryTabs);

    // projects list
    List<ProjectModel> projects = GitBlit.self().getProjectModels(getRepositoryModels(), false);
    repositoryTabs.add(new FilterableProjectList("projects", projects));

    // active repository list
    if (active.isEmpty()) {
      repositoryTabs.add(new Label("active").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("active", active);
      repoList.setTitle(getString("gb.activeRepositories"), "icon-time");
      repositoryTabs.add(repoList);
    }

    // starred repository list
    if (ArrayUtils.isEmpty(starred)) {
      repositoryTabs.add(new Label("starred").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("starred", starred);
      repoList.setTitle(getString("gb.starredRepositories"), "icon-star");
      repositoryTabs.add(repoList);
    }

    // owned repository list
    if (ArrayUtils.isEmpty(owned)) {
      repositoryTabs.add(new Label("owned").setVisible(false));
    } else {
      FilterableRepositoryList repoList = new FilterableRepositoryList("owned", owned);
      repoList.setTitle(getString("gb.myRepositories"), "icon-user");
      repoList.setAllowCreate(user.canCreate() || user.canAdmin());
      repositoryTabs.add(repoList);
    }
  }
Ejemplo n.º 5
0
  protected void setupPage(final UserModel userModel) {
    if (isCreate) {
      super.setupPage(getString("gb.newUser"), "");
    } else {
      super.setupPage(getString("gb.edit"), userModel.username);
    }

    final Model<String> confirmPassword =
        new Model<String>(StringUtils.isEmpty(userModel.password) ? "" : userModel.password);
    CompoundPropertyModel<UserModel> model = new CompoundPropertyModel<UserModel>(userModel);

    // build list of projects including all repositories wildcards
    List<String> repos = getAccessRestrictedRepositoryList(true, userModel);

    List<String> userTeams = new ArrayList<String>();
    for (TeamModel team : userModel.getTeams()) {
      userTeams.add(team.name);
    }
    Collections.sort(userTeams);

    final String oldName = userModel.username;
    final List<RegistrantAccessPermission> permissions =
        app().repositories().getUserAccessPermissions(userModel);

    final Palette<String> teams =
        new Palette<String>(
            "teams",
            new ListModel<String>(new ArrayList<String>(userTeams)),
            new CollectionModel<String>(app().users().getAllTeamNames()),
            new StringChoiceRenderer(),
            10,
            false);
    Form<UserModel> form =
        new Form<UserModel>("editForm", model) {

          private static final long serialVersionUID = 1L;

          /*
           * (non-Javadoc)
           *
           * @see org.apache.wicket.markup.html.form.Form#onSubmit()
           */
          @Override
          protected void onSubmit() {
            if (StringUtils.isEmpty(userModel.username)) {
              error(getString("gb.pleaseSetUsername"));
              return;
            }
            // force username to lower-case
            userModel.username = userModel.username.toLowerCase();
            String username = userModel.username;
            if (isCreate) {
              UserModel model = app().users().getUserModel(username);
              if (model != null) {
                error(MessageFormat.format(getString("gb.usernameUnavailable"), username));
                return;
              }
            }
            boolean rename = !StringUtils.isEmpty(oldName) && !oldName.equalsIgnoreCase(username);
            if (app().authentication().supportsCredentialChanges(userModel)) {
              if (!userModel.password.equals(confirmPassword.getObject())) {
                error(getString("gb.passwordsDoNotMatch"));
                return;
              }
              String password = userModel.password;
              if (!password.toUpperCase().startsWith(StringUtils.MD5_TYPE)
                  && !password.toUpperCase().startsWith(StringUtils.COMBINED_MD5_TYPE)) {
                // This is a plain text password.
                // Check length.
                int minLength = app().settings().getInteger(Keys.realm.minPasswordLength, 5);
                if (minLength < 4) {
                  minLength = 4;
                }
                if (password.trim().length() < minLength) {
                  error(MessageFormat.format(getString("gb.passwordTooShort"), minLength));
                  return;
                }

                // change the cookie
                userModel.cookie = StringUtils.getSHA1(userModel.username + password);

                // Optionally store the password MD5 digest.
                String type = app().settings().getString(Keys.realm.passwordStorage, "md5");
                if (type.equalsIgnoreCase("md5")) {
                  // store MD5 digest of password
                  userModel.password =
                      StringUtils.MD5_TYPE + StringUtils.getMD5(userModel.password);
                } else if (type.equalsIgnoreCase("combined-md5")) {
                  // store MD5 digest of username+password
                  userModel.password =
                      StringUtils.COMBINED_MD5_TYPE
                          + StringUtils.getMD5(username + userModel.password);
                }
              } else if (rename
                  && password.toUpperCase().startsWith(StringUtils.COMBINED_MD5_TYPE)) {
                error(getString("gb.combinedMd5Rename"));
                return;
              }
            }

            // update user permissions
            for (RegistrantAccessPermission repositoryPermission : permissions) {
              if (repositoryPermission.mutable) {
                userModel.setRepositoryPermission(
                    repositoryPermission.registrant, repositoryPermission.permission);
              }
            }

            Iterator<String> selectedTeams = teams.getSelectedChoices();
            userModel.removeAllTeams();
            while (selectedTeams.hasNext()) {
              TeamModel team = app().users().getTeamModel(selectedTeams.next());
              if (team == null) {
                continue;
              }
              userModel.addTeam(team);
            }

            try {
              if (isCreate) {
                app().gitblit().addUser(userModel);
              } else {
                app().gitblit().reviseUser(oldName, userModel);
              }
            } catch (GitBlitException e) {
              error(e.getMessage());
              return;
            }
            setRedirect(false);
            if (isCreate) {
              // create another user
              info(MessageFormat.format(getString("gb.userCreated"), userModel.username));
              setResponsePage(EditUserPage.class);
            } else {
              // back to users page
              setResponsePage(UsersPage.class);
            }
          }
        };

    // do not let the browser pre-populate these fields
    form.add(new SimpleAttributeModifier("autocomplete", "off"));

    // not all user providers support manipulating username and password
    boolean editCredentials = app().authentication().supportsCredentialChanges(userModel);

    // not all user providers support manipulating display name
    boolean editDisplayName = app().authentication().supportsDisplayNameChanges(userModel);

    // not all user providers support manipulating email address
    boolean editEmailAddress = app().authentication().supportsEmailAddressChanges(userModel);

    // not all user providers support manipulating team memberships
    boolean editTeams = app().authentication().supportsTeamMembershipChanges(userModel);

    // not all user providers support manipulating the admin role
    boolean changeAdminRole = app().authentication().supportsRoleChanges(userModel, Role.ADMIN);

    // not all user providers support manipulating the create role
    boolean changeCreateRole = app().authentication().supportsRoleChanges(userModel, Role.CREATE);

    // not all user providers support manipulating the fork role
    boolean changeForkRole = app().authentication().supportsRoleChanges(userModel, Role.FORK);

    // field names reflective match UserModel fields
    form.add(new TextField<String>("username").setEnabled(editCredentials));
    NonTrimmedPasswordTextField passwordField = new NonTrimmedPasswordTextField("password");
    passwordField.setResetPassword(false);
    form.add(passwordField.setEnabled(editCredentials));
    NonTrimmedPasswordTextField confirmPasswordField =
        new NonTrimmedPasswordTextField("confirmPassword", confirmPassword);
    confirmPasswordField.setResetPassword(false);
    form.add(confirmPasswordField.setEnabled(editCredentials));
    form.add(new TextField<String>("displayName").setEnabled(editDisplayName));
    form.add(new TextField<String>("emailAddress").setEnabled(editEmailAddress));

    if (userModel.canAdmin() && !userModel.canAdmin) {
      // user inherits Admin permission
      // display a disabled-yet-checked checkbox
      form.add(new CheckBox("canAdmin", Model.of(true)).setEnabled(false));
    } else {
      form.add(new CheckBox("canAdmin").setEnabled(changeAdminRole));
    }

    if (userModel.canFork() && !userModel.canFork) {
      // user inherits Fork permission
      // display a disabled-yet-checked checkbox
      form.add(new CheckBox("canFork", Model.of(true)).setEnabled(false));
    } else {
      final boolean forkingAllowed = app().settings().getBoolean(Keys.web.allowForking, true);
      form.add(new CheckBox("canFork").setEnabled(forkingAllowed && changeForkRole));
    }

    if (userModel.canCreate() && !userModel.canCreate) {
      // user inherits Create permission
      // display a disabled-yet-checked checkbox
      form.add(new CheckBox("canCreate", Model.of(true)).setEnabled(false));
    } else {
      form.add(new CheckBox("canCreate").setEnabled(changeCreateRole));
    }

    form.add(new CheckBox("excludeFromFederation"));
    form.add(new CheckBox("disabled"));

    form.add(
        new RegistrantPermissionsPanel(
            "repositories", RegistrantType.REPOSITORY, repos, permissions, getAccessPermissions()));
    form.add(teams.setEnabled(editTeams));

    form.add(new TextField<String>("organizationalUnit").setEnabled(editDisplayName));
    form.add(new TextField<String>("organization").setEnabled(editDisplayName));
    form.add(new TextField<String>("locality").setEnabled(editDisplayName));
    form.add(new TextField<String>("stateProvince").setEnabled(editDisplayName));
    form.add(new TextField<String>("countryCode").setEnabled(editDisplayName));
    form.add(new Button("save"));
    Button cancel =
        new Button("cancel") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            setResponsePage(UsersPage.class);
          }
        };
    cancel.setDefaultFormProcessing(false);
    form.add(cancel);

    add(form);
  }