public UserServices(IdentityContext identityContext) { _identityContext = identityContext; _password = _identityContext.Set <Password>(); _user = _identityContext.Set <User>(); _loginAttempt = _identityContext.Set <LoginAttempt>(); }
public ActionResult EditUser(ApplicationUser User1) { if (ModelState.IsValid) { UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext())); //جهت فعال کردن امکان ثبت نام فارسی UserManager1.UserValidator = new UserValidator <ApplicationUser>(UserManager1) { AllowOnlyAlphanumericUserNames = false }; if ((UserManager1.FindByName(User1.UserName) == null) || (UserManager1.FindById(User1.Id).UserName == User1.UserName)) { IdentityContext IdentityContext1 = new IdentityContext(); IdentityContext1.Entry(User1).State = System.Data.Entity.EntityState.Modified; IdentityContext1.SaveChanges(); //return RedirectToAction("AllUsers"); return(Json(new { success = true })); } else { ModelState.AddModelError("", "نام" + User1.UserName + "قبلا انتخاب شده است."); } } else { ModelState.AddModelError("", "داده های وارد شده نامعتبراند"); } return(PartialView("_EditUser", User1)); }
public async Task OnPostDeleteProyectosPersonales_VerSiRealmenteBorra() { // Arrange //Preparamos un contexto que guarde la base de datos en memoria ram. var OptionsBuilder = new DbContextOptionsBuilder <IdentityContext>() .UseInMemoryDatabase("InMemoryDb"); IdentityContext TestIdentityContext = new IdentityContext(OptionsBuilder.Options); ProyectoPersonal ProyectoPersonal = new ProyectoPersonal() { ID = 45, Descripcion = "Book", FechaComienzo = DateTime.Parse("2019/02/12"), FechaFinalizacion = DateTime.Parse("2019/02/12"), TipoDeProyecto = "Foto" }; //Guardamos un Proyecto Personal en bd TestIdentityContext.ProyectoPersonal.Add(ProyectoPersonal); await TestIdentityContext.SaveChangesAsync(); // Act //Creamos una pagina de tipo DeleteModel (de Proyectos Personales), la cual es la que se encarga de la logica //de borrar Proyectos Personales en bd. DeleteModel PageDeleteModel = new DeleteModel(TestIdentityContext); //Simulamos un post que envíe el formulario de la pagina y por ende borre en bd, el Proyecto Personal que ingresamos en bd anteriormente await PageDeleteModel.OnPostAsync(ProyectoPersonal.ID); // Assert //Buscamos si aún esta en bd el Proyecto Personal que debió haber sido borrada por la pagina ProyectoPersonal ProyectoPersonalRecibida = await TestIdentityContext.ProyectoPersonal.FindAsync(ProyectoPersonal.ID); Assert.Null(ProyectoPersonalRecibida); //Si es Null significa que la pagina lo borro correctamente }
public void CanUserBeRegistered_Return_False() { // Arrange var options = GetContextOptions(); var accountViewModel = new AccountViewModel { Login = "******", Email = "*****@*****.**", Password = "******", Role = 1, IsActive = true }; var result = false; var message = string.Empty; // Act using (var context = new IdentityContext(options)) { IAccountService accountService = new AccountService(_options, context, _mapper); _ = accountService.RegistrationAsync(accountViewModel).GetAwaiter().GetResult(); (result, message) = accountService.RegistrationAsync(accountViewModel).GetAwaiter().GetResult(); } // Assert Assert.False(result); Assert.Equal(IdentityConstants.USER_EXIST, message); }
public ActionResult DeleteRoleConfirmed(string id) { try { IdentityContext IdentityContext1 = new IdentityContext(); UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext())); IdentityUser IdentityUser1 = new IdentityUser(); var IdentityUsers = IdentityContext1.Users.Where(u => u.Roles.Any(r => r.RoleId == id)); foreach (IdentityUser user1 in IdentityUsers) { UserManager1.RemoveFromRole(user1.Id, id); } //RoleManager<IdentityRole> RoleManager1 = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); IdentityRole IdentityRole1 = new IdentityRole(); IdentityRole1 = IdentityContext1.Roles.Find(id); IdentityContext1.Roles.Remove(IdentityRole1); IdentityContext1.SaveChanges(); //return RedirectToAction("AllRoles"); return(Json(new { success = true })); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(PartialView("_DeleteRole", id)); } }
public ActionResult AddUserInRole() { IdentityContext IdentityDbContext1 = new IdentityContext(); //ساخت لیستی از نام یوزرها List <ApplicationUser> AllUsers = IdentityDbContext1.Users.ToList(); List <string> AllUserNames = new List <string> { }; foreach (ApplicationUser IdentityUser1 in AllUsers) { AllUserNames.Add(IdentityUser1.UserName); } ViewBag.UserNames = AllUserNames; //ساخت لیستی از نام رولها List <IdentityRole> AllRoles = IdentityDbContext1.Roles.ToList(); List <string> AllRoleNames = new List <string> { }; foreach (IdentityRole IdentityRole1 in AllRoles) { AllRoleNames.Add(IdentityRole1.Name); } ViewBag.RoleNames = AllRoleNames; return(PartialView("_AddUserInRole")); }
//private static string ErrorCodeToString(MembershipCreateStatus createStatus) //{ // // See http://go.microsoft.com/fwlink/?LinkID=177550 for a full list of status codes. // switch (createStatus) // { // case MembershipCreateStatus.DuplicateUserName: // return "User name already exists. Please enter a different user name."; // case MembershipCreateStatus.DuplicateEmail: // return "A user name for that e-mail address already exists. Please enter a different e-mail address."; // case MembershipCreateStatus.InvalidPassword: // return "The password provided is invalid. Please enter a valid password value."; // case MembershipCreateStatus.InvalidEmail: // return "The e-mail address provided is invalid. Please check the value and try again."; // case MembershipCreateStatus.InvalidAnswer: // return "The password retrieval answer provided is invalid. Please check the value and try again."; // case MembershipCreateStatus.InvalidQuestion: // return "The password retrieval question provided is invalid. Please check the value and try again."; // case MembershipCreateStatus.InvalidUserName: // return "The user name provided is invalid. Please check the value and try again."; // case MembershipCreateStatus.ProviderError: // return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; // case MembershipCreateStatus.UserRejected: // return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; // default: // return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; // } //} #endregion #region Roles public ActionResult AllRoles() { IdentityContext IdentityDbContext = new IdentityContext(); List <IdentityRole> AllRoles = IdentityDbContext.Roles.ToList(); return(View(AllRoles)); }
public ActionResult EditRole(string id, string Name) { string RoleNameNew = Name; if (ModelState.IsValid) { RoleManager <IdentityRole> RoleManager1 = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityContext())); if (!RoleManager1.RoleExists(RoleNameNew)) { IdentityContext IdentityDbContext1 = new IdentityContext(); IdentityRole Role1 = IdentityDbContext1.Roles.First(x => x.Id == id); Role1.Name = RoleNameNew; IdentityDbContext1.Entry(Role1).State = System.Data.Entity.EntityState.Modified; IdentityDbContext1.SaveChanges(); //return RedirectToAction("AllRoles"); return(Json(new { success = true })); } else { ModelState.AddModelError("", "گروه جدید قبلا ساخته شده است."); } } else { ModelState.AddModelError("", "داده های وارد شده معتبر نیستند."); } return(PartialView("_EditRole", RoleNameNew)); }
public void CreateAdminUserAndRole() { //Initialzie Admin user and Password IdentityContext IdentityContext1 = new IdentityContext(); UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext())); //Create User "Admin" if it is not existed. if (UserManager1.FindByName("Admin") == null) { var user = new ApplicationUser() { UserName = "******" }; UserManager1.Create(user, "Pass#1"); } //Create Role "Admin" if it is not existed. RoleManager <IdentityRole> RoleManager1 = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new IdentityContext())); if (RoleManager1.FindByName("Admin") == null) { IdentityRole IdentityRole1 = new IdentityRole("Admin"); RoleManager1.Create(IdentityRole1); } //Add Admin user to Admin Role string IdentityUserId = IdentityContext1.Users.First(x => x.UserName == "Admin").Id; UserManager1.AddToRole(IdentityUserId, "Admin"); }
public ActionResult DeleteUserConfirmed(string id = null) { try { IdentityContext IdentityContext1 = new IdentityContext(); ApplicationUser IdentityUser1 = IdentityContext1.Users.First(x => x.Id == id); UserManager <ApplicationUser> UserManager1 = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new IdentityContext())); foreach (string UserRole1 in UserManager1.GetRoles(id)) { UserManager1.RemoveFromRole(id, UserRole1); } foreach (System.Security.Claims.Claim UserClaim1 in UserManager1.GetClaims(id)) { UserManager1.RemoveClaim(id, UserClaim1); } foreach (UserLoginInfo UserLoginInfo1 in UserManager1.GetLogins(id)) { UserManager1.RemoveLogin(id, UserLoginInfo1); } IdentityContext1.Users.Remove(IdentityUser1); IdentityContext1.SaveChanges(); //return RedirectToAction("AllUsers"); return(Json(new { success = true })); } catch (Exception ex) { return(Content(ex.Message)); } }
public static ApplicationUserManager Create( IdentityFactoryOptions <ApplicationUserManager> identityFactoryOptions, IOwinContext owinContext) { IdentityContext applicationContext = owinContext.Get <IdentityContext>(); ApplicationUserManager applicationUserManager = new ApplicationUserManager(new UserStore <ApplicationUser>(applicationContext)) { //EmailService = new EmailService(), PasswordValidator = new PasswordValidator { RequiredLength = 6 }, }; IDataProtectionProvider dataProtectionProvider = identityFactoryOptions.DataProtectionProvider; if (dataProtectionProvider != null) { applicationUserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromHours(6) }; } return(applicationUserManager); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DefaultContext defaultContext, IdentityContext identityContext) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } defaultContext.Database.Migrate(); identityContext.Database.Migrate(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
/// <summary> /// Check the user credentials /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns>User claims</returns> public static async Task <ClaimsIdentity> GetIdentityAsync(IdentityContext context, string username, string password) { ClaimsIdentity cIdentity = null; { var user = await context.ApplicationUsers.FirstOrDefaultAsync(i => i.username == username); if (user != null) { using (var md5Hash = MD5.Create()) { var hash = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(password)); var sBuilder = new StringBuilder(); foreach (var t in hash) { sBuilder.Append(t.ToString("x2")); } if (user.password.Equals(sBuilder.ToString())) { cIdentity = new ClaimsIdentity( new GenericIdentity(username, "Token"), new Claim[] { new Claim("isAdmin", user.level == 0 ? "true" : "false"), new Claim("userId", user.id), new Claim("username", user.username) }); } } } return(cIdentity); } }
public HomeController(ILogger <HomeController> logger, IdentityContext identity, fagelgamousContext context, IGamousRepository repository) { _logger = logger; _identity = identity; _context = context; _repository = repository; }
public void BeforeEachTest() { DatabaseConnection = connectionFactory.Get(); DB = Query.Db(TEST_DB_NAME); // Create DB if it does not exist if (!DatabaseConnection.Run(Query.DbList()).Contains(TEST_DB_NAME)) { DatabaseConnection.Run(Query.DbCreate(TEST_DB_NAME)); } IdentityContext = new IdentityContext(DatabaseConnection, DB); // Cleanup if needed if (DatabaseConnection.Run(DB.TableList()).Contains("IdentityUsers")) { DatabaseConnection.Run(DB.TableDrop("IdentityUsers")); } if (DatabaseConnection.Run(DB.TableList()).Contains("IdentityRoles")) { DatabaseConnection.Run(DB.TableDrop("IdentityRoles")); } // Create Tables DatabaseConnection.Run(DB.TableCreate("IdentityUsers")); DatabaseConnection.Run(DB.TableCreate("IdentityRoles")); }
public AuthController(UserManager <User> usermanager, SignInManager <User> signinmanager, IdentityContext logcontext, IOptions <JWTSettings> settings) { UserMgr = usermanager; SignInMgr = signinmanager; _context = logcontext; JWTSettings = settings.Value; }
public RefreshTokenService(IdentityContext context, IOptions <JwtSettings> jwtSettings, UserManager <IdentityUser> userManager, IConfiguration config) { this.context = context; this.jwtSettings = jwtSettings.Value; this.userManager = userManager; this.config = config; }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IdentityContext identityContext, ApiContext apiContext) { if (env.IsDevelopment()) { // for development purposes, migrate any database changes on startup (includes initial db creation) apiContext.Database.Migrate(); identityContext.Database.Migrate(); app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } var swaggerOptions = new MySwaggerOptions(); Configuration.GetSection(nameof(swaggerOptions)).Bind(swaggerOptions); app.UseMiddleware(typeof(ExceptionMiddleware)); if (!env.IsProduction()) { app.UseSwagger(option => option.RouteTemplate = swaggerOptions.JsonRoute) .UseSwaggerUI(option => option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description)); } app.UseHttpsRedirection() .UseRouting() .UseAuthentication() .UseAuthorization() .UseEndpoints(e => e.MapControllers()); }
public void ClassSetUp() { _identityId = Guid.NewGuid(); identityContext = new IdentityContext() { IdentityId = Guid.NewGuid() }; _authorizationPolicy = new Mock <IServiceAuthorizationPolicy>(); _identityProvider = new Mock <IServiceIdentityProvider>(); _identityProvider.Setup(x => x.GetPrincipalIdentifier()).Returns(identityContext.IdentityId); _identityProvider.Setup(x => x.GetIdentityContext()).Returns(identityContext); _factory = new MockRepository(MockBehavior.Loose); _summariesUnitOfWork = _factory.Create <ISummariesUnitOfWork>(); _summariesUnitOfWork.Setup(x => x.PendingMessages).Returns(new System.Collections.Generic.List <TriTech.InformRMS.Infrastructure.Messaging.Contracts.Messages.Message>()); _iIMasterIndexService = _factory.Create <IMasterIndexService>(); _messageBusClient = _factory.Create <IMessageBusPublishClient>(); _citationSummaryCommandService = new CitationSummaryCommandService(_summariesUnitOfWork.Object, _iIMasterIndexService.Object, Mock.Of <ILog>(), _authorizationPolicy.Object, _identityProvider.Object); DTOObjectsIntitalization(); _iIMasterIndexService.Setup( mock => mock.ProcessMasterIndexes(It.IsAny <DomainEntities.Citation.CitationEvent>())); _authorizationPolicy.Setup(mock => mock.RequireViewPermissions(It.IsAny <IdentityContext>(), It.IsAny <Guid>(), It.IsAny <ModuleType>())); DomainObjectsIntialization(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( "default", "{controller=Home}/{action=Index}/{id?}"); }); IdentityContext.CreateAdminAccount(app.ApplicationServices, Configuration).Wait(); }
public LoginController(UserManager <User> userManager, SignInManager <User> signInManager, IdentityContext identityContext) { _identityConext = identityContext; StaffMgr = userManager; SignInMgr = signInManager; //_httpContextAccessor = httpContextAccessor; }
public ProfileService( UserManager <ApplicationUser> userManager, IdentityContext context) { this.userManager = userManager; this.context = context; }
/// <summary> /// Seed theIdentityContext with user data /// For Development purposes, only. /// </summary> /// <param name="connection"></param> /// <returns></returns> public async Task Initialise(IdentityContext connection) { var roleStore = new RoleStore <IdentityRole>(connection); var initialUser = new IdentityUser { UserName = "******", NormalizedUserName = "******", Email = "*****@*****.**", NormalizedEmail = "*****@*****.**", EmailConfirmed = true, LockoutEnabled = false, SecurityStamp = Guid.NewGuid().ToString() }; if (!connection.Roles.Any(r => r.Name == "admin")) { await roleStore.CreateAsync(new IdentityRole { Name = "admin", NormalizedName = "admin" }); } if (!connection.Users.Any(u => u.UserName == initialUser.UserName)) { initialUser.PasswordHash = new PasswordHasher <IdentityUser>().HashPassword(initialUser, "password123"); var userStore = new UserStore <IdentityUser>(connection); await userStore.CreateAsync(initialUser); await userStore.AddToRoleAsync(initialUser, "admin"); } await connection.SaveChangesAsync(); }
public AdminController( UserManager <AppUser> userManager, IdentityContext identityContext) { UserManager = userManager; IdentityContext = identityContext; }
public void DeserializeModel_StartWorkflowCommand_CorrelationId() { IdentityModel identityModel = new IdentityModel(accountName, AuthorizationType.NTLM); IdentityContext identityContext = new IdentityContext(identityModel); RoleModel roleModel = new RoleModel(AuthorizationType.DocSuiteSecurity, Guid.NewGuid()); identityContext.Roles.Add(roleModel); WorkflowModel workflowModel = new WorkflowModel("DSW_StartCollaboration"); SignerModel singner1 = new SignerModel(1, true, SignerType.AD, identityModel); WorkflowParameterModel workflowParameterModel1 = new WorkflowParameterModel(singner1, WorkflowParameterNames.CollaborationNames.SIGNER); workflowModel.WorkflowParameters.Add(workflowParameterModel1); SignerModel singner2 = new SignerModel(2, true, SignerType.DSWRole, role: roleModel); WorkflowParameterModel workflowParameterModel2 = new WorkflowParameterModel(singner2, WorkflowParameterNames.CollaborationNames.SIGNER); workflowModel.WorkflowParameters.Add(workflowParameterModel2); StartWorkflowContentType startWorkflowContentType = new StartWorkflowContentType(workflowModel, accountName, Guid.NewGuid()); StartWorkflowCommand startWorkflowCommand = new StartWorkflowCommand(Guid.NewGuid(), tenantName, tenantId, Guid.NewGuid(), identityContext, startWorkflowContentType) { CorrelationId = Guid.NewGuid() }; string json = ManagerHelper.SerializeModel(startWorkflowCommand); StartWorkflowCommand deJson = ManagerHelper.DeserializeModel <StartWorkflowCommand>(json); Assert.AreEqual <Guid>(startWorkflowCommand.CorrelationId.Value, deJson.CorrelationId.Value); }
public void IdentityContext_IdentityNotNull() { IdentityModel identityModel = new IdentityModel(accountName, AuthorizationType.NTLM); IdentityContext identityContext = new IdentityContext(identityModel); Assert.IsNotNull(identityContext.Identity); }
public ParkingSpotsController(IHostingEnvironment hostingEnviroment, KeeParkContext context, IdentityContext identity, UserManager <GeneralUser> userManager) { this.hostingEnvironment = hostingEnviroment; this._identity = identity; _context = context; UserManager = userManager; }
public static void SeedDB(IdentityContext context, string adminID) { if (context.WudFilmAppUser.Any()) { return; // DB seeded } }
public DetailsModel( IdentityContext context, IAuthorizationService authorizationService, UserManager <IdentityUser> userManager) : base(context, authorizationService, userManager) { }
public static async Task EnsurePopulated(IApplicationBuilder app) { IdentityContext context = app.ApplicationServices .CreateScope().ServiceProvider .GetRequiredService <IdentityContext>(); if (context.Database.GetPendingMigrations().Any()) { context.Database.Migrate(); } UserManager <IdentityUser> userManager = app.ApplicationServices .CreateScope().ServiceProvider .GetRequiredService <UserManager <IdentityUser> >(); IdentityUser user = await userManager.FindByIdAsync(adminUser); if (user == null) { user = new IdentityUser(adminUser); user.Email = "*****@*****.**"; user.PhoneNumber = "123-123"; await userManager.CreateAsync(user, adminPass); } }
// // GET: /Guests/ public ActionResult Index() { using (IdentityContext db = new IdentityContext()) { ViewBag.Title = "Guest List"; var guestList = GetGuestList(); return View(guestList); } }
public List<GuestListViewModel> GetGuestList() { using (IdentityContext db = new IdentityContext()) { var guests = from users in db.Users orderby users.JoinDate select new GuestListViewModel { FirstName = users.FirstName, LastName = users.LastName, JoinDate = users.JoinDate, Logins = users.Logins }; return guests.ToList<GuestListViewModel>(); } }
public AccountController() { var identityDbContext = new IdentityContext("DefaultConnection"); IdentityManager = new AuthenticationIdentityManager(new IdentityStore(identityDbContext)); }