private static void CreateAdminUser(UserManager<ApplicationUser> userManager) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ContosoWebContext(StaticConfig.DbContext.WebConnectionStringName))); if (!roleManager.RoleExists(AdminConstants.Role)) { roleManager.Create(new IdentityRole(AdminConstants.Role)); } var username = ConfigurationHelpers.GetString("Authentication.Administrator.UserName"); var password = ConfigurationHelpers.GetString("Authentication.Administrator.Password"); var user = userManager.FindByName(username); if (user == null) { user = new ApplicationUser { UserName = username, Email = username }; var result = userManager.Create(user, password); if (!result.Succeeded) throw new Exception(string.Format("Failed to create admin user: {0}", string.Join(",", result.Errors))); user = userManager.FindByName(username); userManager.AddToRole(user.Id, AdminConstants.Role); userManager.AddClaim(user.Id, new Claim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed)); } }
public ActionResult DeleteRoleForUser(string userName, string roleName) { List<string> userRoles; List<string> roles; List<string> users; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); roles = (from r in roleManager.Roles select r.Name).ToList(); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); var user = userManager.FindByName(userName); if (user == null) throw new Exception("User not found!"); if (userManager.IsInRole(user.Id, roleName)) { userManager.RemoveFromRole(user.Id, roleName); context.SaveChanges(); ViewBag.ResultMessage = "Role removed from this user successfully !"; } else { ViewBag.ResultMessage = "This user doesn't belong to selected role."; } var userRoleIds = (from r in user.Roles select r.RoleId); userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select r.Name).ToList(); } ViewBag.RolesForThisUser = userRoles; ViewBag.Roles = new SelectList(roles); ViewBag.Users = new SelectList(users); return View("RoleAddToUser"); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // App Harbor load balancers run HTTP internally. This will confuse ASP.NET into believing a secure connection is not app.Use(async (context, next) => { if (string.Equals(context.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.InvariantCultureIgnoreCase)) { context.Request.Scheme = "https"; } await next.Invoke(); }); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); // Google Oauth2 provider. app.UseGoogleAuthentication(ConfigurationManager.AppSettings["GoogleAuthKey"], ConfigurationManager.AppSettings["GoogleAuthSecret"]); // LinkedIn var linkedInSettings = new LinkedInAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["LinkedInKey"], ClientSecret = ConfigurationManager.AppSettings["LinkedInSecret"] }; linkedInSettings.Scope.Add("r_basicprofile"); linkedInSettings.Provider = new LinkedInAuthenticationProvider() { OnAuthenticated = async context => { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = userManager.FindByName(context.Request.User.Identity.Name); userManager.AddClaim(user.Id, new Claim("LinkedIn_AccessToken", context.AccessToken)); } }; linkedInSettings.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie; app.UseLinkedInAuthentication(linkedInSettings); // Owin context for claims }
public ActionResult GetRoles(string userName) { if (!string.IsNullOrWhiteSpace(userName)) { List<string> userRoles; List<string> roles; List<string> users; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); roles = (from r in roleManager.Roles select r.Name).ToList(); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); var user = userManager.FindByName(userName); if (user == null) throw new Exception("User not found!"); var userRoleIds = (from r in user.Roles select r.RoleId); userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select r.Name).ToList(); } ViewBag.Roles = new SelectList(roles); ViewBag.Users = new SelectList(users); ViewBag.RolesForThisUser = userRoles; } return View("RoleAddToUser"); }
public ActionResult RoleAddToUser(string roleName, string userName) { List<string> roles; List<string> users; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); var user = userManager.FindByName(userName); if (user == null) throw new Exception("User not found!"); var role = roleManager.FindByName(roleName); if (role == null) throw new Exception("Role not found!"); if (userManager.IsInRole(user.Id, role.Name)) { ViewBag.ResultMessage = "This user already has the role specified !"; } else { userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); ViewBag.ResultMessage = "Username added to the role succesfully !"; } roles = (from r in roleManager.Roles select r.Name).ToList(); } ViewBag.Roles = new SelectList(roles); ViewBag.Users = new SelectList(users); return View(); }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); #region Add Admin and Role for Admin using (var context = new ApplicationDbContext()) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var aspUser = UserManager.FindByName(Constant.USER_USERNAME); if (aspUser != null) { UserManager.RemovePassword(aspUser.Id); UserManager.AddPassword(aspUser.Id, Constant.USER_PASS); } else { aspUser = new ApplicationUser() { UserName = Constant.USER_USERNAME }; var result = UserManager.Create(aspUser, Constant.USER_PASS); if (result.Succeeded) { var user = new User { UserName = Constant.USER_USERNAME, Email = Constant.USER_EMAIL, Phone = Constant.USER_PHONE, Address = Constant.USER_ADDRESS, AspnetId = aspUser.Id }; using (var db = new TShirtEntities()) { db.User.Add(user); db.SaveChanges(); } } } // Create Role IdentityResult roleResult = null; if (!RoleManager.RoleExists(Constant.ROLES_ADMIN)) { roleResult = RoleManager.Create(new IdentityRole(Constant.ROLES_ADMIN)); } // Add role to admin if (roleResult != null && roleResult.Succeeded) UserManager.AddToRole(aspUser.Id, Constant.ROLES_ADMIN); } #endregion #region Add Constants Config var lstConfig = new List<Config>(); using (var db = new TShirtEntities()) { var fb = db.Config.FirstOrDefaultAsync(m => m.Code == Constant.CODE_MESS_FACEBOOK); var price = db.Config.FirstOrDefaultAsync(m => m.Code == Constant.CODE_PRICE_DESIGN); if (fb == null) { lstConfig.Add(new Config() { Code = Constant.CODE_MESS_FACEBOOK, Value = "Website thiết kế áo chuyên nghiệp", Description = "Nội dung khi chia sẻ trên facebook" }); } if (price == null) { lstConfig.Add(new Config() { Code = Constant.CODE_PRICE_DESIGN, Value = "15000", Description = "Giá một icon design" }); } if (lstConfig.Count > 0) { db.Config.AddRange(lstConfig); db.SaveChanges(); } } #endregion }
public ActionResult AddRoleToUser(string roleName, string userName) { List<string> roles; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByName(userName); if (user == null) { throw new Exception("User not found!"); } if (roleManager == null) { throw new Exception("Roles not found!"); } var role = roleManager.FindByName(roleName); if (userManager.IsInRole(user.Id, role.Name)) { ViewBag.ErrorMessage = "This user already has the role specified!"; roles = (from r in roleManager.Roles select r.Name).ToList(); ViewBag.Roles = new SelectList(roles); ViewBag.UserName = userName; return View(); } else { userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); List<string> userRoles; var userRoleIds = (from r in user.Roles select r.RoleId); userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select r.Name).ToList(); ViewBag.UserName = userName; ViewBag.RolesForUser = userRoles; return View("ViewUserRoles"); } } }
public ActionResult DeleteRoleForUser(string userName = null, string roleName = null) { if ((!string.IsNullOrWhiteSpace(userName)) || (!string.IsNullOrWhiteSpace(roleName))) { List<string> userRoles; using (var context = new ApplicationDbContext()) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = userManager.FindByName(userName); if (user == null) { throw new Exception("User not found!"); } if (userManager.IsInRole(user.Id, roleName)) { userManager.RemoveFromRole(user.Id, roleName); context.SaveChanges(); } var userRoleIds = (from r in user.Roles select r.RoleId); userRoles = (from id in userRoleIds let r = roleManager.FindById(id) select r.Name).ToList(); } ViewBag.UserName = userName; ViewBag.RolesForUser = userRoles; return View("ViewUserRoles"); } else { return View("Index"); } }