/// <summary> /// This method has been implemented so as we can refactor the entire application to use the Infostructure.SimpleList.Web.Service.Api class, which takes a userName and password parameter for every call. /// This method returns the User object for an authenticated user, whether they have come in through the service or the web front-end. /// There is still a bit of a "smell" about this method and some of the authetication architecture, in particular that I'm passing around unencrypted passwords, but it's tollerable for the time being. /// Since the API service is accessed directly, there should be no need to use this method where the user is not ASP.NET authenticated. /// </summary> /// <param name="controller"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns>A Infostructure.SimpleList.DataModel.Models.User instance if authetication is successful.</returns> private User GetUserCredentials() { _userRepository = new UserRepository(); // Get the username and password off the query string, if they're there. string userName = HttpContext.Current.Request.QueryString["userName"]; string password = HttpContext.Current.Request.QueryString["password"]; // This is where we would go if we've come in via the service. if (userName != null && password != null) { IMembershipService membershipService = new AccountMembershipService(); if (membershipService.ValidateUser(userName, password)) { return(_userRepository.GetUser(userName)); } else { return(null); } } // This is where we go if we've come in via the web front-end, since the request will not be ASP.NET authenticated by the service. else if (HttpContext.Current.User.Identity.IsAuthenticated) { return(_userRepository.GetUser(HttpContext.Current.User.Identity.Name)); } // User has not been successfully authenticated. else { return(null); } }
public ActionResult Staff(itmmAdminStaff model, string type) { if (ModelState.IsValid) { AccountMembershipService MembershipService = new AccountMembershipService(); MembershipCreateStatus createStatus = MembershipService.CreateUser(model.uname, model.password, model.eadd); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRole(model.uname, "Staff"); Laboratory_Staff a = new Laboratory_Staff(); a.FirstName = model.fname; a.LastName = model.lname; a.IdNumber = model.cnum; a.CourseAndYear = model.course; a.EmailAddress = model.eadd; a.Type = type; a.UserName = model.uname; //for LabId var c = (from y in con.Laboratories where y.UserName == User.Identity.Name select y.LaboratoryId).FirstOrDefault(); a.LaboratoryId = c; con.AddToLaboratory_Staff(a); con.SaveChanges(); return(RedirectToAction("Staff", "Head")); } else { ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } } return(View(model)); }
public IHttpActionResult UpdatePassword(UpdatePass pass) { string str = "Password modification failed"; if (!string.IsNullOrEmpty(pass.username) && !string.IsNullOrEmpty(pass.newPassword) && !string.IsNullOrEmpty(pass.oldP)) { var MembershipService = new AccountMembershipService(); try { Membership.ApplicationName = "MES"; if (MembershipService.ChangePassword(pass.username, pass.oldP, pass.newPassword)) { str = "Password reset complete"; } else { return(BadRequest("Password modification failed")); } } catch (Exception eJob) { var error = string.Format("Job错误,执行aspnet_Membership_SetPassword出错,错误信息{0}", eJob.Message); var resp = new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = error, Content = new StringContent(error) }; Loger.Error(eJob); throw new HttpResponseException(resp); } } return(Ok(str)); }
public ActionResult Index(int dinnerCount = 100) { const string name = "Nerd"; var membershipService = new AccountMembershipService(); if(membershipService.ValidateUser(name, "password") == false) { membershipService.CreateUser(name, "password", "*****@*****.**"); } var repo = new DinnerRepository(); foreach(var d in repo.All) { repo.Delete(d.DinnerID); } for (var i = 0; i < dinnerCount; i++) { var dinner = new Dinner {Title = "Nerd-Out", Description = "Nerding out with the nerds", EventDate = DateTime.Now.Add(new TimeSpan(30, 0, 0, 0)), ContactPhone = "403-999-9999", Address = "Calgary, AB", Country = "Canada", HostedById = name, HostedBy = name}; var rsvp = new RSVP {AttendeeNameId = name, AttendeeName = name}; dinner.RSVPs = new List<RSVP> {rsvp}; repo.InsertOrUpdate(dinner); } try { repo.Save(); } catch(DbEntityValidationException e) { var error = e.EntityValidationErrors.First().ValidationErrors.First(); return new ContentResult {Content = string.Format("{0}: {1}", error.PropertyName, error.ErrorMessage)}; } return new ContentResult{Content = "Success"}; }
public async Task <IHttpActionResult> ForgotPassword(string Email) { if (!String.IsNullOrEmpty(Email)) { var user = await UserManager.FindByNameAsync(Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return(BadRequest("The email is not associated with any account.")); } var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var encodedId = HttpUtility.HtmlEncode(user.Id); var encodedCode = HttpUtility.HtmlEncode(code); //IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, code, "Test@123"); // var callbackUrl = String.Format(ConfigurationManager.AppSettings["Password_Reset_Link"], user.Id,code); // await UserManager.SendEmailAsync(user.Id, "Reset Password", //"Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>"); IMembershipService ams = new AccountMembershipService(); ams.SendVerification(encodedId, Email, encodedCode, SupportMailType.ResetPassword); return(Ok("Success")); } // If we got this far, something failed, redisplay form return(BadRequest("The email is required."));; }
public override void OnAuthorization(AuthorizationContext filterContext) { bool basicValidated = false; var req = filterContext.HttpContext.Request; var auth = req.Headers["Authorization"]; if (!string.IsNullOrEmpty(auth)) { var cred = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':'); var userName = cred[0]; var pass = cred[1]; var membership = new AccountMembershipService(); basicValidated = membership.ValidateUser(userName, pass); if (!basicValidated) { base.OnAuthorization(filterContext); } else { var roles = System.Web.Security.Roles.GetRolesForUser(userName); IPrincipal principal = new GenericPrincipal( new GenericIdentity(userName), roles); Thread.CurrentPrincipal = principal; System.Web.HttpContext.Current.User = principal; } } else { base.OnAuthorization(filterContext); } }
protected override void Initialize(RequestContext requestContext) { if (FormsService == null) { FormsService = new FormsAuthenticationService(); } if (MembershipService == null) { MembershipService = new AccountMembershipService(); } base.Initialize(requestContext); }
/// <summary> /// This method has been implemented so as we can refactor the entire application to use the Infostructure.SimpleList.Web.Service.Api class, which takes a userName and password parameter for every call. /// This method returns the User object for an authenticated user, whether they have come in through the service or the web front-end. /// There is still a bit of a "smell" about this method and some of the authetication architecture, in particular that I'm passing around unencrypted passwords, but it's tollerable for the time being. /// Since the API service is accessed directly, there should be no need to use this method where the user is not ASP.NET authenticated. /// </summary> /// <param name="controller"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns>A Infostructure.SimpleList.DataModel.Models.User instance if authetication is successful.</returns> public static User GetUserCredentials(this Controller controller) { // Get the username and password off the quesry string, if they're there. string userName = controller.Request.QueryString["userName"]; string password = controller.Request.QueryString["password"]; if (userName != null && password != null) // This is where we would go if we've come in via the service. { IMembershipService membershipService = new AccountMembershipService(); if (membershipService.ValidateUser(userName, password)) { return(_userRepository.GetUser(userName)); } else { return(null); } } else if (controller.User.Identity.IsAuthenticated) // This is where we go if we've come in via the web front-end, since the request will not be ASP.NET authenticated by the service. { return(_userRepository.GetUser(userName)); } else // User has not been successfully authenticated. { return(null); } }
public ActionResult Edit(int id) { Scrum scrum = _ScrumService.GetScrumById(id); if (scrum == null) // new scrum { scrum = new Scrum() { DateOfScrum = DateTime.Now, SprintId = SessionHelper.GetCurrentSprintId(User.Identity.Name, Session) }; scrum = _ScrumService.GenerateNewScrumDetails(SessionHelper.GetCurrentSprintId(User.Identity.Name, Session), scrum); } IMembershipService membershipService = new AccountMembershipService(); ScrumViewModel scrumViewModel = new ScrumViewModel() { ScrumModel = scrum, MemberUsernames = membershipService.GetAlphabeticalUsernameList() }; scrumViewModel.MemberUsernames.Insert(0, AccountMembershipService.UNASSIGNED); return(PartialView(scrumViewModel)); }
public static ScrumCollectionViewModel BuildByDateOfScrumDesc(int productId, int selectedSprintId) { ScrumTimeEntities scrumTimeEntities = new ScrumTimeEntities(); ScrumCollectionViewModel scrumCollectionViewModel = new ScrumCollectionViewModel(selectedSprintId); if (selectedSprintId > 0) { Sprint sprint = scrumTimeEntities.Sprints.First <Sprint>(s => s.SprintId == selectedSprintId); var results = from s in sprint.Scrums orderby s.DateOfScrum ascending select s; List <Scrum> scrums = results.ToList <Scrum>(); scrumCollectionViewModel.Scrums = scrums; } scrumCollectionViewModel.Usernames = new List <string>(); AccountMembershipService membershipService = new AccountMembershipService(); MembershipUserCollection membershipUserCollection = membershipService.GetAllUsers(); foreach (MembershipUser user in membershipUserCollection) { scrumCollectionViewModel.Usernames.Add(user.UserName); } return(scrumCollectionViewModel); }
/// <summary> /// Initializes this instance. /// </summary> public override void Initialize() { base.Initialize(); FormsAuth = new FormsAuthenticationService(); MembershipService = new AccountMembershipService(); }
public static void AddDefaultAccount() { var svc = new AccountMembershipService(); if (svc.ValidateUser("zys", "112233445566") == false) { svc.CreateUser("zys", "112233445566", "*****@*****.**"); } }
protected override void Initialize(RequestContext requestContext) { if (MembershipService == null) { MembershipService = new AccountMembershipService(); } base.Initialize(requestContext); }
public ActionResult SendStudentAnEmail(EmailViewModel model) { if (ModelState.IsValid) { AccountMembershipService.SendCustomEmail(model); return(RedirectToAction("Message", "Course", new { message = "Your email has been sent." })); } return(View("Error")); }
public ActionResult PasswordReset(PasswordResetViewModel model) { string emailAddress = model.email; string user = Membership.GetUserNameByEmail(emailAddress); AccountMembershipService.ChangePassword(user); TempData["tempMessage"] = "You have reset your password, please retrieve it from your email inbox and log on."; return(RedirectToAction("LogOn")); }
public NotificationService(IRepository <Seminar> seminarRepository, IRepository <EmailQueue> emailQueueRepository, IRepository <MailingList> mailingListRepository) { _seminarRepository = seminarRepository; _emailQueueRepository = emailQueueRepository; _mailingListRepository = mailingListRepository; if (_membershipService == null) { _membershipService = new AccountMembershipService(); } }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); AccountMembershipService membershipService = new AccountMembershipService(membershipProvider); AccountController controller = new AccountController(formsAuth, membershipService); ControllerContext controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller); controller.ControllerContext = controllerContext; return(controller); }
public static bool IsUserAuthenticated(this Controller controller, string userName, string password) { if (userName != null && password != null) { IMembershipService membershipService = new AccountMembershipService(); return(membershipService.ValidateUser(userName, password)); } else { return(false); } }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); var membershipService = new AccountMembershipService(membershipProvider); var controller = new AccountController(formsAuth, new CommandServiceClient(), new MembershipReadModel()); var controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller); controller.ControllerContext = controllerContext; return(controller); }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); AccountMembershipService membershipService = new AccountMembershipService(membershipProvider, null); var modRepo = new FakeModuleRepository(); AccountController controller = new AccountController(modRepo, formsAuth, membershipService); ControllerContext controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller); controller.ControllerContext = controllerContext; return(controller); }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); AccountMembershipService membershipService = new AccountMembershipService(membershipProvider); AccountController controller = new AccountController(formsAuth, membershipService); HttpContextBase contextBase = MvcMockHelpers.FakeHttpContext(); // new MockHttpContext(); controller.ControllerContext = new ControllerContext(contextBase, new RouteData(), controller); controller.Url = new UrlHelper(new RequestContext(contextBase, new RouteData()), new RouteCollection()); return(controller); }
public void ConstructorSetsProperties() { // Arrange IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); IMembershipService membershipService = new AccountMembershipService(); // Act AccountController controller = new AccountController(formsAuth, membershipService); // Assert Assert.AreEqual(formsAuth, controller.FormsAuth, "FormsAuth property did not match."); Assert.AreEqual(membershipService, controller.MembershipService, "MembershipService property did not match."); }
protected override void Initialize(RequestContext requestContext) { if (FormsService == null) { FormsService = new FormsAuthenticationService(); } if (MembershipService == null) { MembershipService = new AccountMembershipService(); } base.Initialize(requestContext); }
public ActionResult Register(RegisterViewModel viewModel, int stateInt) { string stringStateAbbreviation = StateList.First(m => m.Value == stateInt.ToString()).Text; if (ModelState.IsValid) { var model = new RegisterModel { UserName = viewModel.UserName, Email = viewModel.Email, FirstMidName = viewModel.FirstMidName, LastName = viewModel.LastName, StreetAddress = viewModel.StreetAddress, City = viewModel.City, State = stringStateAbbreviation, ZipCode = viewModel.ZipCode, Phone = viewModel.Phone, DateOfBirth = viewModel.DateOfBirth, ParishAffiliation = viewModel.ParishAffiliation, MinistryInvolvement = viewModel.MinistryInvolvement, Password = viewModel.Password, ConfirmPassword = viewModel.ConfirmPassword }; // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser( model.UserName, model.Password, model.Email, null, null, false, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { //FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); CustomProfile profile = CustomProfile.GetUserProfile(model.UserName); SetDefaultStateOfUser(model, profile); SaveNewProfile(model, profile); MembershipUser user = Membership.GetUser(model.UserName, false); AccountMembershipService.SendConfirmationEmail(user); return(RedirectToAction("confirmation")); } ModelState.AddModelError(string.Empty, ErrorCodeToString(createStatus)); } // If we got this far, something failed, redisplay form viewModel.State = StateList; return(View(viewModel)); }
private int CreateNewUser(string userName, bool createInUserAppTable, bool createInCurrentAppUsersTable, bool CreateInMembership) { Dictionary <string, object> parameters = new Dictionary <string, object>(); string role = "User"; string password = new AccountMembershipService().GetRandomPassword(10); string firstName = "heroku"; string lastName = "heroku"; Guid guid = Guid.NewGuid(); string sql = "INSERT INTO [durados_User] ([Username],[FirstName],[LastName],[Email],[Role],[Guid]) VALUES (@Username,@FirstName,@LastName,@Email,@Role,@Guid); SELECT IDENT_CURRENT(N'[durados_User]') AS ID "; parameters.Add("@Email", userName); parameters.Add("@Username", userName); parameters.Add("@FirstName", firstName); parameters.Add("@LastName", lastName); parameters.Add("@Role", role); parameters.Add("@Guid", guid); object scalar = SqlAccess.ExecuteScalar(Maps.Instance.DuradosMap.Database.ConnectionString, sql, parameters); int newUserId = Convert.ToInt32(scalar); if (createInUserAppTable) { parameters = new Dictionary <string, object>(); parameters.Add("newUser", userName); parameters.Add("appName", Map.AppName); parameters.Add("role", role); sqlAccess.ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, "durados_NewAppAsignment @newUser, @appName, @role", parameters, null); } if (createInCurrentAppUsersTable) { int userId = Map.Database.GetUserID(userName); if (userId == -1) { throw new DuradosException("Problem with get user detalis"); } PlugInHelper.AddUserToApp(Convert.ToInt32(Map.Id), userId, role); } if (CreateInMembership) { System.Web.Security.MembershipCreateStatus createStatus = (new Durados.Web.Mvc.Controllers.AccountMembershipService()).CreateUser(userName, password, userName); if (createStatus == System.Web.Security.MembershipCreateStatus.Success) { System.Web.Security.Roles.AddUserToRole(userName, role); } } return(newUserId); }
public PersonService(IRepository <Firm> firmRepository, IRepository <Person> personRepository, IRepository <SeminarPerson> seminarPersonRepository, IRepository <Seminar> seminarRepository, IRepositoryWithTypedId <User, Guid> userRepository, IFirmService firmService, IRepositoryWithTypedId <AddressType, char> addressTypeRepository, IRepositoryWithTypedId <ContactType, char> contactTypeRepository, IRepository <Commodity> commodityRepository) { _firmRepository = firmRepository; _personRepository = personRepository; _seminarPersonRepository = seminarPersonRepository; _seminarRepository = seminarRepository; _userRepository = userRepository; _firmService = firmService; _addressTypeRepository = addressTypeRepository; _contactTypeRepository = contactTypeRepository; _commodityRepository = commodityRepository; _membershipService = new AccountMembershipService(); }
private static void RequiredData(string installDirPath, string adminUser, string adminPass) { MembershipCreateStatus createStatus; AccountMembershipService membershipService = new AccountMembershipService(); AccountRoleService roleService = new AccountRoleService(); Common.Models.Account.Users user = Data.Account.Users.Get("Administrator"); if (user == null) { createStatus = membershipService.CreateUser(adminUser, adminPass, Common.Settings.Manager.Instance.System.AdminEmail, true); } if (!roleService.RoleExists("Login")) { roleService.CreateRole("Login"); } if (!roleService.RoleExists("Admin")) { roleService.CreateRole("Admin"); } if (!roleService.RoleExists("User")) { roleService.CreateRole("User"); } if (!roleService.RoleExists("Client")) { roleService.CreateRole("Client"); } if (!roleService.IsUserInRole(adminUser, "Login")) { roleService.AddUserToRole(adminUser, "Login"); } if (!roleService.IsUserInRole(adminUser, "Admin")) { roleService.AddUserToRole(adminUser, "Admin"); } if (!roleService.IsUserInRole(adminUser, "User")) { roleService.AddUserToRole(adminUser, "User"); } }
private static void RequiredData(string installDirPath, string adminUser, string adminPass) { MembershipCreateStatus createStatus; AccountMembershipService membershipService = new AccountMembershipService(); AccountRoleService roleService = new AccountRoleService(); Common.Models.Account.Users user = Data.Account.Users.Get("Administrator"); if (user == null) { createStatus = membershipService.CreateUser(adminUser, adminPass, Common.Settings.Manager.Instance.System.AdminEmail, true); } if (!roleService.RoleExists("Login")) { roleService.CreateRole("Login"); } if (!roleService.RoleExists("Admin")) { roleService.CreateRole("Admin"); } if (!roleService.RoleExists("User")) { roleService.CreateRole("User"); } if (!roleService.RoleExists("Client")) { roleService.CreateRole("Client"); } if (!roleService.IsUserInRole(adminUser, "Login")) { roleService.AddUserToRole(adminUser, "Login"); } if (!roleService.IsUserInRole(adminUser, "Admin")) { roleService.AddUserToRole(adminUser, "Admin"); } if (!roleService.IsUserInRole(adminUser, "User")) { roleService.AddUserToRole(adminUser, "User"); } }
public ActionResult Head(itmmAdminHead model, int section) { var l = from y in con.Laboratories orderby y.LaboratoryName ascending select y; ViewBag.LabList = l; var b = from y in con.Laboratory_Head select y; ViewBag.HeadList = b; if (ModelState.IsValid) { AccountMembershipService MembershipService = new AccountMembershipService(); MembershipCreateStatus createStatus = MembershipService.CreateUser(model.uname, model.password, model.eadd); if (createStatus == MembershipCreateStatus.Success) { Roles.AddUserToRole(model.uname, "Head"); Laboratory_Head a = new Laboratory_Head(); a.FirstName = model.fname; a.LastName = model.lname; a.UserName = model.uname; a.ContactNum = model.cnum; a.EmailAdd = model.eadd; a.LaboratoryId = section; var x = (from y in con.Laboratories where y.LaboratoryId == section select y).FirstOrDefault(); x.UserName = model.uname; con.AddToLaboratory_Head(a); con.SaveChanges(); return(RedirectToAction("Head", "Admin")); } else { ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } } return(View(model)); }
public ActionResult SearchByPhoto(PeopleSearchModel model, string returnUrl) { if (!Request.IsAuthenticated) { return(RedirectToAction("LogOnByUserName", "Account")); } Session["ComparedPhoto"] = null; byte[] userPhoto = (byte[])Session["ContentStream"]; double runTime = -1; try { if (Request.Form["Algorithm"] == null) { throw new Exception(); } support.Algorithm alg = support.Algorithm.EigenFaces; if (!Enum.TryParse <support.Algorithm>(Request.Form["Algorithm"].ToString(), out alg)) { throw new Exception(); } AccountMembershipService service = new AccountMembershipService(); MembershipPerson person = null; if (service.ValidatePerson(userPhoto, out person, alg, out runTime)) { Session["LastRecognitionAlgorithm"] = Enum.GetName(typeof(support.Algorithm), alg); Session["LastRecognitionTime"] = runTime; if (person != null) { Session["PersonForReview"] = person; Session["ComparedPhoto"] = userPhoto; return(View("PersonSearch")); } } } catch { } finally { // Session["ContentStream"] = null; // Session["ContentLength"] = null; // Session["ContentType"] = null; } ModelState.AddModelError("", "No record found."); return(View("PersonSearch")); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { // load the user and make sure they are valid var userName = httpContext.User.Identity.Name; var membership = new AccountMembershipService(); var result = membership.IsValidUser(userName); if (result) { // load the site id var siteId = httpContext.Request.RequestContext.RouteData.Values["site"]; var personRepository = SmartServiceLocator <IRepositoryWithTypedId <Person, string> > .GetService(); var person = personRepository.Queryable.First(a => a.User.LoweredUserName == userName.ToLower()); //httpContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden); return(person.Sites.Any(a => a.Id == (string)siteId)); } return(false); }
public JsonResult SignUp(string username, string password, string send, string phone, string fullname, string dbtype, string dbother) { int identity = -1; try { Durados.DataAccess.SqlAccess sql = new Durados.DataAccess.SqlAccess(); Dictionary <string, object> parameters = new Dictionary <string, object>(); string email = username.Trim(); parameters.Add("@Email", email); parameters.Add("@Username", username); if (sql.ExecuteScalar(Map.Database.ConnectionString, "SELECT TOP 1 [Username] FROM [durados_User] WHERE [Username]=@Username", parameters) != string.Empty) { return(Json(new { Success = false, Message = string.Format("{0} is already signed up.", username) })); } string email1 = email; try { email1 = email.Split('@')[0]; } catch { } email1 = email1.ReplaceNonAlphaNumeric(); if (string.IsNullOrEmpty(email1)) { email1 = email; } string[] email1arr = email1.Split('_'); string firstName = string.Empty; if (email1arr.Length > 0) { firstName = email1arr[0]; } else { firstName = email; } parameters.Add("@FirstName", firstName); string lastName = string.Empty; if (email1arr.Length > 0) { lastName = email1arr[email1arr.Length - 1]; } else { lastName = email; } parameters.Add("@LastName", lastName); //Create random Password if (string.IsNullOrEmpty(password)) { password = new AccountMembershipService().GetRandomPassword(10); } parameters.Add("@Password", password); string role = "User"; parameters.Add("@Role", role); Guid guid = Guid.NewGuid(); parameters.Add("@Guid", guid); sql.ExecuteNonQuery(Map.Database.ConnectionString, "INSERT INTO [durados_User] ([Username],[FirstName],[LastName],[Email],[Role],[Guid]) VALUES (@Username,@FirstName,@LastName,@Email,@Role,@Guid)", parameters, CreateMembershipCallback); System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, true); if (user != null) { if (!user.IsApproved && Maps.MultiTenancy) { user.IsApproved = true; System.Web.Security.Membership.UpdateUser(user); } } FormsAuth.SignIn(username, true); identity = Convert.ToInt32(Map.Database.GetUserRow(username)["Id"]); //CreatePendingDatabase(identity); bool sendEmail = false; sendEmail = send != null && send == "true"; if (sendEmail) { Durados.Web.Mvc.UI.Helpers.Account.SendRegistrationRequest(fullname, lastName, email, guid.ToString(), username, password, Map, DontSend); } try { Durados.Web.Mvc.UI.Helpers.Account.UpdateWebsiteUsers(username, identity); } catch (Exception ex) { Maps.Instance.DuradosMap.Logger.Log(RouteData.Values["Controller"].ToString(), RouteData.Values["Action"].ToString(), "SignUp", ex, 1, "failed to update websiteusercookie with userid"); } //Insert into website users try { Durados.Web.Mvc.UI.Helpers.Account.InsertContactUsUsers(username, fullname, null, phone, 10, int.Parse(dbtype), dbother); //10=welcome email } catch (Exception ex) { Maps.Instance.DuradosMap.Logger.Log(RouteData.Values["Controller"].ToString(), RouteData.Values["Action"].ToString(), "SignUp", ex, 1, "failed to update websiteuser in ContactUs"); } } catch (DuradosException exception) { Map.Logger.Log(this.ControllerContext.RouteData.Values["controller"].ToString(), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, null); return(Json(new { Success = false, Message = "The server is busy, please try again later." })); } catch (Exception exception) { Map.Logger.Log(this.ControllerContext.RouteData.Values["controller"].ToString(), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, null); //ViewData["confirmed"] = false; return(Json(new { Success = false, Message = "The server is busy, please try again later." })); } return(Json(new { Success = true, Message = "Success", identity = identity, DemoDefaults = GetDefaultDemo(identity) })); }
public void ConstructorSetsProperties() { // Arrange IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); IMembershipService membershipService = new AccountMembershipService(); // Act AccountController controller = new AccountController(formsAuth, membershipService); // Assert Assert.AreEqual(formsAuth, controller.FormsAuth, "FormsAuth property did not match."); Assert.AreEqual(membershipService, controller.MembershipService, "MembershipService property did not match."); }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); AccountMembershipService membershipService = new AccountMembershipService(membershipProvider); AccountController controller = new AccountController(formsAuth, membershipService); HttpContextBase contextBase = MvcMockHelpers.FakeHttpContext(); // new MockHttpContext(); controller.ControllerContext = new ControllerContext(contextBase, new RouteData(), controller); controller.Url = new UrlHelper(new RequestContext(contextBase, new RouteData()), new RouteCollection()); return controller; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (IsConnectingDatabase(httpContext)) { return(true); } if (Map.Database.SecureLevel == SecureLevel.AllUsers && string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["id"])) { if (string.IsNullOrEmpty(System.Web.HttpContext.Current.User.Identity.Name)) { System.Data.DataRow userRow = Map.Database.GetUserRow(); if (userRow == null) { AccountMembershipService accountMembershipService = new AccountMembershipService(); string userId = accountMembershipService.RegisterGuest(); } } return(true); } if (!authorize) { return(true); } if (httpContext.User.Identity is System.Security.Principal.WindowsIdentity && Maps.Skin == true) { bool userRegistered = Map.Database.GetUserRow() != null; if (Map.Database.SecureLevel == SecureLevel.AuthenticatedUsers) { if (!userRegistered) { string email = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["fromError"]); AccountMembershipService accountMembershipService = new AccountMembershipService(); accountMembershipService.RegisterGuest(new Durados.Web.Mvc.Controllers.AccountMembershipService.AuthenticatedUserInfo() { FirstName = httpContext.User.Identity.Name, LastName = httpContext.User.Identity.Name, Email = email }, httpContext.User.Identity.Name); } return(true); } else if (Map.Database.SecureLevel == SecureLevel.RegisteredUsers) { if (!userRegistered) { try { Map.Logger.Log(httpContext.Request.Url.PathAndQuery, "AuthorizeCore", httpContext.User.Identity.Name, null, 1, null); } catch { } } return(userRegistered); } } if (guidValidation)// || httpContext.Request.Browser.Browser.ToLower() == "ie") { string id = httpContext.Request.QueryString["id"]; if (!string.IsNullOrEmpty(id)) { string username = Map.Database.GetUsernameByGuid(id); //if (id == System.Web.Configuration.WebConfigurationManager.AppSettings["code"]) if (username != null) { return(true); } } } bool b = base.AuthorizeCore(httpContext); if (!b) { try { Map.Logger.Log(httpContext.Request.Url.PathAndQuery, "AuthorizeCore", httpContext.User.Identity.Name, null, 77, "Not authorized user: "******". probably session endded"); } catch { } } //if (!(Map is DuradosMap) && !string.IsNullOrEmpty(Map.securityConnectionString)) //{ // //MapMembershipProvider provider = new MapMembershipProvider(); // System.Web.Security.MembershipUser user =(System.Web.Security.Membership.Provider.GetUser(System.Web.HttpContext.Current.User.Identity.Name, System.Web.HttpContext.Current.User.Identity.IsAuthenticated)); // if(user!=null) // b=user.IsApproved && !user.IsLockedOut; //} Maps.Instance.DuradosMap.Logger.Log(((MvcHandler)httpContext.Handler).RequestContext.RouteData.Values["controller"].ToString() + " Authorization Filter", ((MvcHandler)httpContext.Handler).RequestContext.RouteData.Values["action"].ToString(), "username: "******", id: " + System.Web.HttpContext.Current.Request.QueryString["id"], null, 77, "url: " + System.Web.HttpContext.Current.Request.Url.ToString()); return(b); }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); AccountMembershipService membershipService = new AccountMembershipService(membershipProvider); AccountController controller = new AccountController(formsAuth, membershipService); ControllerContext controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller); controller.ControllerContext = controllerContext; return controller; }
protected override void Initialize(RequestContext requestContext) { if (MembershipService == null) { MembershipService = new AccountMembershipService(); } base.Initialize(requestContext); }
private static AccountController GetAccountController() { IFormsAuthentication formsAuth = new MockFormsAuthenticationService(); MembershipProvider membershipProvider = new MockMembershipProvider(); var membershipService = new AccountMembershipService(membershipProvider); var controller = new AccountController(formsAuth, new CommandServiceClient(), new MembershipReadModel()); var controllerContext = new ControllerContext(new MockHttpContext(), new RouteData(), controller); controller.ControllerContext = controllerContext; return controller; }