protected async void UpdateForm() { if (Request["isUpdate"] == "true") { string newpass = Request["txt_newpass"]; string oldpass = Request["txt_oldpass"]; if (!string.IsNullOrEmpty(newpass)) { if (!string.IsNullOrEmpty(oldpass)) { if (newpass == Request["txt_newpass2"]) { store = new UserStore<User>(new ApplicationDbContext()); manager = new Microsoft.AspNet.Identity.UserManager<User>(store); User user1 = manager.FindById(HttpContext.Current.User.Identity.GetUserId()); var task = await manager.ChangePasswordAsync(u.Id, oldpass, newpass); if (task.Errors.ToList().Count > 0) { SiteLogic.AddError(task.Errors.ToList()[0]); } else { FormMessage.ShowSuccess(GetLocalResourceObject("err1").ToString()); } } else SiteLogic.AddError(GetLocalResourceObject("err2").ToString()); } else SiteLogic.AddError(GetLocalResourceObject("err3").ToString()); } else SiteLogic.AddError(GetLocalResourceObject("err4").ToString()); } }
public IIdentityManagerService Create() { #if USE_INT_PRIMARYKEY var db = new IdentityDbContext <CustomUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>(connString); var store = new UserStore <CustomUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>(db); var usermgr = new UserManager <CustomUser, int>(store); usermgr.PasswordValidator = new PasswordValidator { RequiredLength = 3 }; var rolestore = new RoleStore <CustomRole, int, CustomUserRole>(db); var rolemgr = new RoleManager <CustomRole, int>(rolestore); var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService <CustomUser, int, CustomRole, int>(usermgr, rolemgr); var dispose = new DisposableIdentityManagerService(svc, db); return(dispose); #else var db = new IdentityDbContext <IdentityUser>(this.connString); var userstore = new UserStore <IdentityUser>(db); var usermgr = new Microsoft.AspNet.Identity.UserManager <IdentityUser>(userstore); usermgr.PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator { RequiredLength = 3 }; var rolestore = new RoleStore <IdentityRole>(db); var rolemgr = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(rolestore); var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService <IdentityUser, string, IdentityRole, string>(usermgr, rolemgr); var dispose = new DisposableIdentityManagerService(svc, db); return(dispose); #endif }
public ActionResult GetUserIDLogic() { string UserID = User.Identity.GetUserId(); string UserName = User.Identity.GetUserName(); ApplicationUser user = _AccountContext.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var userManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_AccountContext)); ViewBag.UserRoles = userManager.GetRoles(user.Id); foreach (var role in ViewBag.UserRoles) { switch (role) { case "Admin": return(RedirectToAction("AdminHomePage", new { Controller = "Admin" })); case "Staff": return(RedirectToAction("ManageUniversities", new { Controller = "Admin" })); case "Applicant": return(RedirectToAction("ShowUserProfile", new { UserID = UserID, Controller = "Applicant" })); default: break; } } return(View()); }
public ActionResult CreateEmployee(FormCollection form) { bool isAvailable = true; ViewBag.error = ""; var UserManager = new Microsoft.AspNet.Identity.UserManager <AspNetUser>(new UserStore <AspNetUser>(context)); string UserName = form["txtEmail"]; string email = form["txtEmail"]; string pwd = "Caretta.97"; List <AspNetUser> uList = db.Users.ToList(); foreach (var item in uList) { if (item.Email == email) { ViewBag.error = "The employee you want to add is already registered."; isAvailable = false; } } if (isAvailable) { var user = new AspNetUser(); user.UserName = UserName; user.Email = email; user.pwdChanged = false; var newUser = UserManager.Create(user, pwd); UserManager.AddToRole(user.Id, "personel"); ViewBag.error = "The employee you want to add has been successfully registered."; } return(View()); }
public ActionResult DifferentPage(string UserName) { string Role = null; string Page = null; string controller = null; ApplicationUser user = _context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser> (new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context)); foreach (string rm in um.GetRoles(user.Id)) { Role = rm; } if (Role == "Applicant") { Page = "searchUserProfile"; controller = "Profiles"; } if (Role == "Admin" || Role == "Staff") { Page = "AdminAndStaff"; controller = "Admin"; } return(RedirectToAction(Page, controller)); }
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(Microsoft.AspNet.Identity.UserManager <WfpUser, string> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here try { using (WfpictContext ctx = new WfpictContext()) { var userId = userIdentity.GetUserId(); var user = ctx.Users.Include(x => x.Roles).FirstOrDefault(x => x.Id == userId); if (user != null) { foreach (var role in user.Roles) { var roleClaims = ctx.RoleClaims.Include("Claim").Where(x => x.RoleId == role.RoleId); foreach (var roleClaim in roleClaims) { userIdentity.AddClaim(new Claim(ClaimTypes.UserData, roleClaim.Claim.ClaimValue)); } } } } } catch (Exception ex) { // ignored } return(userIdentity); }
public ActionResult ManageUserRoles(string UserName, string RoleName) { ApplicationUser user = _context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context)); var idResult = um.AddToRole(user.Id, RoleName); // Prepopulate roles for the view dropdown var roleList = _context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); ViewBag.Roles = roleList; // Prepopulate users for the view dropdown var userList = _context.Users.OrderBy(u => u.UserName).ToList().Select(uu => new SelectListItem { Value = uu.UserName.ToString(), Text = uu.UserName }).ToList(); ViewBag.Users = userList; return(View("ManageUserRoles")); }
protected override void Seed(MPSContext context) { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); var userManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); //uzytkownicy o roli Admin roleManager.Create(new IdentityRole("Admin")); var u1 = new ApplicationUser { Email = "*****@*****.**", UserName = "******" }; string passwor = "Biblioteka1@"; userManager.Create(u1, passwor); userManager.AddToRole(u1.Id, "Admin"); var uu1 = new UserNew { UserName = "******", Id = u1.Id }; context.User.Add(uu1); context.SaveChanges(); /* var P = new Person * { * Name = "", * Surname = "" * * };*/ // context.Person.Add(P); // context.SaveChanges(); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser> (new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context)); um.AddToRole(user.Id, "Applicant"); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("AddProfile", "NAAAdmin")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task TestMethod0() { IdentityTableContext<IdentityUser> context = new IdentityTableContext<IdentityUser>( new CloudStorageAccount(new StorageCredentials("c1azuretests", File.ReadAllText("C:\\dev\\storagekey.txt")), true)); var store = new UserStore<IdentityUser>(context); var mgr = new Microsoft.AspNet.Identity.UserManager<IdentityUser>(store); var obj = await mgr.FindAsync(new UserLoginInfo("google", "notfound")); Assert.IsNull(obj); var username="******"+Guid.NewGuid().ToString().Substring(0,5); var user = new IdentityUser(username); var result = await mgr.CreateAsync(user); Trace.WriteLine(string.Join(", ", result.Errors)); Assert.AreEqual(0, result.Errors.Count()); var userFromDb = await mgr.FindByIdAsync(user.Id); Assert.IsNotNull(userFromDb); }
private void createRolesandUsers(string username, string userType) { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new Microsoft.AspNet.Identity.RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var UserManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); if (!roleManager.RoleExists("Employee") && userType == "1") { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Employee"; roleManager.Create(role); } if (!roleManager.RoleExists("Customer") && userType == "2") { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Customer"; roleManager.Create(role); } string s; if (userType == "1") { s = "Employee"; } else { s = "Customer"; } var result1 = UserManager.AddToRole(username, s); }
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(Microsoft.AspNet.Identity.UserManager <MarketplaceUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return(userIdentity); }
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(Microsoft.AspNet.Identity.UserManager <ApplicationUser> manager) { // Observe que o authenticationType deve corresponder àquele definido em CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Adicionar declarações de usuário personalizado aqui return(userIdentity); }
//from webapi for OWin public async Task <ClaimsIdentity> GenerateUserIdentityAsync(Microsoft.AspNet.Identity.UserManager <AspNetIdentityUser, string> manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return(userIdentity); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { ApplicationUser user = _context.Users.Where(u => u.UserName.Equals(model.Email, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context)); ViewBag.RolesForThisUser = um.GetRoles(user.Id); string uid = user.Id; if (!ModelState.IsValid) { return(View(model)); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: ViewBag.userId = uid; if (um.GetRoles(user.Id) == null) { return(RedirectToAction("ApplicantHome", new { Controller = "Home" })); } else { if (um.GetRoles(user.Id).Contains("Admin")) { return(RedirectToAction("AdminHome", new { Controller = "Home" })); } else if (um.GetRoles(user.Id).Contains("Staff")) { return(RedirectToAction("StaffHome", new { Controller = "Home" })); } else { return(RedirectToAction("ApplicantHome", new { Controller = "Home" })); } } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
protected override void Seed(ThingWall.Data.DataContext context) { //PROTIP: tutaj mo¿na wype³niæ bazê danych wstêpnymi danymi //UWAGA: trzeba sprawdzaæ, czy dany rekord ju¿ istnieje, Seed uruchamiany jest po ka¿dej migracji var examples = new List <ExampleItem>() { new ExampleItem() { Name = "Test 1" }, new ExampleItem() { Name = "Test 2" }, new ExampleItem() { Name = "Test 3" } }; //PROTIP: mechanizm u¿ytkowników dostarza ASP.NET Identity //klasa UserManager pozwala trochê ³atwiej ich ogarn¹æ var userManager = new Microsoft.AspNet.Identity.UserManager <User>(new UserStore <User>(context)); var testUser = userManager.FindByEmail("*****@*****.**"); if (testUser == null) { var hasher = new PasswordHasher(); testUser = new User() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true, PasswordHash = hasher.HashPassword("test"), Nick = "NowyNick" }; userManager.Create(testUser); } foreach (var example in examples) { if (!context.ExampleItems.Any(i => i.Name == example.Name)) { //PROTIP: ustawianie klucza obcego wystarczy do "zrobienia" relacji example.OwnerId = testUser.Id; context.ExampleItems.Add(example); } } //PROTIP: SaveChanges poza pêtl¹ wrzuca wszystkie zmiany w kolejce jednym zapytaniem context.SaveChanges(); }
public MyUser getMyUser() { this.ApplicationDbContext = new ApplicationDbContext(); this.UserManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(this.ApplicationDbContext)); ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); return(new MyUser { UserName = user.UserName, Address = user.Address, FullName = user.FullName, Email = user.Email }); }
public AspNetIdentityUserService(Microsoft.AspNet.Identity.UserManager <TUser> userManager, Func <string> parseSubject = null) { if (userManager == null) { throw new ArgumentNullException("userManager"); } _userManager = userManager; EnableSecurityStamp = true; }
public AccountController() { var userStore = new UserStore <ApplicationUser>(new Identity.IdentityDbContext()); userManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(userStore); var roleStore = new RoleStore <ApplicationRole>(new Identity.IdentityDbContext()); roleManager = new Microsoft.AspNet.Identity.RoleManager <ApplicationRole>(roleStore); }
public void AddUserRole(string id, string role) { UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db); Microsoft.AspNet.Identity.UserManager<ApplicationUser> userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(userStore); userManager.AddToRole(id, role); db.SaveChanges(); //return userManager; }
public ActionResult GetRolesforUser(string UserName) { if (!string.IsNullOrWhiteSpace(UserName)) { var user = _context.Users.FirstOrDefault(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)); var um = new Microsoft.AspNet.Identity.UserManager <IdentityUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <IdentityUser>(_context)); ViewBag.RolesForThisUser = um.GetRoles(user.Id); } return(View("GetRolesforUserConfirmed")); } // GET: Admin
public async Task <ClaimsIdentity> GenerateUserIdentityAsync(Microsoft.AspNet.Identity.UserManager <eCommerceUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim("Email", Email)); userIdentity.AddClaim(new Claim("Picture", this.Picture != null ? this.Picture.URL : string.Empty)); return(userIdentity); }
public static IUserManager Create() { var db = new IdentityDbContext<IdentityUser>("DefaultConnection"); var store = new UserStore<IdentityUser>(db); var mgr = new Microsoft.AspNet.Identity.UserManager<IdentityUser>(store); return new Thinktecture.IdentityManager.AspNetIdentity.UserManager<IdentityUser>(mgr, db); //var db = new CustomDbContext("CustomAspId"); //var store = new CustomUserStore(db); //var mgr = new CustomUserManager(store); //return new Thinktecture.IdentityManager.AspNetIdentity.UserManager<CustomUser, int, CustomUserLogin, CustomUserRole, CustomUserClaim>(mgr, db); }
public ActionResult AssignRole(FormCollection form) { string username = form["txtUserName"]; string rolname = form["RoleName"]; AspNetUser user = context.Users.Where(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var userManager = new Microsoft.AspNet.Identity.UserManager <AspNetUser>(new UserStore <AspNetUser>(context)); userManager.AddToRole(user.Id, rolname); return(View("Index")); }
//[Authorize(Roles = "Admin")] public ActionResult ManageUserRoles(string UserName, string RoleName) { ApplicationUser user = _DBcontext.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_DBcontext)); var idResult = um.AddToRole(user.Id, RoleName); //populate roles for the view dropdown ViewBag.Roles = _abcLib.PopulateRoleListItem(); //populate users for the view dropdown ViewBag.Users = _abcLib.PopulateUserListItem(); return(View("ManageUserRoles")); }
public static IUserManager Create() { var db = new IdentityDbContext <IdentityUser>("DefaultConnection"); var store = new UserStore <IdentityUser>(db); var mgr = new Microsoft.AspNet.Identity.UserManager <IdentityUser>(store); return(new Thinktecture.IdentityManager.AspNetIdentity.UserManager <IdentityUser>(mgr, db)); //var db = new CustomDbContext("CustomAspId"); //var store = new CustomUserStore(db); //var mgr = new CustomUserManager(store); //return new Thinktecture.IdentityManager.AspNetIdentity.UserManager<CustomUser, int, CustomUserLogin, CustomUserRole, CustomUserClaim>(mgr, db); }
public void CreateAdmin() { var userManger = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db)); var user = new ApplicationUser(); user.Email = "*****@*****.**"; user.UserName = "******"; var isUserExist = userManger.Create(user, "123456"); if (isUserExist.Succeeded) { userManger.AddToRole(user.Id, "Admin"); } }
public ActionResult ManageUserRoles(UserViewModel model) { var user = _context.Users.FirstOrDefault(u => u.UserName.Equals(model.UserName, StringComparison.CurrentCultureIgnoreCase)); var um = new Microsoft.AspNet.Identity.UserManager <IdentityUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <IdentityUser>(_context)); um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Applicant); um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Admin); um.RemoveFromRole(user.Id, Helpers.Constants.Roles.Staff); var idResult = um.AddToRole(user.Id, model.RoleName); model = GetUserViewModel(model.UserName); return(View("ManageUserRoles", model)); }
public bool AddRole(string role) { var userManager = new Microsoft.AspNet.Identity.UserManager <MyUser, int>(new MyUserStore(new ApplicationDbContext())); try { userManager.AddToRole(this.Id, role); return(true); } catch { return(false); } }
public List <string> GetUserRoles(string username) { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var UserManager = new Microsoft.AspNet.Identity.UserManager <User>(new UserStore <User>(context)); List <string> ListOfRoleNames = new List <string>(); var ListOfRoleIds = UserManager.FindById(username).Roles.Select(x => x.RoleId).ToList(); foreach (string id in ListOfRoleIds) { string rolename = roleManager.FindById(id).Name; ListOfRoleNames.Add(rolename); } return(ListOfRoleNames); }
protected override string CreateUniqueUserName(Microsoft.AspNet.Identity.UserManager <ApplicationUser> userManager, Microsoft.AspNet.Identity.Owin.ExternalLoginInfo externalLoginInfo) { Assert.ArgumentNotNull((object)userManager, nameof(userManager)); Assert.ArgumentNotNull((object)externalLoginInfo, nameof(externalLoginInfo)); IdentityProvider identityProvider = this.FederatedAuthenticationConfiguration.GetIdentityProvider(externalLoginInfo.ExternalIdentity); if (identityProvider == null) { throw new InvalidOperationException("Unable to retrieve identity provider for given identity"); } string domain = identityProvider.Domain; string email = externalLoginInfo.DefaultUserName; // return email and domain return($"{domain}\\\\\\\\{email}"); }
public ActionResult GetRolesforUser(string UserName) { if (!string.IsNullOrWhiteSpace(UserName)) { ApplicationUser user = _context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); var um = new Microsoft.AspNet.Identity.UserManager <ApplicationUser> (new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(_context)); if (um.GetRoles(user.Id) != null) { ViewBag.RolesForThisUser = um.GetRoles(user.Id); } ViewBag.ThisUser = user.UserName; } return(View("CheakRole")); }
/// <summary> /// Step 1 : user creation /// </summary> /// <param name="model">Registration details</param> /// <returns></returns> public int RegisterUser(ParticipantRegistration model) { string createdBy = string.Empty; int userDetailsID = 0; #region Create useer using (OCASIAMeetingUOW db = new OCASIAMeetingUOW()) { var res = db.Repository <ApplicationUser>().GetAll().Where(f => f.Email == model.Email).FirstOrDefault(); if (res == null) { var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, RoleCustomID = 3, IsActive = true, IspasswordActive = true }; var userManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(new OCASIAMeetingContext())); var ures = userManager.Create(user, model.Password); if (ures.Succeeded) { // userManager.AddClaim(user.Id, new System.Security.Claims.Claim("FullName", model.Email)); Passwordhash mdl = new Passwordhash() { UserId = user.Id, Password = model.Password }; db.Repository <Passwordhash>().Add(mdl); db.SaveChanges(); createdBy = mdl.UserId; } } else { return(-1); } } #endregion if (string.IsNullOrEmpty(createdBy)) { return(userDetailsID); } userDetailsID = CreateUserDetails(model, createdBy); return(userDetailsID); }
public async Task <ActionResult> EditProfile(ApplicationUser _user) { ////get current user and update //var userCurnt = await UserManager.FindByIdAsync(User.Identity.GetUserId()); //userCurnt.Image = _user.Image; //userCurnt.UserName = _user.UserName; //userCurnt.Email = _user.Email; //var updateResult = await UserManager.UpdateAsync(user); //if (updateResult.Succeeded) //{ // //do something and return // return RedirectToAction("showprofile"); //} ////failed - do something else and return //return View(); if (!ModelState.IsValid) { return(View(_user)); } var userStore = new UserStore <ApplicationUser>(new ApplicationDbContext()); var appManager = new Microsoft.AspNet.Identity.UserManager <ApplicationUser>(userStore); var currentUser = appManager.FindByEmail(_user.Email); // here you can assign the updated values currentUser.Image = _user?.Image; currentUser.Email = _user?.Email; currentUser.UserName = _user?.UserName; // and rest fields are goes here await appManager.UpdateAsync(currentUser); var ctx = userStore.Context; ctx.SaveChanges(); // now you can redirect to some other method or-else you can return // to this view itself by returning the data return(RedirectToAction("showProfile")); }
private void UpdateFormNew() { if (!string.IsNullOrEmpty(Request["isUpdate"]) && Request["isUpdate"] == "true") { store = new UserStore<User>(new ApplicationDbContext()); manager = new Microsoft.AspNet.Identity.UserManager<User>(store); User user = manager.FindById(HttpContext.Current.User.Identity.GetUserId()); TryUpdateModel(user, new FormValueProvider(ModelBindingExecutionContext)); if (ModelState.IsValid) { var result = Task.Run(() => manager.UpdateAsync(user)).Result; store.Context.SaveChanges(); UL.SetLoggedUser(user); FormMessage.ShowSuccess(GetLocalResourceObject("Success").ToString()); } else { u.Email = u.UserName; } } }
public void RemoveUserRole(string id, string role) { UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db); Microsoft.AspNet.Identity.UserManager<ApplicationUser> userManager = new Microsoft.AspNet.Identity.UserManager<ApplicationUser>(userStore); //var oldRole = System.Web.Security.Roles.GetRolesForUser().Single(); //var account = new AccountController(); //var oldRole = account.UserManager.GetRoles(id); userManager.RemoveFromRole(id, role); db.SaveChanges(); //return userManager; }