Browse files

Merge pull request #21 from kuangmarkeleven/master

Reviewed code changes that refactored out membership dependency.
  • Loading branch information...
2 parents 6ffb295 + bacbadd commit 200eddfb788004fc8fc2c60106f19041b644c4e8 @kendallmiller kendallmiller committed Oct 30, 2011
View
BIN src/GiveCRM.DataAccess.Test/TestDB.sdf
Binary file not shown.
View
2 src/GiveCRM.Database/GiveCRM.Database.dbproj
@@ -40,7 +40,7 @@
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>.\sql\debug\</OutputPath>
<BuildScriptName>$(MSBuildProjectName).sql</BuildScriptName>
- <TargetConnectionString>Data Source=.;Integrated Security=True;Pooling=False</TargetConnectionString>
+ <TargetConnectionString>Data Source=(local);Integrated Security=True;Pooling=False</TargetConnectionString>
<TargetDatabase>GiveCRM</TargetDatabase>
<TreatWarningsAsErrors>False</TreatWarningsAsErrors>
<SuppressWarnings>
View
2 src/GiveCRM.Database/sql/debug/GiveCRM.Database.deploymanifest
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
- <TargetConnectionString>Data Source=.;Integrated Security=True;Pooling=False</TargetConnectionString>
+ <TargetConnectionString>Data Source=(local);Integrated Security=True;Pooling=False</TargetConnectionString>
<TargetDatabase>GiveCRM</TargetDatabase>
<DeployToDatabase>True</DeployToDatabase>
<DeployToScript>True</DeployToScript>
View
7 src/GiveCRM.Web.Tests/GiveCRM.Web.Tests.csproj
@@ -38,6 +38,9 @@
<StartupObject />
</PropertyGroup>
<ItemGroup>
+ <Reference Include="Moq">
+ <HintPath>..\packages\Moq.4.0.10827\lib\NET40\Moq.dll</HintPath>
+ </Reference>
<Reference Include="MvcContrib.TestHelper">
<HintPath>..\packages\MvcContrib.Mvc3.TestHelper-ci.3.0.90.0\lib\MvcContrib.TestHelper.dll</HintPath>
</Reference>
@@ -49,14 +52,17 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
+ <Reference Include="System.Web" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
+ <Reference Include="System.Web.Routing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
+ <Compile Include="controllers\AccountController.Tests.cs" />
<Compile Include="controllers\CampaignController.Tests.cs" />
<Compile Include="controllers\DonationController.Tests.cs" />
<Compile Include="controllers\HomeController.Tests.cs" />
@@ -65,6 +71,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\ExcelImport\ExcelImportService_Import_Should.cs" />
<Compile Include="Services\ExcelImport\MemberFactory_CreateMember_Should.cs" />
+ <Compile Include="Services\UrlValidationService.Tests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
View
140 src/GiveCRM.Web.Tests/Services/UrlValidationService.Tests.cs
@@ -0,0 +1,140 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Web;
+using System.Web.Mvc;
+using GiveCRM.Web.Controllers;
+using GiveCRM.Web.Services;
+using Moq;
+using NUnit.Framework;
+using System.Web.Routing;
+
+namespace GiveCRM.Web.Tests.Services
+{
+ [TestFixture]
+ public class UrlValidationServiceTest:AssertionHelper
+ {
+
+ private UrlValidationService CreateService()
+ {
+ var rules = new List<IAmAUrlValidationRule>
+ {
+ new IsLocal(),
+ new LengthIsGreaterThanOne(),
+ new BeginsWithForwardSlash(),
+ new DoesNotBeginWithDoubleForwardSlash(),
+ new DoesNotBeginWithForwardSlashBackslash()
+ };
+ return new UrlValidationService(rules);
+ }
+
+ [Test]
+ public void ShouldReturnTrueForValidUrl()
+ {
+ var routes = new RouteCollection();
+ MvcApplication.RegisterRoutes(routes);
+
+ var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
+ request.SetupGet(x => x.ApplicationPath).Returns("/");
+ request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Home", UriKind.Absolute));
+ request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
+
+ var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
+ response.Setup(x => x.ApplyAppPathModifier("/Home")).Returns("http://localhost/Home");
+
+ var context = new Mock<HttpContextBase>(MockBehavior.Strict);
+ context.SetupGet(x => x.Request).Returns(request.Object);
+ context.SetupGet(x => x.Response).Returns(response.Object);
+
+ var controller = new AccountController(null,null,null);
+ controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
+ controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
+
+ var service = CreateService();
+ var result = service.IsRedirectable(controller, @"/Home");
+ Expect(result, Is.True);
+ }
+
+ [Test]
+ public void ShouldReturnFalseForEmptyStringUrl()
+ {
+ var routes = new RouteCollection();
+ MvcApplication.RegisterRoutes(routes);
+
+ var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
+ request.SetupGet(x => x.ApplicationPath).Returns("/");
+ request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Home", UriKind.Absolute));
+ request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
+
+ var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
+ response.Setup(x => x.ApplyAppPathModifier("/Home")).Returns("http://localhost/Home");
+
+ var context = new Mock<HttpContextBase>(MockBehavior.Strict);
+ context.SetupGet(x => x.Request).Returns(request.Object);
+ context.SetupGet(x => x.Response).Returns(response.Object);
+
+ var controller = new AccountController(null, null, null);
+ controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
+ controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
+
+ var service = CreateService();
+ var result = service.IsRedirectable(controller, string.Empty);
+ Expect(result, Is.False);
+ }
+
+ [Test]
+ public void ShouldReturnFalseForUrlNotBeginingWithForwardSlash()
+ {
+ var routes = new RouteCollection();
+ MvcApplication.RegisterRoutes(routes);
+
+ var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
+ request.SetupGet(x => x.ApplicationPath).Returns("/");
+ request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Home", UriKind.Absolute));
+ request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
+
+ var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
+ response.Setup(x => x.ApplyAppPathModifier("/Home")).Returns("http://localhost/Home");
+
+ var context = new Mock<HttpContextBase>(MockBehavior.Strict);
+ context.SetupGet(x => x.Request).Returns(request.Object);
+ context.SetupGet(x => x.Response).Returns(response.Object);
+
+ var controller = new AccountController(null, null, null);
+ controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
+ controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
+
+ var service = CreateService();
+ var result = service.IsRedirectable(controller, "muppet");
+ Expect(result, Is.False);
+ }
+
+ [Test]
+ public void ShouldReturnFalseForUrlBeginingWithDoubleForwardSlash()
+ {
+ var routes = new RouteCollection();
+ MvcApplication.RegisterRoutes(routes);
+
+ var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
+ request.SetupGet(x => x.ApplicationPath).Returns("/");
+ request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Home", UriKind.Absolute));
+ request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
+
+ var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
+ response.Setup(x => x.ApplyAppPathModifier("/Home")).Returns("http://localhost/Home");
+
+ var context = new Mock<HttpContextBase>(MockBehavior.Strict);
+ context.SetupGet(x => x.Request).Returns(request.Object);
+ context.SetupGet(x => x.Response).Returns(response.Object);
+
+ var controller = new AccountController(null, null, null);
+ controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
+ controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
+
+ var service = CreateService();
+ var result = service.IsRedirectable(controller, "//muppet");
+ Expect(result, Is.False);
+ }
+ }
+}
View
191 src/GiveCRM.Web.Tests/controllers/AccountController.Tests.cs
@@ -0,0 +1,191 @@
+using System.Globalization;
+using System.Web.Mvc;
+using GiveCRM.Web.Controllers;
+using GiveCRM.Web.Models;
+using GiveCRM.Web.Services;
+using Moq;
+using MvcContrib.TestHelper;
+using NUnit.Framework;
+
+namespace GiveCRM.Web.Tests.controllers
+{
+ [TestFixture]
+ public class AccountControllerTests:AssertionHelper
+ {
+ private Mock<IMembershipService> mockMembershipService;
+ private Mock<IAuthenticationService> mockAuthenticationService;
+ private Mock<IUrlValidationService> mockUrlValidationService;
+
+ [SetUp]
+ public void SetUp()
+ {
+ mockMembershipService = new Mock<IMembershipService>();
+ mockAuthenticationService = new Mock<IAuthenticationService>();
+ mockUrlValidationService = new Mock<IUrlValidationService>();
+ }
+
+ private AccountController CreateController()
+ {
+ return new AccountController(mockMembershipService.Object,
+ mockAuthenticationService.Object,
+ mockUrlValidationService.Object);
+ }
+
+ [Test]
+ public void ShouldLogOnUserAndRedirectToHome()
+ {
+ var controller = CreateController();
+
+
+ mockMembershipService.Setup(ms=>ms.ValidateUser("test","password")).Returns(true);
+ mockUrlValidationService.Setup(uvs=>uvs.IsRedirectable(controller,"")).Returns(false);
+
+
+ var model = new LogOnModel();
+ model.UserName = "test";
+ model.Password = "password";
+ var url = string.Empty;
+
+ var actionResult = controller.LogOn(model, url);
+ Expect(controller.ModelState.IsValid, Is.True);
+ actionResult.AssertActionRedirect();
+ }
+
+ [Test]
+ public void ShouldLogOnUserAndRedirectToUrl()
+ {
+ var controller = CreateController();
+
+ mockMembershipService.Setup(ms => ms.ValidateUser("test", "password")).Returns(true);
+ mockUrlValidationService.Setup(uvs => uvs.IsRedirectable(controller, "testurl")).Returns(true);
+
+ var model = new LogOnModel();
+ model.UserName = "test";
+ model.Password = "password";
+ var url = "testurl";
+
+ var actionResult = controller.LogOn(model, url);
+ Expect(controller.ModelState.IsValid, Is.True);
+ Expect(actionResult.AssertHttpRedirect().Url, Is.EqualTo(url));
+ actionResult.AssertHttpRedirect();
+ }
+
+ [Test]
+ public void ShouldNotLogOnForIncorrectCredentials()
+ {
+ var controller = CreateController();
+
+ mockMembershipService.Setup(ms => ms.ValidateUser("test", "password")).Returns(false);
+
+ var model = new LogOnModel();
+ model.UserName = "test";
+ model.Password = "password";
+ var url = string.Empty;
+
+ var actionResult = controller.LogOn(model, url);
+ Expect(controller.ModelState.IsValid, Is.False);
+ Expect(controller.ModelState[""].Errors.Count,Is.EqualTo(1));
+ Expect(controller.ModelState[""].Errors[0].ErrorMessage,Is.EqualTo("The user name or password provided is incorrect."));
+ actionResult.AssertViewRendered().WithViewData<LogOnModel>();
+ }
+
+ [Test]
+ public void ShouldLogOff()
+ {
+ mockAuthenticationService.Setup(a => a.SignOut()).Verifiable();
+ var controller = CreateController();
+ var actionResult = controller.LogOff();
+ mockAuthenticationService.Verify();
+ actionResult.AssertActionRedirect();
+ }
+
+ [Test]
+ public void ShouldRegister()
+ {
+ var error = string.Empty;
+ mockMembershipService.Setup(s => s.CreateUser("test", "password", "a@a.a", out error)).Returns(true);
+ var controller = CreateController();
+ var model = new RegisterModel
+ {
+ UserName = "test",
+ Password ="password",
+ Email = "a@a.a"
+ };
+ var actionResult = controller.Register(model);
+ actionResult.AssertActionRedirect();
+ }
+
+ [Test]
+ public void ShouldFailToRegister()
+ {
+ var error = string.Empty;
+ mockMembershipService.Setup(s => s.CreateUser("test", "password", "a@a.a", out error)).Returns(false);
+ var controller = CreateController();
+ var model = new RegisterModel
+ {
+ UserName = "test",
+ Password = "password",
+ Email = "a@a.a"
+ };
+ var actionResult = controller.Register(model);
+ actionResult.AssertViewRendered().WithViewData<RegisterModel>();
+ }
+
+ [Test]
+ public void ShouldChangePassword()
+ {
+ var model = new ChangePasswordModel
+ {
+ NewPassword = "Slartibartfast",
+ OldPassword = "password",
+ ConfirmPassword = "Slartibartfast"
+ };
+
+ mockMembershipService.Setup(s => s.ChangePassword(It.IsAny<string>(),"password","Slartibartfast")).Returns(true);
+
+ var controller = CreateController();
+
+ var actionResult = controller.ChangePassword(model);
+ Expect(controller.ModelState.IsValid,Is.True);
+ actionResult.AssertActionRedirect();
+ }
+
+ [Test]
+ public void ShouldNotChangePasswordInvalidModel()
+ {
+ var model = new ChangePasswordModel
+ {
+ NewPassword = "Slartibartfast",
+ OldPassword = "password",
+ ConfirmPassword = "ZaphodBeeblebrox"
+ };
+
+ var controller = CreateController();
+ controller.ModelState.AddModelError("NewPassword","The new password and confirmation password do not match.");
+
+ var actionResult = controller.ChangePassword(model);
+ Expect(controller.ViewData.ModelState.IsValid, Is.False);
+ actionResult.AssertViewRendered().WithViewData<ChangePasswordModel>();
+ }
+
+ [Test]
+ public void ShouldNotChangePasswordIFailForChangePassword()
+ {
+ var model = new ChangePasswordModel
+ {
+ NewPassword = "Slartibartfast",
+ OldPassword = "password",
+ ConfirmPassword = "Slartibartfast"
+ };
+
+ mockMembershipService.Setup(s => s.ChangePassword(It.IsAny<string>(), "password", "Slartibartfast")).Returns(false);
+ var controller = CreateController();
+
+ var actionResult = controller.ChangePassword(model);
+ Expect(controller.ViewData.ModelState.IsValid, Is.False);
+ Expect(controller.ModelState[""].Errors.Count,Is.EqualTo(1));
+ Expect(controller.ModelState[""].Errors[0].ErrorMessage, Is.EqualTo("The current password is incorrect or the new password is invalid."));
+ actionResult.AssertViewRendered().WithViewData<ChangePasswordModel>();
+ }
+ }
+}
View
1 src/GiveCRM.Web.Tests/packages.config
@@ -4,4 +4,5 @@
<package id="NSubstitute" version="1.2.1.0" />
<package id="NUnit" version="2.5.10.11092" />
<package id="RhinoMocks" version="3.6" />
+ <package id="Moq" version="4.0.10827" />
</packages>
View
BIN src/GiveCRM.Web/App_Data/ASPNETDB.MDF
Binary file not shown.
View
BIN src/GiveCRM.Web/App_Data/aspnetdb_log.ldf
Binary file not shown.
View
4 src/GiveCRM.Web/App_Start/NinjectMVC3.cs
@@ -1,3 +1,4 @@
+using GiveCRM.Web.Services;
using Ninject.Extensions.Conventions;
[assembly: WebActivator.PreApplicationStartMethod(typeof(GiveCRM.Web.App_Start.NinjectMVC3), "Start")]
@@ -56,7 +57,8 @@ private static void RegisterServices(IKernel kernel)
a.BindWithDefaultConventions();
a.InRequestScope();
});
-
+
+ kernel.Bind<IMembershipService>().To<MembershipService>();
}
}
}
View
84 src/GiveCRM.Web/Controllers/AccountController.cs
@@ -2,11 +2,23 @@
using System.Web.Mvc;
using System.Web.Security;
using GiveCRM.Web.Models;
+using GiveCRM.Web.Services;
namespace GiveCRM.Web.Controllers
{
public class AccountController : Controller
{
+ private IMembershipService membershipService;
+ private IAuthenticationService authenticationService;
+ private IUrlValidationService urlValidationService;
+
+ public AccountController(IMembershipService membershipService, IAuthenticationService authenticationService, IUrlValidationService urlValidationService)
+ {
+ this.membershipService = membershipService;
+ this.authenticationService = authenticationService;
+ this.urlValidationService = urlValidationService;
+ }
+
//
// GET: /Account/LogOn
@@ -24,11 +36,12 @@ public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
- if (Membership.ValidateUser(model.UserName, model.Password))
+
+ if(membershipService.ValidateUser(model.UserName,model.Password))
{
- FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
- if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
- && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
+ authenticationService.SetAuthorizationCredentials(model.UserName,model.RememberMe);
+
+ if(urlValidationService.IsRedirectable(this,returnUrl))
{
return Redirect(returnUrl);
}
@@ -52,8 +65,7 @@ public ActionResult LogOn(LogOnModel model, string returnUrl)
public ActionResult LogOff()
{
- FormsAuthentication.SignOut();
-
+ authenticationService.SignOut();
return RedirectToAction("Index", "Home");
}
@@ -73,19 +85,15 @@ public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
- // Attempt to register the user
- MembershipCreateStatus createStatus;
- Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
-
- if (createStatus == MembershipCreateStatus.Success)
+ var error = string.Empty;
+ if (membershipService.CreateUser(model.UserName,model.Password,model.Email,out error))
{
- FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
+ authenticationService.SetAuthorizationCredentials(model.UserName,false);
return RedirectToAction("Index", "Home");
}
- else
- {
- ModelState.AddModelError("", ErrorCodeToString(createStatus));
- }
+
+ ModelState.AddModelError("", error);
+
}
// If we got this far, something failed, redisplay form
@@ -116,8 +124,8 @@ public ActionResult ChangePassword(ChangePasswordModel model)
bool changePasswordSucceeded;
try
{
- MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
- changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
+ string username = User == null ? string.Empty : User.Identity.Name;
+ changePasswordSucceeded = membershipService.ChangePassword(username, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
@@ -146,44 +154,6 @@ public ActionResult ChangePasswordSuccess()
return View();
}
- #region Status Codes
- private static string ErrorCodeToString(MembershipCreateStatus createStatus)
- {
- // See http://go.microsoft.com/fwlink/?LinkID=177550 for
- // a full list of status codes.
- switch (createStatus)
- {
- case MembershipCreateStatus.DuplicateUserName:
- return "User name already exists. Please enter a different user name.";
-
- case MembershipCreateStatus.DuplicateEmail:
- return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
-
- case MembershipCreateStatus.InvalidPassword:
- return "The password provided is invalid. Please enter a valid password value.";
-
- case MembershipCreateStatus.InvalidEmail:
- return "The e-mail address provided is invalid. Please check the value and try again.";
-
- case MembershipCreateStatus.InvalidAnswer:
- return "The password retrieval answer provided is invalid. Please check the value and try again.";
-
- case MembershipCreateStatus.InvalidQuestion:
- return "The password retrieval question provided is invalid. Please check the value and try again.";
-
- case MembershipCreateStatus.InvalidUserName:
- return "The user name provided is invalid. Please check the value and try again.";
-
- case MembershipCreateStatus.ProviderError:
- return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
-
- case MembershipCreateStatus.UserRejected:
- return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
-
- default:
- return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
- }
- }
- #endregion
+
}
}
View
6 src/GiveCRM.Web/GiveCRM.Web.csproj
@@ -110,6 +110,7 @@
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
+ <Compile Include="Services\AuthenticationService.cs" />
<Compile Include="Services\CampaignService.cs" />
<Compile Include="Services\DonationsService.cs" />
<Compile Include="Services\ExcelImport\ExcelImportService.cs" />
@@ -119,17 +120,22 @@
<Compile Include="Services\ExcelImport\ImportDataFailedEventArgs.cs" />
<Compile Include="Services\ExcelImport\MemberFactory.cs" />
<Compile Include="Services\FacetsService.cs" />
+ <Compile Include="Services\IAuthenticationService.cs" />
<Compile Include="Services\ICampaignService.cs" />
<Compile Include="Services\IDonationsService.cs" />
<Compile Include="Services\IFacetsService.cs" />
<Compile Include="Services\IMailingListService.cs" />
<Compile Include="Services\IMemberSearchFilterService.cs" />
<Compile Include="Services\IMemberService.cs" />
+ <Compile Include="Services\IMembershipService.cs" />
<Compile Include="Services\ISearchService.cs" />
+ <Compile Include="Services\IUrlValidationService.cs" />
<Compile Include="Services\MailingListService.cs" />
<Compile Include="Services\MemberSearchFilterService.cs" />
<Compile Include="Services\MemberService.cs" />
+ <Compile Include="Services\MembershipService.cs" />
<Compile Include="Services\SearchService.cs" />
+ <Compile Include="Services\UrlValidationService.cs" />
<Compile Include="Views\MenuHelper.cs" />
</ItemGroup>
<ItemGroup>
View
21 src/GiveCRM.Web/Services/AuthenticationService.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.Security;
+
+namespace GiveCRM.Web.Services
+{
+ public class AuthenticationService :IAuthenticationService
+ {
+ public void SetAuthorizationCredentials(string username, bool persistCredentials)
+ {
+ FormsAuthentication.SetAuthCookie(username, persistCredentials);
+ }
+
+ public void SignOut()
+ {
+ FormsAuthentication.SignOut();
+ }
+ }
+}
View
8 src/GiveCRM.Web/Services/IAuthenticationService.cs
@@ -0,0 +1,8 @@
+namespace GiveCRM.Web.Services
+{
+ public interface IAuthenticationService
+ {
+ void SetAuthorizationCredentials(string username, bool persistCredentials);
+ void SignOut();
+ }
+}
View
9 src/GiveCRM.Web/Services/IMembershipService.cs
@@ -0,0 +1,9 @@
+namespace GiveCRM.Web.Services
+{
+ public interface IMembershipService
+ {
+ bool ValidateUser(string userName, string password);
+ bool CreateUser(string userName, string password,string email,out string error);
+ bool ChangePassword(string userName, string oldPassword, string newPassword);
+ }
+}
View
1 src/GiveCRM.Web/Services/IUrlValidationService.cs
@@ -0,0 +1 @@
+
View
186 src/GiveCRM.Web/Services/MemberService.cs
@@ -1,99 +1,99 @@
-using System.Collections.Generic;
-using System.Linq;
-using GiveCRM.DataAccess;
-using GiveCRM.Models;
-
-namespace GiveCRM.Web.Services
-{
- public class MemberService: IMemberService
- {
- private Members _membersDb = new Members();
-
- public IEnumerable<Member> All()
- {
- return _membersDb.All();
- }
-
- public Member Get(int id)
- {
- var member = _membersDb.Get(id);
- return member;
- }
-
- public void Update(Member member)
- {
- _membersDb.Update(member);
- }
-
- public void Insert(Member member)
- {
- _membersDb.Insert(member);
- }
-
- public void Save(Member member)
- {
- if (member.Id == 0)
- this.Insert(member);
- else
- this.Update(member);
- }
-
- public void Delete(Member member)
- {
- member.AddressLine1 = "deleted";
- member.AddressLine2 = "deleted";
- member.EmailAddress = "deleted";
- member.FirstName = "deleted";
- member.LastName = "deleted";
-
- member.Archived = true;
-
- _membersDb.Update(member);
- }
-
- public IEnumerable<Member> Search(string name, string postcode, string reference)
- {
- var members = _membersDb.Search(name, postcode, reference);
- return members;
- }
-
- public IEnumerable<Member> Search(string criteria)
- {
- var results = _membersDb
- .All()
- .Where(member =>
- !member.Archived &&
- (criteria == string.Empty || NameSearch(member, criteria.ToLower())));
-
- return results;
+using System.Collections.Generic;
+using System.Linq;
+using GiveCRM.DataAccess;
+using GiveCRM.Models;
+
+namespace GiveCRM.Web.Services
+{
+ public class MemberService: IMemberService
+ {
+ private Members _membersDb = new Members();
+
+ public IEnumerable<Member> All()
+ {
+ return _membersDb.All();
+ }
+
+ public Member Get(int id)
+ {
+ var member = _membersDb.Get(id);
+ return member;
+ }
+
+ public void Update(Member member)
+ {
+ _membersDb.Update(member);
+ }
+
+ public void Insert(Member member)
+ {
+ _membersDb.Insert(member);
+ }
+
+ public void Save(Member member)
+ {
+ if (member.Id == 0)
+ this.Insert(member);
+ else
+ this.Update(member);
+ }
+
+ public void Delete(Member member)
+ {
+ member.AddressLine1 = "deleted";
+ member.AddressLine2 = "deleted";
+ member.EmailAddress = "deleted";
+ member.FirstName = "deleted";
+ member.LastName = "deleted";
+
+ member.Archived = true;
+
+ _membersDb.Update(member);
+ }
+
+ public IEnumerable<Member> Search(string name, string postcode, string reference)
+ {
+ var members = _membersDb.Search(name, postcode, reference);
+ return members;
+ }
+
+ public IEnumerable<Member> Search(string criteria)
+ {
+ var results = _membersDb
+ .All()
+ .Where(member =>
+ !member.Archived &&
+ (criteria == string.Empty || NameSearch(member, criteria.ToLower())));
+
+ return results;
}
public IEnumerable<Member> FromCampaignRun(int campaignId)
{
return _membersDb.FromCampaignRun(campaignId);
- }
-
- private bool NameSearch(Member member, string criteria)
- {
- return GetForenameSurname(member).Contains(criteria) || GetSurnameForename(member).Contains(criteria) || GetInitialSurname(member).Contains(criteria);
- }
-
- private string GetForenameSurname(Member member)
- {
- return string.Format("{0} {1} {2}", member.Salutation, member.FirstName, member.LastName).ToLower();
- }
-
- private string GetSurnameForename(Member member)
- {
- return string.Format("{0} {1} {2}", member.Salutation, member.LastName, member.FirstName).ToLower();
- }
-
- private string GetInitialSurname(Member member)
- {
- return string.Format("{0} {1} {2}", member.Salutation, member.FirstName.Substring(0, 1), member.LastName).ToLower();
- }
-
-
-
- }
+ }
+
+ private bool NameSearch(Member member, string criteria)
+ {
+ return GetForenameSurname(member).Contains(criteria) || GetSurnameForename(member).Contains(criteria) || GetInitialSurname(member).Contains(criteria);
+ }
+
+ private string GetForenameSurname(Member member)
+ {
+ return string.Format("{0} {1} {2}", member.Salutation, member.FirstName, member.LastName).ToLower();
+ }
+
+ private string GetSurnameForename(Member member)
+ {
+ return string.Format("{0} {1} {2}", member.Salutation, member.LastName, member.FirstName).ToLower();
+ }
+
+ private string GetInitialSurname(Member member)
+ {
+ return string.Format("{0} {1} {2}", member.Salutation, member.FirstName.Substring(0, 1), member.LastName).ToLower();
+ }
+
+
+
+ }
}
View
74 src/GiveCRM.Web/Services/MembershipService.cs
@@ -0,0 +1,74 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web;
+using System.Web.Security;
+
+namespace GiveCRM.Web.Services
+{
+ public class MembershipService : IMembershipService
+ {
+ public bool ValidateUser(string userName, string password)
+ {
+ return Membership.ValidateUser(userName, password);
+ }
+
+ public bool CreateUser(string userName, string password, string email,out string error)
+ {
+ error = string.Empty;
+ MembershipCreateStatus createStatus;
+ Membership.CreateUser(userName, password, email, null, null, true, null, out createStatus);
+ if (createStatus == MembershipCreateStatus.Success) return true;
+
+ error = ErrorCodeToString(createStatus);
+ return false;
+ }
+
+ public bool ChangePassword(string userName, string oldPassword, string newPassword)
+ {
+ MembershipUser currentUser = Membership.GetUser(userName, true);
+ return currentUser.ChangePassword(oldPassword, newPassword);
+ }
+
+ private static string ErrorCodeToString(MembershipCreateStatus createStatus)
+ {
+ // See http://go.microsoft.com/fwlink/?LinkID=177550 for
+ // a full list of status codes.
+ switch (createStatus)
+ {
+ case MembershipCreateStatus.DuplicateUserName:
+ return "User name already exists. Please enter a different user name.";
+
+ case MembershipCreateStatus.DuplicateEmail:
+ return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
+
+ case MembershipCreateStatus.InvalidPassword:
+ return "The password provided is invalid. Please enter a valid password value.";
+
+ case MembershipCreateStatus.InvalidEmail:
+ return "The e-mail address provided is invalid. Please check the value and try again.";
+
+ case MembershipCreateStatus.InvalidAnswer:
+ return "The password retrieval answer provided is invalid. Please check the value and try again.";
+
+ case MembershipCreateStatus.InvalidQuestion:
+ return "The password retrieval question provided is invalid. Please check the value and try again.";
+
+ case MembershipCreateStatus.InvalidUserName:
+ return "The user name provided is invalid. Please check the value and try again.";
+
+ case MembershipCreateStatus.ProviderError:
+ return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
+
+ case MembershipCreateStatus.UserRejected:
+ return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
+
+ default:
+ return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
+ }
+ }
+
+
+
+ }
+}
View
89 src/GiveCRM.Web/Services/UrlValidationService.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Web.Mvc;
+using System.Web;
+
+namespace GiveCRM.Web.Services
+{
+ public interface IUrlValidationService
+ {
+ bool IsRedirectable(Controller controller,string url);
+ }
+
+ public class UrlValidationService : IUrlValidationService
+ {
+ private IEnumerable<IAmAUrlValidationRule> rules;
+
+ public UrlValidationService(IEnumerable<IAmAUrlValidationRule>rules)
+ {
+ this.rules = rules;
+ }
+
+ public bool IsRedirectable(Controller controller, string url)
+ {
+ var result = true;
+ foreach(var rule in rules)
+ {
+ if(!rule.IsValid(controller,url))
+ {
+ result = false;
+ break;
+ }
+ }
+ return result;
+ }
+ }
+
+
+
+ public interface IAmAUrlValidationRule
+ {
+ bool IsValid(Controller controller, string url);
+ }
+
+ public class IsLocal:IAmAUrlValidationRule
+ {
+
+ public bool IsValid(Controller controller, string url)
+ {
+ return controller.Url.IsLocalUrl(url);
+ }
+ }
+
+ public class LengthIsGreaterThanOne:IAmAUrlValidationRule
+ {
+
+ public bool IsValid(Controller controller, string url)
+ {
+ return url.Length > 1;
+ }
+ }
+
+ public class BeginsWithForwardSlash : IAmAUrlValidationRule
+ {
+
+ public bool IsValid(Controller controller, string url)
+ {
+ return url.StartsWith("/");
+ }
+ }
+
+ public class DoesNotBeginWithDoubleForwardSlash : IAmAUrlValidationRule
+ {
+
+ public bool IsValid(Controller controller, string url)
+ {
+ return !url.StartsWith("//");
+ }
+ }
+
+ public class DoesNotBeginWithForwardSlashBackslash : IAmAUrlValidationRule
+ {
+
+ public bool IsValid(Controller controller, string url)
+ {
+ return !url.StartsWith("/\\");
+ }
+ }
+}

0 comments on commit 200eddf

Please sign in to comment.