Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to create and find Repos that are nested #876

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
8 changes: 4 additions & 4 deletions Bonobo.Git.Server.Test/UnitTests/GitAuthorizeAttributeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ public class GitAuthorizeAttributeTest
[TestMethod]
public void GetRepoPathTest()
{
var repo = GitAuthorizeAttribute.GetRepoPath("/other/test.git/info/refs", "/other");
Assert.AreEqual("test", repo);
repo = GitAuthorizeAttribute.GetRepoPath("/test.git/info/refs", "/");
Assert.AreEqual("test", repo);
var repo = GitAuthorizeAttribute.GetRepoPath("/other/test.git/info/refs", "/other", false);
Assert.AreEqual(@"\test.git", repo);
repo = GitAuthorizeAttribute.GetRepoPath("/test.git/info/refs", "/", false);
Assert.AreEqual("test.git", repo);
}
}
}
20 changes: 19 additions & 1 deletion Bonobo.Git.Server/App_GlobalResources/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Bonobo.Git.Server/App_GlobalResources/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -957,4 +957,10 @@ The regular C# string formatting rules apply: To get {} in your link you need to
<data name="Settings_Global_SiteCssUrl_Hint" xml:space="preserve">
<value>URL to a CSS file to use for the site. Site-relative (~) paths are supported.</value>
</data>
<data name="Repository_Create_NameExtensionFailure" xml:space="preserve">
<value>Must have an extension of .git</value>
</data>
<data name="Repository_Create_IsAControllerNameFailure" xml:space="preserve">
<value>Invalid root repo folder. Choose a different folder name.</value>
</data>
</root>
47 changes: 47 additions & 0 deletions Bonobo.Git.Server/App_Start/DoesControllerExistConstraint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Routing;

namespace Bonobo.Git.Server.App_Start
{
/// <summary>
/// Checks if controller and action is defined
/// </summary>
public class DoesControllerExistConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
var action = values["action"] as string;
var controller = values["controller"] as string;

return DoesControllerExist(controller, action);
}
else
return true;
}

public static bool DoesControllerExist(string controller, string action = null)
{
if (controller is null)
return false;

var controllerFullName = string.Format("Bonobo.Git.Server.Controllers.{0}Controller", controller);

var cont = Assembly.GetExecutingAssembly().GetType(controllerFullName);

try
{
return cont != null && (!string.IsNullOrEmpty(action) ? cont.GetMethod(action) != null : true);
}
catch(AmbiguousMatchException)
{
return true;
}
}
}
}
35 changes: 13 additions & 22 deletions Bonobo.Git.Server/App_Start/RouteConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,6 @@ public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("SecureInfoRefs",
"{repositoryName}.git/info/refs",
new { controller = "Git", action = "SecureGetInfoRefs" },
new { method = new HttpMethodConstraint("GET") });

routes.MapRoute("SecureUploadPack",
"{repositoryName}.git/git-upload-pack",
new { controller = "Git", action = "SecureUploadPack" },
new { method = new HttpMethodConstraint("POST") });

routes.MapRoute("SecureReceivePack",
"{repositoryName}.git/git-receive-pack",
new { controller = "Git", action = "SecureReceivePack" },
new { method = new HttpMethodConstraint("POST") });

routes.MapRoute("GitBaseUrl",
"{repositoryName}.git",
new { controller = "Git", action = "GitUrl" },
new { method = new HttpMethodConstraint("GET") });

routes.MapRoute("IndexRoute",
"{controller}/Index/",
new { action = "Index" });
Expand Down Expand Up @@ -90,11 +70,22 @@ public static void RegisterRoutes(RouteCollection routes)

routes.MapRoute("RepoCommits",
"Repository/Commits/{id}",
new { controller = "Repository", action = "Commits", id = string.Empty});
new { controller = "Repository", action = "Commits", id = string.Empty });

routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = String.Empty });
new { controller = "Home", action = "Index", id = String.Empty },
new { action = new DoesControllerExistConstraint() }); //Route constraints

routes.MapRoute("GitBaseUrl",
"{repositoryName}",
new { controller = "Git", action = "GitUrl" },
new { method = new HttpMethodConstraint("GET") });

routes.MapRoute(
"GitRepoRouting",
"{*url}",
new { controller = "Git", action = "Index" });

routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

Expand Down
2 changes: 1 addition & 1 deletion Bonobo.Git.Server/Attributes/FileNameAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public override bool IsValid(object value)
{
if (value != null)
{
return value.ToString().IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
return value.ToString().IndexOfAny(Path.GetInvalidPathChars()) == -1;
}

return base.IsValid(null);
Expand Down
31 changes: 28 additions & 3 deletions Bonobo.Git.Server/Attributes/GitAuthorizeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
using Microsoft.Practices.Unity;
using Bonobo.Git.Server.Helpers;
using Serilog;
using System.Linq;
using System.IO;
using Bonobo.Git.Server.Configuration;

namespace Bonobo.Git.Server
{
Expand All @@ -26,10 +29,31 @@ public class GitAuthorizeAttribute : AuthorizeAttribute
[Dependency]
public IRepositoryRepository RepositoryRepository { get; set; }

public static string GetRepoPath(string path, string applicationPath)
public static string GetRepoPath(string url, string applicationPath, bool checkDirectory=true)
{
var repo = path.Replace(applicationPath, "").Replace("/","");
return repo.Substring(0, repo.IndexOf(".git"));
var gitStartIndex = url.IndexOf(".git");
if (gitStartIndex >= 0)
{
var repositoryPath = url.Substring(0, gitStartIndex + 4);

repositoryPath = applicationPath.Length ==1 ? repositoryPath.TrimStart(applicationPath.ToCharArray()) : repositoryPath.Replace(applicationPath, "");

repositoryPath = repositoryPath.Replace('/', '\\').TrimEnd('\\');

if (checkDirectory)
{
string path = Path.Combine(UserConfiguration.Current.Repositories, repositoryPath);

if (Directory.Exists(path))
{
return repositoryPath;
}
}
else
return repositoryPath;
}

return null;
}

public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
Expand All @@ -42,6 +66,7 @@ public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterC
HttpContextBase httpContext = filterContext.HttpContext;

string incomingRepoName = GetRepoPath(httpContext.Request.Path, httpContext.Request.ApplicationPath);

string repoName = Repository.NormalizeRepositoryName(incomingRepoName, RepositoryRepository);

// Add header to prevent redirection to login page even if we fail auth later (see IAuthenticationProvider.Configure)
Expand Down
17 changes: 11 additions & 6 deletions Bonobo.Git.Server/Bonobo.Git.Server.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\LibGit2Sharp.NativeBinaries.2.0.306\build\net46\LibGit2Sharp.NativeBinaries.props" Condition="Exists('..\packages\LibGit2Sharp.NativeBinaries.2.0.306\build\net46\LibGit2Sharp.NativeBinaries.props')" />
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.5\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.5\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.2.2.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.2.2.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\LibGit2Sharp.NativeBinaries.1.0.164\build\LibGit2Sharp.NativeBinaries.props" Condition="Exists('..\packages\LibGit2Sharp.NativeBinaries.1.0.164\build\LibGit2Sharp.NativeBinaries.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
Expand Down Expand Up @@ -47,6 +47,8 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<IncludeIisSettings>true</IncludeIisSettings>
<LegacyPublishPropertiesPageEnabled>true</LegacyPublishPropertiesPageEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
Expand Down Expand Up @@ -82,9 +84,9 @@
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="LibGit2Sharp, Version=0.23.1.0, Culture=neutral, PublicKeyToken=7cbde695407f0333, processorArchitecture=MSIL">
<HintPath>..\packages\LibGit2Sharp.0.23.1\lib\net40\LibGit2Sharp.dll</HintPath>
<Private>True</Private>
<Reference Include="LibGit2Sharp, Version=0.26.0.0, Culture=neutral, PublicKeyToken=7cbde695407f0333, processorArchitecture=MSIL">
<HintPath>..\packages\LibGit2Sharp.0.26.2\lib\net46\LibGit2Sharp.dll</HintPath>
<SpecificVersion>False</SpecificVersion>
</Reference>
<Reference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.5\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll</HintPath>
Expand Down Expand Up @@ -272,6 +274,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="AnonymousComparer.cs" />
<Compile Include="App_Start\DoesControllerExistConstraint.cs" />
<Compile Include="Attributes\AllViewsAttribute.cs" />
<Compile Include="Attributes\FileExtensionsCustom.cs" />
<Compile Include="Attributes\RepositoryNameNormalizerAttribute.cs" />
Expand Down Expand Up @@ -703,7 +706,9 @@
<EmbeddedResource Include="App_GlobalResources\Resources.cs-CZ.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.de-DE.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.es-ES.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.da-DK.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.da-DK.resx">
<SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="App_GlobalResources\Resources.fr-FR.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.ja-JP.resx" />
<EmbeddedResource Include="App_GlobalResources\Resources.pl-PL.resx" />
Expand Down Expand Up @@ -769,10 +774,10 @@ xcopy/s /y /d "$(SolutionDir)packages\LibGit2Sharp.0.21.0.176\lib\net40\NativeBi
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\LibGit2Sharp.NativeBinaries.1.0.164\build\LibGit2Sharp.NativeBinaries.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\LibGit2Sharp.NativeBinaries.1.0.164\build\LibGit2Sharp.NativeBinaries.props'))" />
<Error Condition="!Exists('..\packages\System.Data.SQLite.Core.1.0.104.0\build\net46\System.Data.SQLite.Core.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\System.Data.SQLite.Core.1.0.104.0\build\net46\System.Data.SQLite.Core.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.2.2.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.2.2.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.5\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.5\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
<Error Condition="!Exists('..\packages\LibGit2Sharp.NativeBinaries.2.0.306\build\net46\LibGit2Sharp.NativeBinaries.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\LibGit2Sharp.NativeBinaries.2.0.306\build\net46\LibGit2Sharp.NativeBinaries.props'))" />
</Target>
<Import Project="..\packages\System.Data.SQLite.Core.1.0.104.0\build\net46\System.Data.SQLite.Core.targets" Condition="Exists('..\packages\System.Data.SQLite.Core.1.0.104.0\build\net46\System.Data.SQLite.Core.targets')" />
</Project>
2 changes: 2 additions & 0 deletions Bonobo.Git.Server/Configuration/AuthenticationSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ public static class AuthenticationSettings
public static string MembershipService { get; private set; }
public static string AuthenticationProvider { get; private set; }
public static bool ImportWindowsAuthUsersAsAdmin { get; private set; }
public static string EmailDomain { get; }
public static bool DemoModeActive { get; private set; }

static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
AuthenticationProvider = ConfigurationManager.AppSettings["AuthenticationProvider"];
ImportWindowsAuthUsersAsAdmin = Convert.ToBoolean(ConfigurationManager.AppSettings["ImportWindowsAuthUsersAsAdmin"]);
EmailDomain = ConfigurationManager.AppSettings["EmailDomain"];
DemoModeActive = Convert.ToBoolean(ConfigurationManager.AppSettings["demoModeActive"]);
}
}
Expand Down
13 changes: 10 additions & 3 deletions Bonobo.Git.Server/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,10 @@ public ActionResult Edit(UserEditModel model)
public ActionResult CreateADUser()
{
var efms = MembershipService as EFMembershipService;

if ((!Request.IsAuthenticated) || efms == null)
{
Log.Warning("CreateADUser: can't run IsAuth: {IsAuth}, MemServ {MemServ}",
Log.Warning("CreateADUser: can't run IsAuth: {IsAuth}, MemServ {MemServ}",
Request.IsAuthenticated,
MembershipService.GetType());
return RedirectToAction("Unauthorized", "Home");
Expand All @@ -201,6 +201,13 @@ public ActionResult CreateADUser()
if (adUser != null)
{
var userId = adUser.Guid.GetValueOrDefault(Guid.NewGuid());

if (string.IsNullOrEmpty(adUser.EmailAddress))
{
var username = credentials.Split('\\')[1];
adUser.EmailAddress = $"{username}@{AuthenticationSettings.EmailDomain}";
}

if (MembershipService.CreateUser(credentials, Guid.NewGuid().ToString(), adUser.GivenName, adUser.Surname, adUser.EmailAddress, userId))
{
// 2 because we just added the user and there is the default admin user.
Expand All @@ -209,7 +216,7 @@ public ActionResult CreateADUser()
Log.Information("Making AD user {User} into an admin", credentials);

var id = MembershipService.GetUserModel(credentials).Id;
RoleProvider.AddUserToRoles(id, new[] {Definitions.Roles.Administrator});
RoleProvider.AddUserToRoles(id, new[] { Definitions.Roles.Administrator });

// Add the administrator role to the Identity/cookie
var Identity = (ClaimsIdentity)User.Identity;
Expand Down
Loading