public ActionResult Index([Bind(Include = "UserId,UserName,Password,ConfirmPassword,Salt,FirstName,LastName,Email,Phone,Address,SecurityQuestion,SecurityQuestionAnswer")] RegistrationViewModel model) { if (ModelState.IsValid) { UserRegistration user = new UserRegistration(); user.UserName = model.UserName; user.Salt = encryptionDecryptionUtil.GenerateSalt(saltLength); user.Password = encryptionDecryptionUtil.CreatePasswordHash(model.Password, user.Salt); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Phone = model.Phone; user.Address = model.Address; user.Email = model.Email; user.IsActive = false; user.LastLogin = DateTime.Now; user.SecurityQuestion = model.SecurityQuestion; user.SecurityQuestionAnswer = model.SecurityQuestionAnswer; db.User.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult Create([Bind(Include = "Name")] Group group) { if (ModelState.IsValid) { db.Groups.Add(group); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(group)); }
public IActionResult Post([FromBody] ApplicationRole role) { if (string.IsNullOrWhiteSpace(role.Name)) { return(BadRequest()); } var entry = db.ApplicationRoles.Add(role); db.SaveChanges(); return(Ok()); }
public static Task <ApplicationUser> CheckEncryptedKeys(this ApplicationUser user, SecurityDbContext applicationDbContext) { try { bool generated = false; if (user.EncryptionIv == null || user.EncryptionIv.Length < 1) { generated = true; user.EncryptionIv = KeyGenerator.GetRandomData(128); } if (user.EncryptionKey == null || user.EncryptionKey.Length < 1) { generated = true; user.EncryptionKey = KeyGenerator.GetRandomData(256); } if (generated) { applicationDbContext.Users.Update(user); } applicationDbContext.SaveChanges(); } catch (Exception ex) { Console.Write(ex); } return(Task.FromResult(user)); }
public async Task <ActionResult> Authenticate(XcConnect.Models.LoginModel Model) { if (ModelState.IsValid) { var user = await UserManager.FindAsync(Model.Nit, Model.Phone); if (user != null) { await SignInAsync(user, Model.RememberMe); SecurityDbContext db = new SecurityDbContext(); db.AuthenticationAudit.Add(new AuthenticationAudit() { LoginDate = DateHelper.GetColombiaDateTime(), LoginIP = Request.UserHostAddress, LoginBrowser = Request.UserAgent, LoginPlatform = Request.Browser.Platform, LoginBrowserVersion = Request.Browser.Version, UserId = user.Id }); db.SaveChanges(); return(RedirectToAction("Dashboard", "Dashboards")); } else { ModelState.AddModelError("", "Usuario o contraseña incorrectos."); } } return(View("Login", Model)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Add Logger loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // Add Developer Error Page if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } // Add Cors app.UseCors(builder => builder.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() ); // Add OpenIddict app.UseOAuthValidation(); app.UseIdentity(); app.UseOpenIddict(); // Add Mvc app.UseMvcWithDefaultRoute(); // Security Seed using (var context = new SecurityDbContext(app.ApplicationServices.GetRequiredService <DbContextOptions <SecurityDbContext> >())) { if (!context.Applications.Any()) { context.Applications.Add(new OpenIddictApplication { ClientId = "postman", DisplayName = "Postman", RedirectUri = "https://www.getpostman.com/oauth2/callback", Type = OpenIddictConstants.ClientTypes.Public }); context.SaveChanges(); } } // Command/Events Handlers Registration to Bus var rawRabbitCommandBus = (RawRabbitCommandBus)app.ApplicationServices.GetService(typeof(ICommandBus)); var rawRabbitEventBus = (RawRabbitEventBus)app.ApplicationServices.GetService(typeof(IEventBus)); rawRabbitCommandBus.RegisterHandler(typeof(CreateMyEntityCommand), typeof(ICommandHandler <CreateMyEntityCommand>)).Wait(); rawRabbitCommandBus.RegisterHandler(typeof(UpdateMyEntityCommand), typeof(ICommandHandler <UpdateMyEntityCommand>)).Wait(); rawRabbitEventBus.RegisterHandler(typeof(MyEntityCreatedEvent), typeof(MyEntityCreatedEventHandler)).Wait(); rawRabbitEventBus.RegisterHandler(typeof(MyEntityCreatedEvent), typeof(MyEntityCreated2EventHandler)).Wait(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifeTime) { app.Use(async(context, next) => { using (var dbcontext = new SecurityDbContext(Configuration.GetConnectionString("SecurityConnection"))) { if (dbcontext.Users.FirstOrDefault(e => e.uname == context.User.Identity.Name) == null) { Security.Models.Entities.User user = new Security.Models.Entities.User(); user.uname = context.User.Identity.Name; user.active = true; dbcontext.Users.Add(user); dbcontext.SaveChanges(); } await next(); } }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules")), RequestPath = "/node_modules" }); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=SampleRequests}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "SampleRequests", action = "Index" }); }); appLifeTime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose()); }
public ActionResult Edit([Bind(Include = "Id,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,UserName,FirstName,LastName,EmpresaID")] ApplicationUser editUserViewModel) { if (ModelState.IsValid) { db.Entry(editUserViewModel).State = EntityState.Modified; db.SaveChanges(); if (Helpers.ApplicationContext.CurrentUser.IsSuperAdmin) { return(RedirectToAction("Index", "Account")); } else { return(RedirectToAction("Dashboard", "Dashboards")); } } SetViewBagListData(editUserViewModel.EmpresaID); return(View(editUserViewModel)); }
public ActionResult Edit([Bind(Include = "RoleName,OriginalRoleName,Description")] EditRoleViewModel model) { if (ModelState.IsValid) { var role = _db.Roles.First(r => r.Name == model.OriginalRoleName); role.Name = model.RoleName; role.Description = model.Description; _db.Entry(role).State = EntityState.Modified; _db.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
public ActionResult PasswordReset(string Email, ResetPassword rp) { if (ModelState.IsValid) { List <UserRegistration> appusers = db.User.ToList(); foreach (var appuser in appusers) { if (appuser.Email.Equals(Email)) { appuser.Password = encryptionDecryptionUtil.CreatePasswordHash(rp.NewPassword, appuser.Salt); db.Entry(appuser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Confirmation")); } } if (ModelState.IsValid) { ModelState.AddModelError("", "Something gonna wrong!"); } } return(View(rp)); }
public async Task <IHttpActionResult> PutApplicationUser(AppUserViewModel viewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (viewModel.Id == null) { return(BadRequest()); } // IdentityResult result = await manager.UpdateAsync(applicationUser); db = Request.GetOwinContext().Get <SecurityDbContext>(); manager = Request.GetOwinContext().Get <ApplicationUserManager>(); ApplicationUser user = manager.FindByEmail(viewModel.Email); user.Id = viewModel.Id; user.Email = viewModel.Email; user.FirstName = viewModel.FirstName; user.LastName = viewModel.LastName; user.IsActive = true; user.EmailConfirmed = true; user.PhoneNumber = viewModel.PhoneNumber; user.ShopId = viewModel.ShopId; user.UserName = viewModel.Email; db.Entry(user).State = EntityState.Modified; try { IdentityUserRole entity = db.ApplicationUserRoles.FirstOrDefault(x => x.UserId == user.Id); db.ApplicationUserRoles.Remove(entity); db.SaveChanges(); var identityUserRole = db.ApplicationUserRoles.Add(new IdentityUserRole { RoleId = viewModel.RoleId, UserId = user.Id }); int i = await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ApplicationUserExists(user.Id)) { return(NotFound()); } throw; } return(Ok(user)); }
public ActionResult Create([Bind(Include = "RoleId,RoleName")] Role role) { if (ModelState.IsValid) { db.Roles.Add(role); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(role)); }
private void AddRoles(SecurityDbContext context) { List <string> list = Enum.GetNames(typeof(ApplicationRoles)).ToList(); foreach (string r in list) { ApplicationRole role = context.ApplicationRoles.FirstOrDefault(x => x.Name == r); if (role == null) { context.Roles.Add(new ApplicationRole(r) { Description = r }); context.SaveChanges(); } } }
public static Exception FailSaveChanges(SecurityDbContext dbContextMultiClass) { bool withSecurityException = false; Exception result = new Exception("fail"); try { dbContextMultiClass.SaveChanges(); } catch (SecurityAccessException e) { withSecurityException = true; result = e; } catch (Exception e) { Assert.Fail(e.Message); } Assert.IsTrue(withSecurityException); return(result); }
public async Task <IHttpActionResult> Put(AppUserRolesViewModel vm) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } IdentityUserRole entity = db.ApplicationUserRoles.FirstOrDefault(x => x.UserId == vm.UserId); db.ApplicationUserRoles.Remove(entity); db.SaveChanges(); IdentityUserRole userRole = new IdentityUserRole { RoleId = vm.RoleId, UserId = vm.UserId }; db.ApplicationUserRoles.Add(userRole); await db.SaveChangesAsync(); return(Ok(userRole)); }
private static void AddRolePermissions(SecurityDbContext db, string roleId) { var resources = db.Resources.ToList(); foreach (var resource in resources) { var permission = db.Permissions.FirstOrDefault(x => x.ResourceId == resource.Id && x.RoleId == roleId); if (permission == null || permission.Id == new Guid().ToString()) { permission = new ApplicationPermission() { Id = Guid.NewGuid().ToString(), ResourceId = resource.Id, IsAllowed = true, RoleId = roleId, }; db.Permissions.Add(permission); } db.SaveChanges(); } }
public ActionResult Index(Login loginModel, string returnUrl) { if (loginModel.USERNAME == null || loginModel.PASSWARD == null || loginModel.USERNAME.Trim().Equals("") || loginModel.PASSWARD.Trim().Equals("")) { ModelState.AddModelError("", "Wrong Username or Password"); } List <UserRegistration> appusers = db.User.ToList(); foreach (var appuser in appusers) { if (appuser.UserName.Equals(loginModel.USERNAME) && encryptionDecryptionUtil.VerifyPassword(appuser.Password, loginModel.PASSWARD, appuser.Salt)) { FormsAuthentication.SetAuthCookie(loginModel.USERNAME, false); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } else { RoleAssignUser userpermission = db.RoleAssignUser.SingleOrDefault(u => u.UserId == appuser.UserId); if (userpermission == null) { FormsAuthentication.SignOut(); return(RedirectToAction("AccessDenied", "Error", null)); } appuser.LastLogin = DateTime.Now; db.Entry(appuser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "Home")); } } } if (ModelState.IsValid) { ModelState.AddModelError("", "Wrong Username or Password"); } return(View(loginModel)); }
private void InitializeDbForTests(SecurityDbContext db, ApplicationDbContext dbdata) { var geAdditional = GetAdditionalExaminationTypes(); var activities = GetActivities(); var additionalExamination = GetAdditionalExaminationResults(geAdditional[0]); var icpcCode = GetIcpcCodes(); var patients = GetPatients(); var episodes = GetEpisodes(patients[0], icpcCode[0]); var constultations = GetConsultations(additionalExamination[0], episodes[0]); var prescription = GetPrescriptions(constultations[0], patients[0]); db.Users.AddRange(_users); db.SaveChanges(); dbdata.UserInformation.AddRange(_userInformations); dbdata.Activities.AddRange(activities); dbdata.Consultations.AddRange(constultations); dbdata.Patients.AddRange(patients); dbdata.Prescriptions.AddRange(prescription); dbdata.AdditionalExaminationResults.AddRange(additionalExamination); dbdata.AdditionalExaminationTypes.AddRange(geAdditional); dbdata.SaveChanges(); }
public ActionResult Index(ChangePassword changePassword, string returnUrl) { if (changePassword.UserName == null || changePassword.CurrentPassword == null || changePassword.NewPassword == null || changePassword.ConfirmPassword == null || changePassword.UserName.Trim().Equals("") || changePassword.CurrentPassword.Trim().Equals("") || changePassword.NewPassword.Trim().Equals("") || changePassword.ConfirmPassword.Trim().Equals("")) { ModelState.AddModelError("", "Wrong Username or Password"); } List <UserRegistration> appusers = db.User.ToList(); foreach (var appuser in appusers) { if (appuser.UserName.Equals(changePassword.UserName) && encryptionDecryptionUtil.VerifyPassword(appuser.Password, changePassword.CurrentPassword, appuser.Salt)) { appuser.Password = encryptionDecryptionUtil.CreatePasswordHash(changePassword.NewPassword, appuser.Salt); db.Entry(appuser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index", "Home")); } } if (ModelState.IsValid) { ModelState.AddModelError("", "Wrong Username or Password"); } return(View(changePassword)); }
public void TestInitialize() { TestCleanup(); using (var db = new SecurityDbContext()) { for (int i = 0; i < 108; i++) { var user = new User() { Role = GenerateEnumValue<Role>(), LoginName = string.Format("login-name-{0}", i + 1), DisplayName = string.Format("display-name-{0}", i + 1), _Password = string.Format("password-{0}", i + 1), _IsLocked = (i % 3 == 0), _LockDateTimeUtc = DateTimeOffset.UtcNow }; FillEntityCommonValues(user, DateTimeOffset.UtcNow); db.Users.Add(user); } db.SaveChanges(); } }
public void Save() { _context.SaveChanges(); }
/// <summary> /// /// </summary> /// <param name="authorizationParameter"></param> /// <param name="ct"></param> /// <returns></returns> /// <exception cref="InvalidTokenFormatException"></exception> /// <exception cref="TokenNotFoundException"></exception> /// <exception cref="ApiAuthorizationExpiredException"></exception> protected async override Task <IPrincipal> AuthenticateAsync(string authorizationParameter, CancellationToken ct) { ct.ThrowIfCancellationRequested(); Guid accessToken; try { accessToken = Guid.Parse(authorizationParameter.DecodeFromBase64ASCII()); } catch (Exception e) { throw new InvalidTokenFormatException(e); } ClaimsIdentity identity; using (var context = new SecurityDbContext("ALSContext")) using (var userStore = new SecurityUserStore <ApiUser>(context)) using (var userManager = new UserManager <ApiUser>(userStore)) { var authenticationToken = await context.ApiAuthenticationAccessToken.Include(e => e.ApiAuthenticationToken.BaseApiUser) .SingleOrDefaultAsync(a => a.AccessToken == accessToken, ct); if (authenticationToken == null) { throw new TokenNotFoundException(); } if (authenticationToken.ExpirationDate < DateTime.Now) { throw new ApiAuthorizationExpiredException(); } // Create a ClaimsIdentity with all the claims for this user. ct.ThrowIfCancellationRequested(); // Unfortunately, IClaimsIdenityFactory doesn't support CancellationTokens. identity = await userManager.ClaimsIdentityFactory .CreateAsync( userManager, authenticationToken.ApiAuthenticationToken.BaseApiUser, SchemeId); } #region Cleanup if (DateTime.Now.Millisecond % 10 == 0) { Task.Factory.StartNew( () => { using (var ctx = new SecurityDbContext("ALSContext")) { while (true) { var currentTime = DateTime.Now; ctx.ApiAuthenticationAccessToken.RemoveRange( ctx.ApiAuthenticationAccessToken.Where(t => t.ExpirationDate < currentTime)); try { ctx.SaveChanges(); return; } catch (DbUpdateConcurrencyException e) { e.Entries.Single().Reload(); } } } }, ct); } #endregion return(new ClaimsPrincipal(identity)); }
/// <summary> /// Delete Object From AjaxJQuery /// </summary> /// <param name="id">PK Value</param> /// <returns></returns> public ActionResult Delete(int id) { DbContextTransaction Transaction = null; try { Empresa empresa = db.Empresas.Include(e => e.Clientes).Include(e => e.Peticiones).Include(e => e.Productos).Include(e => e.Actividades).Where(e => e.EmpresaID.Equals(id)).FirstOrDefault(); if (empresa != null) { if (empresa.Clientes != null && empresa.Clientes.Count > 0) { return(new JsonResult { Data = new { Message = "No es posible eliminar una empresa que tiene clientes asociados.", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } if (empresa.Peticiones != null && empresa.Peticiones.Count > 0) { return(new JsonResult { Data = new { Message = "No es posible eliminar una empresa que tiene peticiones asociadas.", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } if (empresa.Productos != null && empresa.Productos.Count > 0) { return(new JsonResult { Data = new { Message = "No es posible eliminar una empresa que tiene productos asociadas.", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } if (empresa.Actividades != null && empresa.Actividades.Count > 0) { return(new JsonResult { Data = new { Message = "No es posible eliminar una empresa que tiene actividades asociadas.", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } Transaction = db.Database.BeginTransaction(); SecurityDbContext dbSecurity = new SecurityDbContext(); var UsersToDelete = dbSecurity.Users.Include(u => u.Groups).Where(u => u.EmpresaID == empresa.EmpresaID).ToList(); if (UsersToDelete != null && UsersToDelete.Count > 0) { for (int i = 0; i < UsersToDelete.Count; i++) { var ResultUsr = ApplicationUser.ClearUserGroups(UsersToDelete[i]); if (!ResultUsr.Succeeded) { return(new JsonResult { Data = new { Message = String.Join(", ", ResultUsr.Errors.Select(u => u.ToString())), Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } else { dbSecurity.Users.Remove(UsersToDelete[i]); } } dbSecurity.SaveChanges(); } db.Empresas.Remove(empresa); db.SaveChanges(); Transaction.Commit(); } else { return(new JsonResult { Data = new { Message = "No es posible identificar la empresa. Por favor, intente de nuevo.", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } return(new JsonResult { Data = new { Message = string.Empty, Success = true }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } catch { if (Transaction != null) { Transaction.Rollback(); } // // Log Exception eX // return(new JsonResult { Data = new { Message = "Error ejecutando la acción de eliminar. Por favor inténtelo de nuevo", Success = false }, ContentEncoding = System.Text.Encoding.UTF8, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); } }
public void SaveChanges() { dataDb.SaveChanges(); securityDb.SaveChanges(); }
public int Save() { return(_context.SaveChanges()); }
public void TestCleanup() { using (var db = new SecurityDbContext()) { db.Database.ExecuteSqlCommand("DELETE tc_employee WHERE created_by <> N'system'"); db.SaveChanges(); } }
private static void UpdateUser(Guid id) { using (var db = new SecurityDbContext()) { var user = db.Users.Find(id); user.DisplayName += " changed"; user.Modified = DateTimeOffset.UtcNow; user.ModifiedBy = "test"; db.SaveChanges(); } }