internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "administrator", }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { //userMgr.RemoveFromRoles(user.Id, "read", "edit"); IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
internal void AddUserAndRole() { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); IdentityResult IdRoleResult; IdentityResult IdUserResult; var roleStore = new RoleStore<IdentityRole>(context); var roleMgr = new RoleManager<IdentityRole>(roleStore); if (!roleMgr.RoleExists("administrator")) { IdRoleResult = roleMgr.Create(new IdentityRole { Name = "administrator" }); } var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var appUser = new ApplicationUser { UserName = "administrator", ImgUrl = "user2-160x160.jpg", Description = "High Level", SinceDate = new DateTime(2016, 1, 1) }; IdUserResult = userMgr.Create(appUser, "1qaz2wsxE"); var user = userMgr.FindByName("administrator"); if (!userMgr.IsInRole(user.Id, "administrator")) { IdUserResult = userMgr.AddToRole(userMgr.FindByName("administrator").Id, "administrator"); } }
public static void Seed(ApplicationDbContext context) { UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context); UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore); RoleStore<Role> roleStore = new RoleStore<Role>(context); RoleManager<Role> roleManager = new RoleManager<Role>(roleStore); if (!roleManager.RoleExists("Admin")) roleManager.Create(new Role { Name = "Admin" }); if (!roleManager.RoleExists("User")) roleManager.Create(new Role { Name = "User" }); IdentityResult result = null; ApplicationUser user1 = userManager.FindByName("[email protected]"); if (user1 == null) { user1 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" }; } result = userManager.Create(user1, "asdfasdf"); if (!result.Succeeded) { string error = result.Errors.FirstOrDefault(); throw new Exception(error); } userManager.AddToRole(user1.Id, "Admin"); user1 = userManager.FindByName("[email protected]"); ApplicationUser user2 = userManager.FindByName("[email protected]"); if (user2 == null) { user2 = new ApplicationUser { Email = "[email protected]", UserName = "[email protected]" }; } result = userManager.Create(user2, "asdfasfd"); if (!result.Succeeded) { string error = result.Errors.FirstOrDefault(); throw new Exception(error); } userManager.AddToRole(user2.Id, "User"); user2 = userManager.FindByName("[email protected]"); }
public static void Start() { using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new UsersDbContext()))) { foreach (var roleName in RolesList.Where(roleName => !roleManager.RoleExists(roleName))) { roleManager.Create(new IdentityRole(roleName)); } } using ( var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new UsersDbContext())) ) { if (userManager.FindByName(Constants.AdminUserName) != null) { return; } var admin = new ApplicationUser {UserName = Constants.AdminUserName}; var result = userManager.Create(admin, "AdminPass"); if (!result.Succeeded) { var txt = new StringBuilder(); foreach (var error in result.Errors) { txt.AppendLine(error); } throw new Exception(txt.ToString()); } userManager.AddToRole(admin.Id, Constants.Roles.Admin); } }
private void AddPermisionToADM(ApplicationDbContext db) { var userManarge = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db)); var user = userManarge.FindByName("[email protected]"); if (!userManarge.IsInRole(user.Id, "View")) { userManarge.AddToRole(user.Id, "View"); } if (!userManarge.IsInRole(user.Id, "Create")) { userManarge.AddToRole(user.Id, "Create"); } if (!userManarge.IsInRole(user.Id, "Edit")) { userManarge.AddToRole(user.Id, "Edit"); } if (!userManarge.IsInRole(user.Id, "Delete")) { userManarge.AddToRole(user.Id, "Delete"); } if (!userManarge.IsInRole(user.Id, "Adm")) { userManarge.AddToRole(user.Id, "Adm"); } }
public static void AddUserRole(string userName, string roleName) { using (var context = new ApplicationDbContext()) { try { if (!context.Roles.Any(r => r.Name == roleName)) return; var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var store = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(store); var user = userManager.FindByName(userName); var role = roleManager.FindByName(roleName); if (userManager.IsInRole(user.Id, role.Name)) return; userManager.AddToRole(user.Id, role.Name); context.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. // ReSharper disable once UnusedVariable var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); throw; } } }
public async Task<ActionResult> Create(DoctorViewModel DoctorViewModel) { if (ModelState.IsValid) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var user = new ApplicationUser() { UserName = DoctorViewModel.Email }; var result = await UserManager.CreateAsync(user, DoctorViewModel.Password); string roleName = "Doctor"; IdentityResult roleResult; if (!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } try { var findUser = UserManager.FindByName(DoctorViewModel.Email); UserManager.AddToRole(findUser.Id, "Doctor"); context.SaveChanges(); } catch { throw; } Doctor_Detail doctor = MapDoctor(DoctorViewModel); db.Doctor_Details.Add(doctor); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(DoctorViewModel); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataBindUserList(); DataBindRoleList(); } //sample to check security authentication //check the Request object that is part of every //internet trip if(Request.IsAuthenticated) { string msg = ""; msg += this.User.Identity.Name; UserManager um = new UserManager(); var theUser = um.FindByName(this.User.Identity.Name); if (string.IsNullOrEmpty(theUser.WaiterID.ToString())) { msg+= "is not a Waiter but a registered user."; } else { msg+= " has the following data: ID: " + theUser.WaiterID.ToString() + " Email: " + theUser.Email; } bob.Text = msg; } }
public PrivateMessageVM SetPMProperties(PrivateMessageVM privateMessageVM, string userid) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); privateMessageVM.PM.receiverId = userManager.FindByName(privateMessageVM.UserName).Id; privateMessageVM.PM.senderId = userManager.FindById(userid).Id; return privateMessageVM; }
private void InitDefaultUsersAndRoles(UserManager<QuestionsAnswersUser> userManager, RoleManager<IdentityRole> roleManager) { if (roleManager.FindByName("admin") == null) { roleManager.Create(new IdentityRole("admin")); } if (roleManager.FindByName("user") == null) { roleManager.Create(new IdentityRole("user")); } if (userManager.FindByName("admin") == null) { var user = new QuestionsAnswersUser {UserName = "admin"}; var result = userManager.Create(user, "adminadmin"); if (result.Succeeded) { userManager.AddToRole(user.Id, "admin"); } } userManager.Users.Where(u => !u.Roles.Any()).ToList().ForEach(u => userManager.AddToRole(u.Id, "user")); }
public ActionResult ChangeAcessMode(ScheduleAccessMode mode) { ApplicationDbContext context = new ApplicationDbContext(); if (HttpContext.User.IsInRole("Admin")) { var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); string userName = HttpContext.User.Identity.GetUserName(); var adminUser = userManager.FindByName(userName); adminUser.ScheduleAccessMode = mode; try { userManager.Update(adminUser); } catch (Exception ex) { return RedirectToAction("View","Error",new CustomError(ex.Message)); } string previousUrl = System.Web.HttpContext.Current.Request.UrlReferrer.AbsoluteUri; //return RedirectToAction("View", "Schedule", new { course = 1 }); return Redirect(previousUrl); } return RedirectToAction("View", "Error", new CustomError("Access Denied")); }
public ActionResult Create(int? Id, [Bind(Include = "Id,MessageId,Text,PublishDate")]Reply reply) { if (Id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } else { if (ModelState.IsValid) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); reply.User = userManager.FindByName(User.Identity.Name); reply.MessageId = (int)Id; reply.PublishDate = DateTime.Now; db.Replies.Add(reply); db.SaveChanges(); return RedirectToAction("Details", "Messages", new { id = Id }); } } return View(); }
public ActionResult Index() { MyIdentityDbContext db = new MyIdentityDbContext(); UserStore<MyIdentityUser> userStore = new UserStore<MyIdentityUser>(db); UserManager<MyIdentityUser> userManager = new UserManager<MyIdentityUser>(userStore); MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name); NorthWindEntities northwindDb = new NorthWindEntities(); List<Customer> customers = null; if (userManager.IsInRole(user.Id, "Administrator")) { customers = northwindDb.Customers.ToList(); } if (userManager.IsInRole(user.Id, "Operator")) { customers = northwindDb.Customers.Where(m => m.City == "USA").ToList(); } ViewBag.FullName = user.FullName + " (" + user.UserName + ") !"; return View(customers); }
public static ApplicationUser CreateUser(UserManager<ApplicationUser> userManager, string email, string firstName, string lastName, string password, bool lockOutEnabled) { var user = userManager.FindByName(email); if (user == null) { user = new ApplicationUser { UserName = email, Email = email, FirstName = firstName, LastName = lastName, EmailConfirmed = true }; try { userManager.Create(user, password); } catch (Exception ex) { Log4NetHelper.Log("Error creating Admin User", LogLevel.ERROR, "AspNetUser", 1, "none", ex); } userManager.SetLockoutEnabled(user.Id, lockOutEnabled); } return user; }
public ViewResult Index(int subid = 0, string search = "", int page = 1) { UserStore<User> userStore = new UserStore<User>(repository.Context); UserManager<User> userManager = new UserManager<User>(userStore); User user = userManager.FindByName(HttpContext.User.Identity.Name); QuestionListViewModel model = new QuestionListViewModel(); model.Questions = repository.Questions .Where(q => subid == 0 ? true : q.SubjectId == subid); model.Questions = model.Questions .Where(q => q.Description.Contains(search)); model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = model.Questions.Count() }; model.Questions = model.Questions .OrderByDescending(q => q.PublishedAt) .Skip((page - 1) * PageSize) .Take(PageSize); model.SubjectId = subid; model.Search = search; model.questionAddViewModel = new QuestionAddViewModel(); model.questionAddViewModel.Subjects = repository.Subjects .OrderBy(s => s.Year); return View(model); }
protected void RadGridUserList_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e) { var editableitem = ((GridEditableItem)e.Item); UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID); /// var useStore = new UserStore<AppUser>(new ApplicationDbContext()); var manager = new UserManager<AppUser>(useStore); string LogInUserName=(editableitem.FindControl("RtxtLoginID") as RadTextBox).Text.Trim(); var user = new AppUser { UserName = LogInUserName, FName = (editableitem.FindControl("RtxtFirstName") as RadTextBox).Text, LName = (editableitem.FindControl("RtxtLastName") as RadTextBox).Text }; IdentityResult result = manager.Create(user, (editableitem.FindControl("RtxtPassword") as RadTextBox).Text); if (result.Succeeded) { //Get The Current Created UserInfo AppUser CreatedUser = manager.FindByName(LogInUserName); var RoleAddResult = manager.AddToRole(CreatedUser.Id.Trim(), (editableitem.FindControl("RDDListRole") as RadDropDownList).SelectedItem.Text.Trim()); lblMessage.Text = string.Format("User {0} is creted successfully", user.UserName); } else { lblMessage.Text = result.Errors.FirstOrDefault(); e.Canceled = true; } }
internal bool RemoveUser(string username) { Models.ApplicationDbContext context = new Models.ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); userMgr.Delete(userMgr.FindByName(username)); return true; }
internal bool UpdateUser(string username, string realUsername, string permission) { IdentityResult result = null; Models.ApplicationDbContext context = new Models.ApplicationDbContext(); var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var user = userMgr.FindByName(username); if (!string.IsNullOrEmpty(realUsername)) { user.RealUserName = realUsername; result = userMgr.Update(user); } if (!string.IsNullOrEmpty(permission) && !userMgr.IsInRole(user.Id, permission)) { userMgr.RemoveFromRoles(user.Id, "read", "edit", "administrator"); switch (permission) { case "administrator": result = userMgr.AddToRole(user.Id, "administrator"); break; case "edit": result = userMgr.AddToRole(user.Id, "edit"); break; default: result = userMgr.AddToRole(user.Id, "read"); break; } } if (result == IdentityResult.Success) return true; else return false; }
public ActionResult Index() { try { if (User.Identity.IsAuthenticated) { // Refresh the session object var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); HelperService.SetSiteUserProfile(userManager.FindByName(User.Identity.Name), new dbTIREntities()); } if (User.IsInRole("Adminstrator")) { Session["UserIsAdmin"] = true; //return list of teacher in my scope return View(); } else { Session["UserIsAdmin"] = false; } return View(); } catch (Exception ex) { Logging log = new Logging(); log.LogException(ex); return View("GeneralError"); } }
public IdentityUser FindUser(string userName) { var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>()); var user = userManager.FindByName(userName); return user; }
// Get user info for a specific user name public ApplicationUserBase GetUserInfo(string userName) { // Create a user manager object var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ds)); // Attempt to fetch the user object var userObject = userManager.FindByName(userName); if (userObject==null) { return null; } else { // Prepare a view model object var appUser = Mapper.Map<ApplicationUserBase>(userObject); // Add the role names foreach (var role in userObject.Roles) { appUser.RolesForUser.Add(role.Role.Name); } return appUser; } }
public ActionResult DisableUser() { List<string> users; List<string> enabledUsers; List<string> disabledUsers; using (var ctx = new ApplicationDbContext()) { var userStore = new UserStore<ApplicationUser>(ctx); var userManager = new UserManager<ApplicationUser>(userStore); users = (from u in userManager.Users select u.UserName).ToList(); disabledUsers = new List<string>(users); enabledUsers = new List<string>(users); foreach (var user in users) { if (!userManager.FindByName(user).LockoutEnabled) { disabledUsers.Remove(user); } else { enabledUsers.Remove(user); } } ViewBag.EnabledUsers = new SelectList(enabledUsers); ViewBag.DisabledUsers = new SelectList(disabledUsers); } return View(); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { return false; } // Get the AD groups var groups = Roles.Split(',').ToList<string>(); // Verify that the user is in the given AD group (if any) UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); var user = httpContext.User.Identity; ApplicationUser userPrincipal = UserManager.FindByName(httpContext.User.Identity.GetUserName()); if (userPrincipal != null) foreach (string group in groups) { if (userPrincipal.AdminRole && group.Equals("Admin")) return true; if (userPrincipal.ConferenceRole && group.Equals("Conference")) return true; if (userPrincipal.ShowRole && group.Equals("Show")) return true; return false; } return true; }
// check if user exists in database public static bool UserExists(string userName) { using (var tmpUserManager = new UserManager<VoatUser>(new UserStore<VoatUser>(new ApplicationDbContext()))) { var tmpuser = tmpUserManager.FindByName(userName); return tmpuser != null; } }
// The id parameter should match the DataKeyNames value set on the control // or be decorated with a value provider attribute, e.g. [QueryString]int id public UniversalProviders_Identity_Migrations.Models.ProfileInfo ProfileForm_GetItem(int? id) { var manager = new UserManager(); var user = manager.FindByName(User.Identity.Name); return user.Profile; }
// return user registration date public static DateTime GetUserRegistrationDateTime(string userName) { using (var tmpUserManager = new UserManager<VoatUser>(new UserStore<VoatUser>(new ApplicationDbContext()))) { var tmpuser = tmpUserManager.FindByName(userName); return tmpuser != null ? tmpuser.RegistrationDateTime : DateTime.MinValue; } }
// return original username public static string OriginalUsername(string userName) { using (var tmpUserManager = new UserManager<VoatUser>(new UserStore<VoatUser>(new ApplicationDbContext()))) { var tmpuser = tmpUserManager.FindByName(userName); return tmpuser != null ? tmpuser.UserName : null; } }
public FTPerfil(UserManager<ApplicationUser> userManager,string username) { var user = userManager.FindByName(username); if (user.perfil != null) { this.fotobase = Convert.ToBase64String(user.perfil); } }
public async Task<ActionResult> DisableUser(string userName) { List<string> users; List<string> enabledUsers; List<string> disabledUsers; using (var context = new ApplicationDbContext()) { var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var selectedUser = userManager.FindByName(userName); if (selectedUser == null) throw new Exception("User not found!"); if (!selectedUser.UserName.Equals("[email protected]")) { if (!selectedUser.LockoutEnabled) { userManager.SetLockoutEnabled(selectedUser.Id, true); DateTime lockoutDate = DateTime.Now.AddYears(50); await userManager.SetLockoutEndDateAsync(selectedUser.Id, lockoutDate); context.SaveChanges(); userManager.Update(selectedUser); ViewBag.ResultMessage = "Disabled successfully !"; } } else { ViewBag.ResultMessage = "Cannot disable Admin"; } users = (from u in userManager.Users select u.UserName).ToList(); disabledUsers = new List<string>(users); enabledUsers = new List<string>(users); foreach (var user in users) { if (!userManager.FindByName(user).LockoutEnabled) { disabledUsers.Remove(user); } else { enabledUsers.Remove(user); } } } ViewBag.EnabledUsers = new SelectList(enabledUsers); ViewBag.DisabledUsers = new SelectList(disabledUsers); return View(); }
public void HandleCommand(UserManager<User> userManager, string message, Player player) { try { string commandText = message.Split(' ')[0]; message = message.Replace(commandText, "").Trim(); commandText = commandText.Replace("/", "").Replace(".", ""); string[] arguments = message.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); List<CommandAttribute> foundCommands = new List<CommandAttribute>(); foreach (var handlerEntry in _pluginCommands) { CommandAttribute commandAttribute = handlerEntry.Value; if (!commandText.Equals(commandAttribute.Command, StringComparison.InvariantCultureIgnoreCase)) continue; MethodInfo method = handlerEntry.Key; if (method == null) return; foundCommands.Add(commandAttribute); var authorizationAttributes = method.GetCustomAttributes<AuthorizeAttribute>(true); foreach (AuthorizeAttribute authorizationAttribute in authorizationAttributes) { if (userManager == null) { player.SendMessage($"UserManager not found. You are not permitted to use this command!"); return; } User user = userManager.FindByName(player.Username); if (user == null) { player.SendMessage($"No registered user '{player.Username}' found. You are not permitted to use this command!"); return; } var userIdentity = userManager.CreateIdentity(user, "none"); if (!authorizationAttribute.OnAuthorization(new GenericPrincipal(userIdentity, new string[0]))) { player.SendMessage("You are not permitted to use this command!"); return; } } if (ExecuteCommand(method, player, arguments)) return; } foreach (var commandAttribute in foundCommands) { player.SendMessage($"Usage: {commandAttribute.Usage}"); } } catch (Exception ex) { Log.Warn(ex); } }