From: James Moger Date: Wed, 21 Dec 2011 00:35:54 +0000 (-0500) Subject: Renamed GitblitUserService, sendMail method, sendmail.groovy, and RepositoryModel... X-Git-Tag: v0.8.0~65 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=eb96eab513101783a750c13419de6bdce3d2fa4c;p=gitblit.git Renamed GitblitUserService, sendMail method, sendmail.groovy, and RepositoryModel.mailingLists --- diff --git a/docs/01_setup.mkd b/docs/01_setup.mkd index 1cc89bf2..7ea57565 100644 --- a/docs/01_setup.mkd +++ b/docs/01_setup.mkd @@ -217,6 +217,18 @@ User passwords are CASE-SENSITIVE and may be *plain*, *md5*, or *combined-md5* f There are two actual *roles* in Gitblit: *#admin*, which grants administrative powers to that user, and *#notfederated*, which prevents an account from being pulled by another Gitblit instance. Administrators automatically have access to all repositories. All other *roles* are repository names. If a repository is access-restricted, the user must have the repository's name within his/her roles to bypass the access restriction. This is how users are granted access to a restricted repository. ## Authentication and Authorization Customization + +### Choice 1: Customize Authentication Only +This is the simplest choice where you implement custom authentication and delegate all other standard user and team operations to one of Gitblit's user service implementations. This choice insulates your customization from changes in User and Team model classes and additional API that may be added to IUserService. + +Please subclass [com.gitblit.GitblitUserService](https://github.com/gitblit/gitblit/blob/master/src/com/gitblit/GitblitUserService.java) and override the *setup()* and *authenticate()* methods. +Make sure to set the *serviceImpl* field in your *setup()* method. + +You may use your subclass by specifying its fully qualified classname in the *realm.userService* setting. + +Your subclass must be on Gitblit's classpath and must have a public default constructor. + +### Choice 2: Customize Everything Instead of maintaining a `users.conf` or `users.properties` file, you may want to integrate Gitblit into an existing environment. You may use your own custom *com.gitblit.IUserService* implementation by specifying its fully qualified classname in the *realm.userService* setting. @@ -232,19 +244,21 @@ The preferred hook mechanism is Groovy. This mechanism only executes when pushi The Groovy hook mechanism allows for dynamic extension of Gitblit to execute custom tasks on receiving and processing push events. The scripts run within the context of your Gitblit instance and therefore have access to Gitblit's internals at runtime. -### Rules & Requirements +### Rules, Requirements, & Behaviors 1. Your Groovy scripts must be stored in the *groovy.scriptsFolder* as specified in `gitblit.properties` or `web.xml`. 2. All script files must have the *.groovy* extension. Because of this you may omit the extension when specifying the script. 3. Scripts must be explicitly specified to be executed, no scripts are *automatically* executed by name or extension. -4. A script can be specified to run on *all repositories* by adding the script file name to *groovy.preReceiveScripts* or *groovy.postReceiveScripts* in `gitblit.properties` or `web.xml`. +4. A script can be specified to run on *all repositories* by adding the script file name to *groovy.preReceiveScripts* or *groovy.postReceiveScripts* in `gitblit.properties` or `web.xml`. Be mindful of access retrictions and global properties like *mail.mailingLists* if specifying *sendmail* to run on all repositories. 5. Scripts may also be specified per-repository in the repository's settings. -6. Global/shared scripts are executed first in their listed order, followed by per-repository scripts in their listed order. -7. A script may only be defined once in a pre-receive list and once in a post-receive list. +6. Globally specified scripts are excluded from the list of available scripts in a repository's settings +7. Globally specified scripts are executed first, in their listed order, followed by per-repository scripts, in their listed order. +8. A script may only be defined once in a pre-receive list and once in a post-receive list. You may execute the same script on pre-receive and post-receive, just not multiple times within a pre-receive or post-receive event. -8. Gitblit does not differentiate between what can be a pre-receive script and what can be a post-receive script. -9. If a script *returns false* then the hook chain is aborted and none of the subsequent scripts will execute. +9. Gitblit does not differentiate between what can be a pre-receive script and what can be a post-receive script. +10. If a script *returns false* then the pre-receive or post-receive hook chain is aborted and none of the subsequent scripts will execute. + +Some sample scripts are included in the GO and WAR distributions to show you how you can tap into Gitblit with the provided bound variables. Additional implementation details may be specified in the header comment of these examples. -Some sample scripts are included in the GO and WAR distributions to show you how you can tap into Gitblit with the provided bound variables. Additional implementation details may be specified in the header comment of these examples. Hook contributions and improvements are welcome. ### Pre-Receive diff --git a/docs/04_releases.mkd b/docs/04_releases.mkd index 1ec06411..292ff987 100644 --- a/docs/04_releases.mkd +++ b/docs/04_releases.mkd @@ -4,16 +4,18 @@ **%VERSION%** ([go](http://code.google.com/p/gitblit/downloads/detail?name=%GO%) | [war](http://code.google.com/p/gitblit/downloads/detail?name=%WAR%) | [express](http://code.google.com/p/gitblit/downloads/detail?name=%EXPRESS%) | [fedclient](http://code.google.com/p/gitblit/downloads/detail?name=%FEDCLIENT%) | [manager](http://code.google.com/p/gitblit/downloads/detail?name=%MANAGER%) | [api](http://code.google.com/p/gitblit/downloads/detail?name=%API%)) based on [%JGIT%][jgit]   *released %BUILDDATE%* - updated: Gitblit GO is now monolithic like the WAR build. (issue 30) -Either the dependencies are downloaded on first execution OR the dependencies are bundled, either way you would need the dependencies. This change helps adoption of GO in environments without an internet connection or with a restricted connection. +This change helps adoption of GO in environments without an internet connection or with a restricted connection. - added: Groovy 1.8.4 and sample pre- and post- push Groovy hook scripts. Hook scripts can be set per-repository or globally for all repositories. Unfortunately this adds another 6 MB to the 8MB Gitblit package, but it allows for a *very* powerful, flexible, platform-independent hook script mechanism. **New:** *groovy.scriptsFolder = groovy* **New:** *groovy.preReceiveScripts =* **New:** *groovy.postReceiveScripts =* -- added: New key for mailing lists. This is _currently_ used in conjunction with the example *sendemail.groovy* post-receive hook script. +- added: New key for mailing lists. This is used in conjunction with the *sendmail.groovy* hook script. **New:** *mail.mailingLists =* +- added: GitblitUserService. This is a wrapper object for the built-in user service implementations. For those wanting to only implement *custom authentication* it is recommended to subclass GitblitUserService and override the appropriate methods. Going forward, this will insulate customized behavior from new IUserService API and changes in model classes. - added: new default user service implementation: com.gitblit.ConfigUserService (users.conf) -This user service implementation allows for serialization and deserialization of more sophisticated Gitblit User objects and will open the door for more advanced Gitblit features. For upgrading installations, a `users.conf` file will automatically be created for you from your existing `users.properties` file on your first launch of Gitblit. You will have to manually set *realm.userService=users.conf* to switch to the new user service. The original `users.properties` file and it's corresponding implementation are deprecated. +This user service implementation allows for serialization and deserialization of more sophisticated Gitblit User objects and will open the door for more advanced Gitblit features. For upgrading installations, a `users.conf` file will automatically be created for you from your existing `users.properties` file on your first launch of Gitblit. You will have to manually set *realm.userService=users.conf* to switch to the new user service. +The original `users.properties` file and it's corresponding implementation are **deprecated**. **New:** *realm.userService = users.conf* - added: Teams for specifying user-repository access in bulk - added: Gitblit Express bundle to get started running Gitblit on RedHat's OpenShift cloud @@ -25,9 +27,9 @@ This user service implementation allows for serialization and deserialization of **New:** *web.datestampLongFormat = EEEE, MMMM d, yyyy* - fixed: several a bugs in FileUserService related to cleaning up old repository permissions on a rename or delete - added: optional flash-based 1-step *copy to clipboard* of the primary repository url -- added: javascript-based 3-step (click, ctrl+c, enter) *copy to clipboard* of the primary repository url +- added: javascript-based 3-step (click, ctrl+c, enter) *copy to clipboard* of the primary repository url **New:** *web.allowFlashCopyToClipboard = true* -- improved: empty repositories now link to the *empty repository* page which gives some direction to the user for the next step in using Gitblit. This page displays the primary push/clone url of the repository and gives sample syntax for the git command-line client. (issue 31) +- improved: empty repositories now link to a new *empty repository* page which gives some direction to the user for the next step in using Gitblit. This page displays the primary push/clone url of the repository and gives sample syntax for the git command-line client. (issue 31) - improved: unit testing framework has been migrated to JUnit4 syntax and the test suite has been redesigned to run all unit tests, including rpc, federation, and git push/clone tests ### Older Releases diff --git a/groovy/sendemail.groovy b/groovy/sendemail.groovy deleted file mode 100644 index 69e2b93d..00000000 --- a/groovy/sendemail.groovy +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2011 gitblit.com. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import com.gitblit.GitBlit -import com.gitblit.Keys -import com.gitblit.models.RepositoryModel -import com.gitblit.models.UserModel -import com.gitblit.utils.JGitUtils -import org.eclipse.jgit.lib.Repository -import org.eclipse.jgit.lib.Config -import org.eclipse.jgit.revwalk.RevCommit -import org.eclipse.jgit.transport.ReceiveCommand -import org.eclipse.jgit.transport.ReceiveCommand.Result -import org.slf4j.Logger - -/** - * Sample Gitblit Post-Receive Hook: sendemail - * - * The Post-Receive hook is executed AFTER the pushed commits have been applied - * to the Git repository. This is the appropriate point to trigger an - * integration build or to send a notification. - * - * This script is only executed when pushing to *Gitblit*, not to other Git - * tooling you may be using. - * - * If this script is specified in *groovy.postReceiveScripts* of gitblit.properties - * or web.xml then it will be executed by any repository when it receives a - * push. If you choose to share your script then you may have to consider - * tailoring control-flow based on repository access restrictions. - * - * Scripts may also be specified per-repository in the repository settings page. - * Shared scripts will be excluded from this list of available scripts. - * - * This script is dynamically reloaded and it is executed within it's own - * exception handler so it will not crash another script nor crash Gitblit. - * - * If you want this hook script to fail and abort all subsequent scripts in the - * chain, "return false" at the appropriate failure points. - * - * Bound Variables: - * gitblit Gitblit Server com.gitblit.GitBlit - * repository Gitblit Repository com.gitblit.models.RepositoryModel - * user Gitblit User com.gitblit.models.UserModel - * commands JGit commands Collection - * url Base url for Gitblit String - * logger Logger instance org.slf4j.Logger - * - */ - -// Indicate we have started the script -logger.info("sendemail hook triggered by ${user.username} for ${repository.name}") - -/* - * Primitive example email notification with example repository-specific checks. - * This requires the mail settings to be properly configured in Gitblit. - */ - -Repository r = gitblit.getRepository(repository.name) - -// reuse some existing repository config settings, if available -Config config = r.getConfig() -def mailinglist = config.getString('hooks', null, 'mailinglist') -def emailprefix = config.getString('hooks', null, 'emailprefix') - -// set default values -def toAddresses = [] -if (emailprefix == null) -emailprefix = '[Gitblit]' - -if (mailinglist != null) { - def addrs = mailinglist.split('(,|\\s)') - toAddresses.addAll(addrs) -} - -// add all mailing lists defined in gitblit.properties or web.xml -toAddresses.addAll(gitblit.getStrings(Keys.mail.mailingLists)) - -// add all mail recipients for the repository -toAddresses.addAll(repository.mailRecipients) - -// special custom cases -switch(repository.name) { - case 'ex@mple.git': - toAddresses.add 'dev-team@somewhere.com' - toAddresses.add 'qa-team@somewhere.com' - break -} - -// define the summary and commit urls -def repo = repository.name.replace('/', gitblit.getString(Keys.web.forwardSlashCharacter, '/')) -def summaryUrl -def commitUrl -if (gitblit.getBoolean(Keys.web.mountParameters, true)) { - summaryUrl = url + "/summary/$repo" - commitUrl = url + "/commit/$repo/" -} else { - summaryUrl = url + "/summary?r=$repo" - commitUrl = url + "/commit?r=$repo&h=" -} - -// construct a simple text summary of the changes contained in the push -def commitCount = 0 -def changes = '' -def table = { it.authorIdent.name.padRight(25, ' ') + it.shortMessage + "\n$commitUrl" + it.id.name } -for (command in commands) { - def ref = command.refName.substring('refs/heads/'.length()) - switch (command.type) { - case ReceiveCommand.Type.CREATE: - def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) - commitCount += commits.size() - // new branch commits table - changes += "created $ref ($commits.size commits)\n\n" - changes += commits.collect(table).join('\n\n') - changes += '\n' - break - case ReceiveCommand.Type.UPDATE: - def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) - commitCount += commits.size() - // fast-forward branch commits table - changes += "updated $ref ($commits.size commits)\n\n" - changes += commits.collect(table).join('\n\n') - changes += '\n' - break - case ReceiveCommand.Type.UPDATE_NONFASTFORWARD: - def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) - commitCount += commits.size() - // non-fast-forward branch commits table - changes += "updated $ref [NON fast-forward] ($commits.size commits)\n\n" - changes += commits.collect(table).join('\n\n') - changes += '\n' - break - case ReceiveCommand.Type.DELETE: - // deleted branch - changes += "deleted $ref\n\n" - break - default: - break - } -} -// close the repository reference -r.close() - -// tell Gitblit to send the message (Gitblit filters duplicate addresses) -gitblit.sendEmail("$emailprefix $user.username pushed $commitCount commits => $repository.name", "$summaryUrl\n\n$changes", toAddresses) \ No newline at end of file diff --git a/groovy/sendmail.groovy b/groovy/sendmail.groovy new file mode 100644 index 00000000..b43f9dea --- /dev/null +++ b/groovy/sendmail.groovy @@ -0,0 +1,154 @@ +/* + * Copyright 2011 gitblit.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import com.gitblit.GitBlit +import com.gitblit.Keys +import com.gitblit.models.RepositoryModel +import com.gitblit.models.UserModel +import com.gitblit.utils.JGitUtils +import org.eclipse.jgit.lib.Repository +import org.eclipse.jgit.lib.Config +import org.eclipse.jgit.revwalk.RevCommit +import org.eclipse.jgit.transport.ReceiveCommand +import org.eclipse.jgit.transport.ReceiveCommand.Result +import org.slf4j.Logger + +/** + * Sample Gitblit Post-Receive Hook: sendmail + * + * The Post-Receive hook is executed AFTER the pushed commits have been applied + * to the Git repository. This is the appropriate point to trigger an + * integration build or to send a notification. + * + * This script is only executed when pushing to *Gitblit*, not to other Git + * tooling you may be using. + * + * If this script is specified in *groovy.postReceiveScripts* of gitblit.properties + * or web.xml then it will be executed by any repository when it receives a + * push. If you choose to share your script then you may have to consider + * tailoring control-flow based on repository access restrictions. + * + * Scripts may also be specified per-repository in the repository settings page. + * Shared scripts will be excluded from this list of available scripts. + * + * This script is dynamically reloaded and it is executed within it's own + * exception handler so it will not crash another script nor crash Gitblit. + * + * If you want this hook script to fail and abort all subsequent scripts in the + * chain, "return false" at the appropriate failure points. + * + * Bound Variables: + * gitblit Gitblit Server com.gitblit.GitBlit + * repository Gitblit Repository com.gitblit.models.RepositoryModel + * user Gitblit User com.gitblit.models.UserModel + * commands JGit commands Collection + * url Base url for Gitblit String + * logger Logger instance org.slf4j.Logger + * + */ + +// Indicate we have started the script +logger.info("sendmail hook triggered by ${user.username} for ${repository.name}") + +/* + * Primitive email notification. + * This requires the mail settings to be properly configured in Gitblit. + */ + +Repository r = gitblit.getRepository(repository.name) + +// reuse existing repository config settings, if available +Config config = r.getConfig() +def mailinglist = config.getString('hooks', null, 'mailinglist') +def emailprefix = config.getString('hooks', null, 'emailprefix') + +// set default values +def toAddresses = [] +if (emailprefix == null) +emailprefix = '[Gitblit]' + +if (mailinglist != null) { + def addrs = mailinglist.split(/(,|\s)/) + toAddresses.addAll(addrs) +} + +// add all mailing lists defined in gitblit.properties or web.xml +toAddresses.addAll(gitblit.getStrings(Keys.mail.mailingLists)) + +// add all mailing lists for the repository +toAddresses.addAll(repository.mailingLists) + +// define the summary and commit urls +def repo = repository.name.replace('/', gitblit.getString(Keys.web.forwardSlashCharacter, '/')) +def summaryUrl +def commitUrl +if (gitblit.getBoolean(Keys.web.mountParameters, true)) { + summaryUrl = url + "/summary/$repo" + commitUrl = url + "/commit/$repo/" +} else { + summaryUrl = url + "/summary?r=$repo" + commitUrl = url + "/commit?r=$repo&h=" +} + +// construct a simple text summary of the changes contained in the push +def commitCount = 0 +def changes = '' +def table = { it.authorIdent.name.padRight(25, ' ') + it.shortMessage + "\n$commitUrl" + it.id.name } +for (command in commands) { + def ref = command.refName + if (ref.startsWith('refs/heads/')) { + ref = command.refName.substring('refs/heads/'.length()) + } else if (ref.startsWith('refs/tags/')) { + ref = command.refName.substring('refs/tags/'.length()) + } + + switch (command.type) { + case ReceiveCommand.Type.CREATE: + def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) + commitCount += commits.size() + // new branch commits table + changes += "$ref created ($commits.size commits)\n\n" + changes += commits.collect(table).join('\n\n') + changes += '\n' + break + case ReceiveCommand.Type.UPDATE: + def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) + commitCount += commits.size() + // fast-forward branch commits table + changes += "$ref updated ($commits.size commits)\n\n" + changes += commits.collect(table).join('\n\n') + changes += '\n' + break + case ReceiveCommand.Type.UPDATE_NONFASTFORWARD: + def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name) + commitCount += commits.size() + // non-fast-forward branch commits table + changes += "$ref updated [NON fast-forward] ($commits.size commits)\n\n" + changes += commits.collect(table).join('\n\n') + changes += '\n' + break + case ReceiveCommand.Type.DELETE: + // deleted branch + changes += "$ref deleted\n\n" + break + default: + break + } +} +// close the repository reference +r.close() + +// tell Gitblit to send the message (Gitblit filters duplicate addresses) +gitblit.sendMail("$emailprefix $user.username pushed $commitCount commits => $repository.name", "$summaryUrl\n\n$changes", toAddresses) \ No newline at end of file diff --git a/resources/bootstrap.gb.css b/resources/bootstrap.gb.css index 6eeec389..08951f2a 100644 --- a/resources/bootstrap.gb.css +++ b/resources/bootstrap.gb.css @@ -690,6 +690,10 @@ td.treeLinks { width: 13em; } +span.help-inline { + color: #777; +} + span.metricsTitle { font-size: 2em; } diff --git a/src/com/gitblit/FederationPullExecutor.java b/src/com/gitblit/FederationPullExecutor.java index c3b7d8b8..2976c402 100644 --- a/src/com/gitblit/FederationPullExecutor.java +++ b/src/com/gitblit/FederationPullExecutor.java @@ -113,7 +113,7 @@ public class FederationPullExecutor implements Runnable { String message = "Federation pull of " + registration.name + " @ " + registration.url + " is now at " + is.name(); GitBlit.self() - .sendEmailToAdministrators( + .sendMailToAdministrators( "Pull Status of " + registration.name + " is " + is.name(), message); } diff --git a/src/com/gitblit/GitBlit.java b/src/com/gitblit/GitBlit.java index f0122791..835aa132 100644 --- a/src/com/gitblit/GitBlit.java +++ b/src/com/gitblit/GitBlit.java @@ -743,8 +743,8 @@ public class GitBlit implements ServletContextListener { "gitblit", null, "preReceiveScript"))); model.postReceiveScripts = new ArrayList(Arrays.asList(config.getStringList( "gitblit", null, "postReceiveScript"))); - model.mailRecipients = new ArrayList(Arrays.asList(config.getStringList( - "gitblit", null, "mailRecipient"))); + model.mailingLists = new ArrayList(Arrays.asList(config.getStringList( + "gitblit", null, "mailingList"))); } r.close(); return model; @@ -971,8 +971,8 @@ public class GitBlit implements ServletContextListener { config.setStringList("gitblit", null, "postReceiveScript", repository.postReceiveScripts); } - if (repository.mailRecipients != null) { - config.setStringList("gitblit", null, "mailRecipient", repository.mailRecipients); + if (repository.mailingLists != null) { + config.setStringList("gitblit", null, "mailingList", repository.mailingLists); } try { config.save(); @@ -1485,7 +1485,7 @@ public class GitBlit implements ServletContextListener { * @param subject * @param message */ - public void sendEmailToAdministrators(String subject, String message) { + public void sendMailToAdministrators(String subject, String message) { try { Message mail = mailExecutor.createMessageForAdministrators(); if (mail != null) { @@ -1505,8 +1505,8 @@ public class GitBlit implements ServletContextListener { * @param message * @param toAddresses */ - public void sendEmail(String subject, String message, ArrayList toAddresses) { - this.sendEmail(subject, message, toAddresses.toArray(new String[0])); + public void sendMail(String subject, String message, ArrayList toAddresses) { + this.sendMail(subject, message, toAddresses.toArray(new String[0])); } /** @@ -1516,7 +1516,7 @@ public class GitBlit implements ServletContextListener { * @param message * @param toAddresses */ - public void sendEmail(String subject, String message, String... toAddresses) { + public void sendMail(String subject, String message, String... toAddresses) { try { Message mail = mailExecutor.createMessage(toAddresses); if (mail != null) { @@ -1634,11 +1634,7 @@ public class GitBlit implements ServletContextListener { loginService = (IUserService) realmClass.newInstance(); } } catch (Throwable t) { - loginService = new UserServiceWrapper() { - @Override - public void setupService(IStoredSettings settings) { - } - }; + loginService = new GitblitUserService(); } setUserService(loginService); mailExecutor = new MailExecutor(settings); diff --git a/src/com/gitblit/GitblitUserService.java b/src/com/gitblit/GitblitUserService.java new file mode 100644 index 00000000..97e1a40c --- /dev/null +++ b/src/com/gitblit/GitblitUserService.java @@ -0,0 +1,217 @@ +/* + * Copyright 2011 gitblit.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.gitblit; + +import java.io.File; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.gitblit.models.TeamModel; +import com.gitblit.models.UserModel; + +/** + * This class wraps the default user service and is recommended as the starting + * point for custom user service implementations. + * + * This does seem a little convoluted, but the idea is to allow IUserService to + * evolve with new methods and implementations without breaking custom + * authentication implementations. + * + * The most common implementation of a custom IUserService is to only override + * authentication and then delegate all other functionality to one of Gitblit's + * user services. This class optimizes that use-case. + * + * Extending GitblitUserService allows for authentication customization without + * having to keep-up-with IUSerService API changes. + * + * @author James Moger + * + */ +public class GitblitUserService implements IUserService { + + protected IUserService serviceImpl; + + private final Logger logger = LoggerFactory.getLogger(GitblitUserService.class); + + public GitblitUserService() { + } + + @Override + public void setup(IStoredSettings settings) { + File realmFile = GitBlit.getFileOrFolder(Keys.realm.userService, "users.conf"); + serviceImpl = createUserService(realmFile); + } + + @SuppressWarnings("deprecation") + protected IUserService createUserService(File realmFile) { + IUserService service = null; + if (realmFile.getName().toLowerCase().endsWith(".properties")) { + // v0.5.0 - v0.7.0 properties-based realm file + service = new FileUserService(realmFile); + } else if (realmFile.getName().toLowerCase().endsWith(".conf")) { + // v0.8.0+ config-based realm file + service = new ConfigUserService(realmFile); + } + + assert service != null; + + if (realmFile.exists()) { + // Create the Administrator account for a new realm file + try { + realmFile.createNewFile(); + } catch (IOException x) { + logger.error(MessageFormat.format("COULD NOT CREATE REALM FILE {0}!", realmFile), x); + } + UserModel admin = new UserModel("admin"); + admin.password = "admin"; + admin.canAdmin = true; + admin.excludeFromFederation = true; + service.updateUserModel(admin); + } + + if (service instanceof FileUserService) { + // automatically create a users.conf realm file from the original + // users.properties file + File usersConfig = new File(realmFile.getParentFile(), "users.conf"); + if (!usersConfig.exists()) { + logger.info(MessageFormat.format("Automatically creating {0} based on {1}", + usersConfig.getAbsolutePath(), realmFile.getAbsolutePath())); + ConfigUserService configService = new ConfigUserService(usersConfig); + for (String username : serviceImpl.getAllUsernames()) { + UserModel userModel = serviceImpl.getUserModel(username); + configService.updateUserModel(userModel); + } + } + // issue suggestion about switching to users.conf + logger.warn("Please consider using \"users.conf\" instead of the deprecated \"users.properties\" file"); + } + return service; + } + + @Override + public boolean supportsCookies() { + return serviceImpl.supportsCookies(); + } + + @Override + public char[] getCookie(UserModel model) { + return serviceImpl.getCookie(model); + } + + @Override + public UserModel authenticate(char[] cookie) { + return serviceImpl.authenticate(cookie); + } + + @Override + public UserModel authenticate(String username, char[] password) { + return serviceImpl.authenticate(username, password); + } + + @Override + public UserModel getUserModel(String username) { + return serviceImpl.getUserModel(username); + } + + @Override + public boolean updateUserModel(UserModel model) { + return serviceImpl.updateUserModel(model); + } + + @Override + public boolean updateUserModel(String username, UserModel model) { + return serviceImpl.updateUserModel(username, model); + } + + @Override + public boolean deleteUserModel(UserModel model) { + return serviceImpl.deleteUserModel(model); + } + + @Override + public boolean deleteUser(String username) { + return serviceImpl.deleteUser(username); + } + + @Override + public List getAllUsernames() { + return serviceImpl.getAllUsernames(); + } + + @Override + public List getAllTeamNames() { + return serviceImpl.getAllTeamNames(); + } + + @Override + public List getTeamnamesForRepositoryRole(String role) { + return serviceImpl.getTeamnamesForRepositoryRole(role); + } + + @Override + public boolean setTeamnamesForRepositoryRole(String role, List teamnames) { + return serviceImpl.setTeamnamesForRepositoryRole(role, teamnames); + } + + @Override + public TeamModel getTeamModel(String teamname) { + return serviceImpl.getTeamModel(teamname); + } + + @Override + public boolean updateTeamModel(TeamModel model) { + return serviceImpl.updateTeamModel(model); + } + + @Override + public boolean updateTeamModel(String teamname, TeamModel model) { + return serviceImpl.updateTeamModel(teamname, model); + } + + @Override + public boolean deleteTeamModel(TeamModel model) { + return serviceImpl.deleteTeamModel(model); + } + + @Override + public boolean deleteTeam(String teamname) { + return serviceImpl.deleteTeam(teamname); + } + + @Override + public List getUsernamesForRepositoryRole(String role) { + return serviceImpl.getUsernamesForRepositoryRole(role); + } + + @Override + public boolean setUsernamesForRepositoryRole(String role, List usernames) { + return serviceImpl.setUsernamesForRepositoryRole(role, usernames); + } + + @Override + public boolean renameRepositoryRole(String oldRole, String newRole) { + return serviceImpl.renameRepositoryRole(oldRole, newRole); + } + + @Override + public boolean deleteRepositoryRole(String role) { + return serviceImpl.deleteRepositoryRole(role); + } +} diff --git a/src/com/gitblit/UserServiceWrapper.java b/src/com/gitblit/UserServiceWrapper.java deleted file mode 100644 index 88eab488..00000000 --- a/src/com/gitblit/UserServiceWrapper.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2011 gitblit.com. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.gitblit; - -import java.io.File; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.gitblit.models.TeamModel; -import com.gitblit.models.UserModel; - -/** - * This class wraps the default user service and is recommended as the starting - * point for custom user service implementations. - * - * This does seem a little convoluted, but the idea is to allow IUserService to - * evolve and be replaced without hampering custom implementations. - * - * The most common need for a custom IUserService is to override authentication - * and then delegate to one of Gitblit's user services. Subclassing this allows - * for authentication customization without having to keep-up-with IUSerService - * API changes. - * - * @author James Moger - * - */ -public abstract class UserServiceWrapper implements IUserService { - - protected IUserService defaultService; - - private final Logger logger = LoggerFactory.getLogger(UserServiceWrapper.class); - - public UserServiceWrapper() { - } - - @SuppressWarnings("deprecation") - @Override - public final void setup(IStoredSettings settings) { - File realmFile = GitBlit.getFileOrFolder(Keys.realm.userService, "users.conf"); - if (realmFile.exists()) { - // load the existing realm file - if (realmFile.getName().toLowerCase().endsWith(".properties")) { - // load the v0.5.0 - v0.7.0 properties-based realm file - defaultService = new FileUserService(realmFile); - - // automatically create a users.conf realm file from the - // original users.properties file - File usersConfig = new File(realmFile.getParentFile(), "users.conf"); - if (!usersConfig.exists()) { - logger.info(MessageFormat.format("Automatically creating {0} based on {1}", - usersConfig.getAbsolutePath(), realmFile.getAbsolutePath())); - ConfigUserService configService = new ConfigUserService(usersConfig); - for (String username : defaultService.getAllUsernames()) { - UserModel userModel = defaultService.getUserModel(username); - configService.updateUserModel(userModel); - } - } - - // issue suggestion about switching to users.conf - logger.warn("Please consider using \"users.conf\" instead of the deprecated \"users.properties\" file"); - } else if (realmFile.getName().toLowerCase().endsWith(".conf")) { - // load the config-based realm file - defaultService = new ConfigUserService(realmFile); - } - } else { - // Create a new realm file and add the default admin - // account. This is necessary for bootstrapping a dynamic - // environment like running on a cloud service. - // As of v0.8.0 the default realm file is ConfigUserService. - try { - realmFile = GitBlit.getFileOrFolder(Keys.realm.userService, "users.conf"); - realmFile.createNewFile(); - defaultService = new ConfigUserService(realmFile); - UserModel admin = new UserModel("admin"); - admin.password = "admin"; - admin.canAdmin = true; - admin.excludeFromFederation = true; - defaultService.updateUserModel(admin); - } catch (IOException x) { - logger.error(MessageFormat.format("COULD NOT CREATE REALM FILE {0}!", realmFile), x); - } - } - - // call subclass setup - setupService(settings); - } - - /** - * Subclasses must implement this method. - * - * @param settings - */ - public abstract void setupService(IStoredSettings settings); - - @Override - public boolean supportsCookies() { - return defaultService.supportsCookies(); - } - - @Override - public char[] getCookie(UserModel model) { - return defaultService.getCookie(model); - } - - @Override - public UserModel authenticate(char[] cookie) { - return defaultService.authenticate(cookie); - } - - @Override - public UserModel authenticate(String username, char[] password) { - return defaultService.authenticate(username, password); - } - - @Override - public UserModel getUserModel(String username) { - return defaultService.getUserModel(username); - } - - @Override - public boolean updateUserModel(UserModel model) { - return defaultService.updateUserModel(model); - } - - @Override - public boolean updateUserModel(String username, UserModel model) { - return defaultService.updateUserModel(username, model); - } - - @Override - public boolean deleteUserModel(UserModel model) { - return defaultService.deleteUserModel(model); - } - - @Override - public boolean deleteUser(String username) { - return defaultService.deleteUser(username); - } - - @Override - public List getAllUsernames() { - return defaultService.getAllUsernames(); - } - - @Override - public List getAllTeamNames() { - return defaultService.getAllTeamNames(); - } - - @Override - public List getTeamnamesForRepositoryRole(String role) { - return defaultService.getTeamnamesForRepositoryRole(role); - } - - @Override - public boolean setTeamnamesForRepositoryRole(String role, List teamnames) { - return defaultService.setTeamnamesForRepositoryRole(role, teamnames); - } - - @Override - public TeamModel getTeamModel(String teamname) { - return defaultService.getTeamModel(teamname); - } - - @Override - public boolean updateTeamModel(TeamModel model) { - return defaultService.updateTeamModel(model); - } - - @Override - public boolean updateTeamModel(String teamname, TeamModel model) { - return defaultService.updateTeamModel(teamname, model); - } - - @Override - public boolean deleteTeamModel(TeamModel model) { - return defaultService.deleteTeamModel(model); - } - - @Override - public boolean deleteTeam(String teamname) { - return defaultService.deleteTeam(teamname); - } - - @Override - public List getUsernamesForRepositoryRole(String role) { - return defaultService.getUsernamesForRepositoryRole(role); - } - - @Override - public boolean setUsernamesForRepositoryRole(String role, List usernames) { - return defaultService.setUsernamesForRepositoryRole(role, usernames); - } - - @Override - public boolean renameRepositoryRole(String oldRole, String newRole) { - return defaultService.renameRepositoryRole(oldRole, newRole); - } - - @Override - public boolean deleteRepositoryRole(String role) { - return defaultService.deleteRepositoryRole(role); - } -} diff --git a/src/com/gitblit/client/EditRepositoryDialog.java b/src/com/gitblit/client/EditRepositoryDialog.java index 44b6fc6a..b7278623 100644 --- a/src/com/gitblit/client/EditRepositoryDialog.java +++ b/src/com/gitblit/client/EditRepositoryDialog.java @@ -89,7 +89,7 @@ public class EditRepositoryDialog extends JDialog { private JCheckBox isFrozen; - private JTextField mailRecipientsField; + private JTextField mailingListsField; private JComboBox accessRestriction; @@ -164,8 +164,8 @@ public class EditRepositoryDialog extends JDialog { anRepository.skipSummaryMetrics); isFrozen = new JCheckBox(Translation.get("gb.isFrozenDescription"), anRepository.isFrozen); - mailRecipientsField = new JTextField(anRepository.mailRecipients == null ? "" - : StringUtils.flattenStrings(anRepository.mailRecipients, " "), 50); + mailingListsField = new JTextField(anRepository.mailingLists == null ? "" + : StringUtils.flattenStrings(anRepository.mailingLists, " "), 50); accessRestriction = new JComboBox(AccessRestrictionType.values()); accessRestriction.setRenderer(new AccessRestrictionRenderer()); @@ -198,7 +198,7 @@ public class EditRepositoryDialog extends JDialog { fieldsPanel .add(newFieldPanel(Translation.get("gb.skipSummaryMetrics"), skipSummaryMetrics)); fieldsPanel.add(newFieldPanel(Translation.get("gb.isFrozen"), isFrozen)); - fieldsPanel.add(newFieldPanel(Translation.get("gb.mailRecipients"), mailRecipientsField)); + fieldsPanel.add(newFieldPanel(Translation.get("gb.mailingLists"), mailingListsField)); usersPalette = new JPalette(); JPanel accessPanel = new JPanel(new BorderLayout(5, 5)); @@ -371,8 +371,17 @@ public class EditRepositoryDialog extends JDialog { repository.skipSummaryMetrics = skipSummaryMetrics.isSelected(); repository.isFrozen = isFrozen.isSelected(); - repository.mailRecipients = StringUtils.getStringsFromValue(mailRecipientsField.getText() - .trim(), " "); + String ml = mailingListsField.getText(); + if (!StringUtils.isEmpty(ml)) { + Set list = new HashSet(); + for (String address : ml.split("(,|\\s)")) { + if (StringUtils.isEmpty(address)) { + continue; + } + list.add(address.toLowerCase()); + } + repository.mailingLists = new ArrayList(list); + } repository.accessRestriction = (AccessRestrictionType) accessRestriction.getSelectedItem(); repository.federationStrategy = (FederationStrategy) federationStrategy.getSelectedItem(); diff --git a/src/com/gitblit/models/RepositoryModel.java b/src/com/gitblit/models/RepositoryModel.java index fc1de8ac..7e33ab06 100644 --- a/src/com/gitblit/models/RepositoryModel.java +++ b/src/com/gitblit/models/RepositoryModel.java @@ -57,7 +57,7 @@ public class RepositoryModel implements Serializable, Comparable preReceiveScripts; public List postReceiveScripts; - public List mailRecipients; + public List mailingLists; public RepositoryModel() { this("", "", "", new Date(0)); diff --git a/src/com/gitblit/wicket/GitBlitWebApp.properties b/src/com/gitblit/wicket/GitBlitWebApp.properties index 4eeb887c..c0b0010d 100644 --- a/src/com/gitblit/wicket/GitBlitWebApp.properties +++ b/src/com/gitblit/wicket/GitBlitWebApp.properties @@ -196,8 +196,8 @@ gb.newTeam = new team gb.permittedTeams = permitted teams gb.emptyRepository = empty repository gb.repositoryUrl = repository url -gb.mailRecipients = mail recipients -gb.mailRecipientsDescription = space-delimited, used by sendemail Groovy hook +gb.mailingLists = mailing lists +gb.mailingListsDescription = used by the sendmail hook gb.preReceiveScripts = pre-receive scripts gb.postReceiveScripts = post-receive scripts -gb.groovyHookScripts = hook scripts \ No newline at end of file +gb.hookScripts = hook scripts \ No newline at end of file diff --git a/src/com/gitblit/wicket/pages/EditRepositoryPage.html b/src/com/gitblit/wicket/pages/EditRepositoryPage.html index 3e221225..310f59e5 100644 --- a/src/com/gitblit/wicket/pages/EditRepositoryPage.html +++ b/src/com/gitblit/wicket/pages/EditRepositoryPage.html @@ -11,18 +11,18 @@ - + - - - - - - - - - + + + + + + + + + @@ -33,7 +33,7 @@ - +

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 
diff --git a/src/com/gitblit/wicket/pages/EditRepositoryPage.java b/src/com/gitblit/wicket/pages/EditRepositoryPage.java index 492addc3..f5950539 100644 --- a/src/com/gitblit/wicket/pages/EditRepositoryPage.java +++ b/src/com/gitblit/wicket/pages/EditRepositoryPage.java @@ -19,9 +19,11 @@ import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.wicket.PageParameters; import org.apache.wicket.extensions.markup.html.form.palette.Palette; @@ -55,7 +57,7 @@ public class EditRepositoryPage extends RootSubPage { private boolean isAdmin; - private IModel mailRecipients; + private IModel mailingLists; public EditRepositoryPage() { // create constructor @@ -118,7 +120,8 @@ public class EditRepositoryPage extends RootSubPage { } final Palette preReceivePalette = new Palette("preReceiveScripts", new ListModel(preReceiveScripts), new CollectionModel(GitBlit - .self().getAvailableScripts()), new ChoiceRenderer("", ""), 12, true); + .self().getAvailableScripts()), new ChoiceRenderer("", ""), 12, + true); // post-receive palette if (repositoryModel.postReceiveScripts != null) { @@ -126,7 +129,8 @@ public class EditRepositoryPage extends RootSubPage { } final Palette postReceivePalette = new Palette("postReceiveScripts", new ListModel(postReceiveScripts), new CollectionModel(GitBlit - .self().getAvailableScripts()), new ChoiceRenderer("", ""), 12, true); + .self().getAvailableScripts()), new ChoiceRenderer("", ""), 12, + true); CompoundPropertyModel model = new CompoundPropertyModel( repositoryModel); @@ -191,11 +195,17 @@ public class EditRepositoryPage extends RootSubPage { } } - // set mail recipients - String ml = mailRecipients.getObject(); + // set mailing lists + String ml = mailingLists.getObject(); if (!StringUtils.isEmpty(ml)) { - List list = StringUtils.getStringsFromValue(ml.trim(), " "); - repositoryModel.mailRecipients = list; + Set list = new HashSet(); + for (String address : ml.split("(,|\\s)")) { + if (StringUtils.isEmpty(address)) { + continue; + } + list.add(address.toLowerCase()); + } + repositoryModel.mailingLists = new ArrayList(list); } // pre-receive scripts @@ -275,9 +285,9 @@ public class EditRepositoryPage extends RootSubPage { form.add(new CheckBox("showReadme")); form.add(new CheckBox("skipSizeCalculation")); form.add(new CheckBox("skipSummaryMetrics")); - mailRecipients = new Model(repositoryModel.mailRecipients == null ? "" - : StringUtils.flattenStrings(repositoryModel.mailRecipients, " ")); - form.add(new TextField("mailRecipients", mailRecipients)); + mailingLists = new Model(repositoryModel.mailingLists == null ? "" + : StringUtils.flattenStrings(repositoryModel.mailingLists, " ")); + form.add(new TextField("mailingLists", mailingLists)); form.add(usersPalette); form.add(teamsPalette); form.add(federationSetsPalette); diff --git a/src/com/gitblit/wicket/pages/EditTeamPage.html b/src/com/gitblit/wicket/pages/EditTeamPage.html index 84a53e3c..614f0aa1 100644 --- a/src/com/gitblit/wicket/pages/EditTeamPage.html +++ b/src/com/gitblit/wicket/pages/EditTeamPage.html @@ -9,13 +9,13 @@
- + - +


 
 
diff --git a/src/com/gitblit/wicket/pages/EditUserPage.html b/src/com/gitblit/wicket/pages/EditUserPage.html index 978393bb..319a2b65 100644 --- a/src/com/gitblit/wicket/pages/EditUserPage.html +++ b/src/com/gitblit/wicket/pages/EditUserPage.html @@ -9,17 +9,17 @@
- + - - + + - +
 
 
 
 


 
 
diff --git a/src/com/gitblit/wicket/panels/RepositoriesPanel.java b/src/com/gitblit/wicket/panels/RepositoriesPanel.java index fc90316f..118ad6da 100644 --- a/src/com/gitblit/wicket/panels/RepositoriesPanel.java +++ b/src/com/gitblit/wicket/panels/RepositoriesPanel.java @@ -25,6 +25,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder; import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; @@ -157,7 +158,7 @@ public class RepositoriesPanel extends BasePanel { } // repository swatch - Label swatch = new Label("repositorySwatch", " "); + Component swatch = new Label("repositorySwatch", " ").setEscapeModelStrings(false); WicketUtils.setCssBackground(swatch, entry.name); row.add(swatch); swatch.setVisible(showSwatch); diff --git a/test-gitblit.properties b/test-gitblit.properties index 5fcc7382..a815198b 100644 --- a/test-gitblit.properties +++ b/test-gitblit.properties @@ -7,7 +7,7 @@ git.searchRepositoriesSubfolders = true git.enableGitServlet = true groovy.scriptsFolder = groovy groovy.preReceiveScripts = blockpush -groovy.postReceiveScripts = sendemail jenkins +groovy.postReceiveScripts = sendmail jenkins web.authenticateViewPages = false web.authenticateAdminPages = true web.allowCookieAuthentication = true