Search in sources :

Example 1 with GitBlitException

use of com.gitblit.GitBlitException in project gitblit by gitblit.

the class GitFilter method createRepository.

/**
	 * An authenticated user with the CREATE role can create a repository on
	 * push.
	 *
	 * @param user
	 * @param repository
	 * @param action
	 * @return the repository model, if it is created, null otherwise
	 */
@Override
protected RepositoryModel createRepository(UserModel user, String repository, String action) {
    boolean isPush = !StringUtils.isEmpty(action) && gitReceivePack.equals(action);
    if (action.equals(gitLfs)) {
        //Repository must already exist for any filestore actions
        return null;
    }
    if (isPush) {
        if (user.canCreate(repository)) {
            // validate name
            if (repository.startsWith("../")) {
                logger.error(MessageFormat.format("Illegal relative path in repository name! {0}", repository));
                return null;
            }
            if (repository.contains("/../")) {
                logger.error(MessageFormat.format("Illegal relative path in repository name! {0}", repository));
                return null;
            }
            // confirm valid characters in repository name
            Character c = StringUtils.findInvalidCharacter(repository);
            if (c != null) {
                logger.error(MessageFormat.format("Invalid character '{0}' in repository name {1}!", c, repository));
                return null;
            }
            // create repository
            RepositoryModel model = new RepositoryModel();
            model.name = repository;
            model.addOwner(user.username);
            model.projectPath = StringUtils.getFirstPathElement(repository);
            if (model.isUsersPersonalRepository(user.username)) {
                // personal repository, default to private for user
                model.authorizationControl = AuthorizationControl.NAMED;
                model.accessRestriction = AccessRestrictionType.VIEW;
            } else {
                // common repository, user default server settings
                model.authorizationControl = AuthorizationControl.fromName(settings.getString(Keys.git.defaultAuthorizationControl, ""));
                model.accessRestriction = AccessRestrictionType.fromName(settings.getString(Keys.git.defaultAccessRestriction, "PUSH"));
            }
            // create the repository
            try {
                repositoryManager.updateRepositoryModel(model.name, model, true);
                logger.info(MessageFormat.format("{0} created {1} ON-PUSH", user.username, model.name));
                return repositoryManager.getRepositoryModel(model.name);
            } catch (GitBlitException e) {
                logger.error(MessageFormat.format("{0} failed to create repository {1} ON-PUSH!", user.username, model.name), e);
            }
        } else {
            logger.warn(MessageFormat.format("{0} is not permitted to create repository {1} ON-PUSH!", user.username, repository));
        }
    }
    // repository could not be created or action was not a push
    return null;
}
Also used : GitBlitException(com.gitblit.GitBlitException) RepositoryModel(com.gitblit.models.RepositoryModel)

Example 2 with GitBlitException

use of com.gitblit.GitBlitException in project gitblit by gitblit.

the class RepositoryManager method updateRepositoryModel.

/**
	 * Creates/updates the repository model keyed by repositoryName. Saves all
	 * repository settings in .git/config. This method allows for renaming
	 * repositories and will update user access permissions accordingly.
	 *
	 * All repositories created by this method are bare and automatically have
	 * .git appended to their names, which is the standard convention for bare
	 * repositories.
	 *
	 * @param repositoryName
	 * @param repository
	 * @param isCreate
	 * @throws GitBlitException
	 */
@Override
public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate) throws GitBlitException {
    if (isCollectingGarbage(repositoryName)) {
        throw new GitBlitException(MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}", repositoryName));
    }
    Repository r = null;
    String projectPath = StringUtils.getFirstPathElement(repository.name);
    if (!StringUtils.isEmpty(projectPath)) {
        if (projectPath.equalsIgnoreCase(settings.getString(Keys.web.repositoryRootGroupName, "main"))) {
            // strip leading group name
            repository.name = repository.name.substring(projectPath.length() + 1);
        }
    }
    boolean isRename = false;
    if (isCreate) {
        // ensure created repository name ends with .git
        if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
            repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
        }
        if (hasRepository(repository.name)) {
            throw new GitBlitException(MessageFormat.format("Can not create repository ''{0}'' because it already exists.", repository.name));
        }
        // create repository
        logger.info("create repository " + repository.name);
        String shared = settings.getString(Keys.git.createRepositoriesShared, "FALSE");
        r = JGitUtils.createRepository(repositoriesFolder, repository.name, shared);
    } else {
        // rename repository
        isRename = !repositoryName.equalsIgnoreCase(repository.name);
        if (isRename) {
            if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) {
                repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT;
            }
            if (new File(repositoriesFolder, repository.name).exists()) {
                throw new GitBlitException(MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.", repositoryName, repository.name));
            }
            close(repositoryName);
            File folder = new File(repositoriesFolder, repositoryName);
            File destFolder = new File(repositoriesFolder, repository.name);
            if (destFolder.exists()) {
                throw new GitBlitException(MessageFormat.format("Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.", repositoryName, repository.name));
            }
            File parentFile = destFolder.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                throw new GitBlitException(MessageFormat.format("Failed to create folder ''{0}''", parentFile.getAbsolutePath()));
            }
            if (!folder.renameTo(destFolder)) {
                throw new GitBlitException(MessageFormat.format("Failed to rename repository ''{0}'' to ''{1}''.", repositoryName, repository.name));
            }
            // rename the roles
            if (!userManager.renameRepositoryRole(repositoryName, repository.name)) {
                throw new GitBlitException(MessageFormat.format("Failed to rename repository permissions ''{0}'' to ''{1}''.", repositoryName, repository.name));
            }
            // rename fork origins in their configs
            if (!ArrayUtils.isEmpty(repository.forks)) {
                for (String fork : repository.forks) {
                    Repository rf = getRepository(fork);
                    try {
                        StoredConfig config = rf.getConfig();
                        String origin = config.getString("remote", "origin", "url");
                        origin = origin.replace(repositoryName, repository.name);
                        config.setString("remote", "origin", "url", origin);
                        config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.name);
                        config.save();
                    } catch (Exception e) {
                        logger.error("Failed to update repository fork config for " + fork, e);
                    }
                    rf.close();
                }
            }
            // update this repository's origin's fork list
            if (!StringUtils.isEmpty(repository.originRepository)) {
                String originKey = getRepositoryKey(repository.originRepository);
                RepositoryModel origin = repositoryListCache.get(originKey);
                if (origin != null && !ArrayUtils.isEmpty(origin.forks)) {
                    origin.forks.remove(repositoryName);
                    origin.forks.add(repository.name);
                }
            }
            // clear the cache
            clearRepositoryMetadataCache(repositoryName);
            repository.resetDisplayName();
        }
        // load repository
        logger.info("edit repository " + repository.name);
        r = getRepository(repository.name);
    }
    // update settings
    if (r != null) {
        updateConfiguration(r, repository);
        // Update the description file
        File descFile = new File(r.getDirectory(), "description");
        if (repository.description != null) {
            com.gitblit.utils.FileUtils.writeContent(descFile, repository.description);
        } else if (descFile.exists() && !descFile.isDirectory()) {
            descFile.delete();
        }
        // only update symbolic head if it changes
        String currentRef = JGitUtils.getHEADRef(r);
        if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) {
            logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", repository.name, currentRef, repository.HEAD));
            if (JGitUtils.setHEADtoRef(r, repository.HEAD)) {
                // clear the cache
                clearRepositoryMetadataCache(repository.name);
            }
        }
        // Adjust permissions in case we updated the config files
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "config"), settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
        JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "HEAD"), settings.getString(Keys.git.createRepositoriesShared, "FALSE"));
        // close the repository object
        r.close();
    }
    // update repository cache
    removeFromCachedRepositoryList(repositoryName);
    // model will actually be replaced on next load because config is stale
    addToCachedRepositoryList(repository);
    if (isCreate && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager.getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onCreation(repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onCreation %s", repositoryName), t);
            }
        }
    } else if (isRename && pluginManager != null) {
        for (RepositoryLifeCycleListener listener : pluginManager.getExtensions(RepositoryLifeCycleListener.class)) {
            try {
                listener.onRename(repositoryName, repository);
            } catch (Throwable t) {
                logger.error(String.format("failed to call plugin onRename %s", repositoryName), t);
            }
        }
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) GitBlitException(com.gitblit.GitBlitException) RepositoryModel(com.gitblit.models.RepositoryModel) RepositoryLifeCycleListener(com.gitblit.extensions.RepositoryLifeCycleListener) File(java.io.File) URISyntaxException(java.net.URISyntaxException) GitBlitException(com.gitblit.GitBlitException) IOException(java.io.IOException)

Example 3 with GitBlitException

use of com.gitblit.GitBlitException in project gitblit by gitblit.

the class GitblitManager method reviseUser.

/**
	 * Updates a user object keyed by username. This method allows
	 * for renaming a user.
	 *
	 * @param username
	 * @param user
	 * @throws GitBlitException
	 */
@Override
public void reviseUser(String username, UserModel user) throws GitBlitException {
    if (!username.equalsIgnoreCase(user.username)) {
        if (userManager.getUserModel(user.username) != null) {
            throw new GitBlitException(MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.", username, user.username));
        }
        // rename repositories and owner fields for all repositories
        for (RepositoryModel model : repositoryManager.getRepositoryModels(user)) {
            if (model.isUsersPersonalRepository(username)) {
                // personal repository
                model.addOwner(user.username);
                String oldRepositoryName = model.name;
                model.name = user.getPersonalPath() + model.name.substring(model.projectPath.length());
                model.projectPath = user.getPersonalPath();
                repositoryManager.updateRepositoryModel(oldRepositoryName, model, false);
            } else if (model.isOwner(username)) {
                // common/shared repo
                model.addOwner(user.username);
                repositoryManager.updateRepositoryModel(model.name, model, false);
            }
        }
        // rename the user's ssh public keystore
        getPublicKeyManager().renameUser(username, user.username);
    }
    if (!userManager.updateUserModel(username, user)) {
        throw new GitBlitException("Failed to update user!");
    }
}
Also used : GitBlitException(com.gitblit.GitBlitException) RepositoryModel(com.gitblit.models.RepositoryModel)

Example 4 with GitBlitException

use of com.gitblit.GitBlitException in project gitblit by gitblit.

the class UserPage method addPreferences.

private void addPreferences(UserModel user) {
    // add preferences
    Form<Void> prefs = new Form<Void>("prefsForm");
    List<Language> languages = getLanguages();
    Locale locale = user.getPreferences().getLocale();
    if (locale == null) {
        // user has not specified language preference
        // try server default preference
        String lc = app().settings().getString(Keys.web.forceDefaultLocale, null);
        if (StringUtils.isEmpty(lc)) {
            // server default language is not configured
            // try browser preference
            Locale sessionLocale = GitBlitWebSession.get().getLocale();
            if (sessionLocale != null) {
                locale = sessionLocale;
            }
        } else {
        }
    }
    Language preferredLanguage = null;
    if (locale != null) {
        String localeCode = locale.getLanguage();
        if (!StringUtils.isEmpty(locale.getCountry())) {
            localeCode += "_" + locale.getCountry();
        }
        for (Language language : languages) {
            if (language.code.equals(localeCode)) {
                // language_COUNTRY match
                preferredLanguage = language;
            } else if (preferredLanguage != null && language.code.startsWith(locale.getLanguage())) {
                // language match
                preferredLanguage = language;
            }
        }
    }
    final IModel<String> displayName = Model.of(user.getDisplayName());
    final IModel<String> emailAddress = Model.of(user.emailAddress == null ? "" : user.emailAddress);
    final IModel<Language> language = Model.of(preferredLanguage);
    final IModel<Boolean> emailMeOnMyTicketChanges = Model.of(user.getPreferences().isEmailMeOnMyTicketChanges());
    final IModel<Transport> transport = Model.of(user.getPreferences().getTransport());
    prefs.add(new TextOption("displayName", getString("gb.displayName"), getString("gb.displayNameDescription"), displayName).setVisible(app().authentication().supportsDisplayNameChanges(user)));
    prefs.add(new TextOption("emailAddress", getString("gb.emailAddress"), getString("gb.emailAddressDescription"), emailAddress).setVisible(app().authentication().supportsEmailAddressChanges(user)));
    prefs.add(new ChoiceOption<Language>("language", getString("gb.languagePreference"), getString("gb.languagePreferenceDescription"), language, languages));
    prefs.add(new BooleanOption("emailMeOnMyTicketChanges", getString("gb.emailMeOnMyTicketChanges"), getString("gb.emailMeOnMyTicketChangesDescription"), emailMeOnMyTicketChanges).setVisible(app().notifier().isSendingMail()));
    List<Transport> availableTransports = new ArrayList<>();
    if (app().services().isServingSSH()) {
        availableTransports.add(Transport.SSH);
    }
    if (app().services().isServingHTTP()) {
        availableTransports.add(Transport.HTTP);
    }
    if (app().services().isServingHTTPS()) {
        availableTransports.add(Transport.HTTPS);
    }
    if (app().services().isServingGIT()) {
        availableTransports.add(Transport.GIT);
    }
    prefs.add(new ChoiceOption<Transport>("transport", getString("gb.transportPreference"), getString("gb.transportPreferenceDescription"), transport, availableTransports));
    prefs.add(new AjaxButton("save") {

        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            UserModel user = GitBlitWebSession.get().getUser();
            user.displayName = displayName.getObject();
            user.emailAddress = emailAddress.getObject();
            Language lang = language.getObject();
            if (lang != null) {
                user.getPreferences().setLocale(lang.code);
            }
            user.getPreferences().setEmailMeOnMyTicketChanges(emailMeOnMyTicketChanges.getObject());
            user.getPreferences().setTransport(transport.getObject());
            try {
                app().gitblit().reviseUser(user.username, user);
                setRedirect(true);
                setResponsePage(UserPage.class, WicketUtils.newUsernameParameter(user.username));
            } catch (GitBlitException e) {
            // logger.error("Failed to update user " + user.username, e);
            // error(getString("gb.failedToUpdateUser"), false);
            }
        }
    });
    // add the preferences tab
    add(new Fragment("preferencesLink", "preferencesLinkFragment", this).setRenderBodyOnly(true));
    Fragment fragment = new Fragment("preferencesTab", "preferencesTabFragment", this);
    fragment.add(prefs);
    add(fragment.setRenderBodyOnly(true));
}
Also used : Locale(java.util.Locale) Form(org.apache.wicket.markup.html.form.Form) ArrayList(java.util.ArrayList) TextOption(com.gitblit.wicket.panels.TextOption) GitBlitException(com.gitblit.GitBlitException) Fragment(org.apache.wicket.markup.html.panel.Fragment) UserModel(com.gitblit.models.UserModel) AjaxButton(org.apache.wicket.ajax.markup.html.form.AjaxButton) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) Transport(com.gitblit.Constants.Transport) BooleanOption(com.gitblit.wicket.panels.BooleanOption)

Example 5 with GitBlitException

use of com.gitblit.GitBlitException in project gitblit by gitblit.

the class GroovyScriptTest method test.

private void test(String script, MockGitblit gitblit, MockLogger logger, MockClientLogger clientLogger, List<ReceiveCommand> commands, RepositoryModel repository) throws Exception {
    UserModel user = new UserModel("mock");
    String gitblitUrl = GitBlitSuite.url;
    File groovyDir = repositories().getHooksFolder();
    GroovyScriptEngine gse = new GroovyScriptEngine(groovyDir.getAbsolutePath());
    Binding binding = new Binding();
    binding.setVariable("gitblit", gitblit);
    binding.setVariable("repository", repository);
    binding.setVariable("user", user);
    binding.setVariable("commands", commands);
    binding.setVariable("url", gitblitUrl);
    binding.setVariable("logger", logger);
    binding.setVariable("clientLogger", clientLogger);
    Object result = gse.run(script, binding);
    if (result instanceof Boolean) {
        if (!((Boolean) result)) {
            throw new GitBlitException(MessageFormat.format("Groovy script {0} has failed!  Hook scripts aborted.", script));
        }
    }
}
Also used : UserModel(com.gitblit.models.UserModel) Binding(groovy.lang.Binding) GroovyScriptEngine(groovy.util.GroovyScriptEngine) GitBlitException(com.gitblit.GitBlitException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) File(java.io.File)

Aggregations

GitBlitException (com.gitblit.GitBlitException)16 RepositoryModel (com.gitblit.models.RepositoryModel)10 ArrayList (java.util.ArrayList)9 UserModel (com.gitblit.models.UserModel)6 Form (org.apache.wicket.markup.html.form.Form)5 TeamModel (com.gitblit.models.TeamModel)4 File (java.io.File)4 SimpleAttributeModifier (org.apache.wicket.behavior.SimpleAttributeModifier)4 Button (org.apache.wicket.markup.html.form.Button)4 CompoundPropertyModel (org.apache.wicket.model.CompoundPropertyModel)4 RegistrantAccessPermission (com.gitblit.models.RegistrantAccessPermission)3 StringChoiceRenderer (com.gitblit.wicket.StringChoiceRenderer)3 BooleanOption (com.gitblit.wicket.panels.BooleanOption)3 RegistrantPermissionsPanel (com.gitblit.wicket.panels.RegistrantPermissionsPanel)3 IOException (java.io.IOException)3 Repository (org.eclipse.jgit.lib.Repository)3 RepositoryLifeCycleListener (com.gitblit.extensions.RepositoryLifeCycleListener)2 IRepositoryManager (com.gitblit.manager.IRepositoryManager)2 UserChoice (com.gitblit.models.UserChoice)2 AccessPolicyPanel (com.gitblit.wicket.panels.AccessPolicyPanel)2