public ActionResult Create([Bind(Include = "CareProviderID,AverageRating,ExperienceDetails,UserID")] DAL.CareProvider careProvider) { if (ModelState.IsValid) { //Changing Current user to a Pet Care Provider var identityID = User.Identity.GetUserId(); DAL.PetopiaUser currentUser = pdb.PetopiaUsers.Where(x => x.ASPNetIdentityID == identityID).First(); currentUser.IsProvider = true; pdb.Entry(currentUser).State = EntityState.Modified; //Roles.AddUserToRole(currentUser.ASPNetIdentityID, "Provider"); var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); var theUser = UserManagerExtensions.FindByName(userManager, currentUser.ASPNetIdentityID); UserManagerExtensions.AddToRole(userManager, identityID, "Provider"); pdb.SaveChanges(); careProvider.UserID = pdb.PetopiaUsers.Where(x => x.ASPNetIdentityID == identityID).Select(x => x.UserID).First(); pdb.CareProviders.Add(careProvider); pdb.SaveChanges(); return(RedirectToAction("Index", "ProfilePage")); } return(View(careProvider)); }
public async Task <bool> UpdateUser([FromBody] UpdateOrCreateUserDto req) { //update password // await _userManager.AddPasswordAsync(await _userManager.GetByIdAsync(req.Id), req.Password); //update info var user = await _identityUser.FirstOrDefaultAsync(x => x.Id == req.Id); await _userManager.SetUserNameAsync(user, req.UserName); await _userManager.SetEmailAsync(user, req.Email); await _userManager.SetPhoneNumberAsync(user, req.PhoneNumber); await _userManager.SetRolesAsync(user, req.Roles); if (!req.Password.Contains("AQAAAAEAACcQAAAAE")) { await UserManagerExtensions.ChangePasswordAsync1(_Uu, user, req.Password); } //update user permission await _permissionGrant.DeleteAsync(r => r.ProviderName == "user" && r.ProviderKey == req.Id.ToString()); foreach (var item in req.Permissions) { await _permissionGrant.InsertAsync(new PermissionGrant(Guid.NewGuid(), item, "User", req.Id.ToString())); } return(true); }
/// <summary> /// Sends registration token for the given username /// </summary> /// <param name="user">User to send the registration token</param> public void SendRegistrationToken(User user) { UserSecurityCode confirmationToken = null; do { confirmationToken = UserSecurityCode.CreateSecurityCode(user, "Registration"); } while (this.FindUserForRegistrationToken(confirmationToken.Code) != null); user.RegistrationConfirmationToken = confirmationToken.EncryptedCode; UserManagerExtensions.Update(this, user); TextParser parser = new TextParser(this.manager); TextDefinition td = parser.ParseMessage("RegistrationEmail", new Dictionary <Model.Messages.ReplaceableObjectKeys, object>() { { ReplaceableObjectKeys.User, user }, { ReplaceableObjectKeys.Code, confirmationToken.Code } }); IdentityResult result = new IdentityResult(); try { SmtpMailClient.SendMail(user.Email, "OPSMC RePLAY Registration", td.Text, td.Html); } catch (Exception ex) { // TODO add logger audit throw ex; } }
/// <summary> /// Resets the password for the user with the given User name /// </summary> /// <param name="username">The user name of the user to reset the password for</param> /// <param name="newPassword">The new password to set</param> /// <param name="securityToken">The reset token</param> /// <param name="securityAnswer">The answer to the security question</param> /// <returns>An identify Result indicating success or failure</returns> public IdentityResult ResetPassword(string username, string newPassword, string securityToken, string securityAnswer) { try { User u = this.FindByName(username); if (u == null) { throw this.manager.MessageHandler.GetError(ErrorCodes.USER_UNKNOWN); } IdentityResult result; if (u.SecurityAnswer.Equals(securityAnswer, StringComparison.CurrentCultureIgnoreCase)) { result = UserManagerExtensions.ResetPassword(this, u.Id, securityToken, newPassword); } else { result = new IdentityResult("The supplied security answer is incorrect"); } Logger.Audit(new Audit(Actions.RESET_PASSWORD, AuditEventType.READ, u, result.Succeeded, result.Succeeded ? null : result.Errors.Aggregate((s1, s2) => { return(s1 + "\n" + s2); }))); return(result); } catch (Exception ex) { Logger.Audit(new Audit(Actions.RESET_PASSWORD, AuditEventType.READ, typeof(User), "UserName", username, false, ex.Message)); throw ex; } }
public async Task <bool> CreateUser([FromBody] UpdateOrCreateUserDto req) { var dto = await _userAppService.CreateAsync(new IdentityUserCreateDto() { Email = req.Email, UserName = req.UserName, RoleNames = req.Roles, Password = "******", PhoneNumber = req.PhoneNumber }); var user = await _identityUser.FirstOrDefaultAsync(x => x.Id == dto.Id); await UserManagerExtensions.ChangePasswordAsync1(_Uu, user, req.Password); await _permissionGrant.DeleteAsync(r => r.ProviderName == "user" && r.ProviderKey == user.Id.ToString()); foreach (var item in req.Permissions) { await _permissionGrant.InsertAsync(new PermissionGrant(Guid.NewGuid(), item, "User", user.Id.ToString())); } return(true); }
public ActionResult RemoveAdmin([Bind(Include = "Email")] string email) { NavbarInfo(); var context = new TipstersContext(); var user = data.Users.Find(x => x.Email == email).First(); UserManagerExtensions.RemoveFromRole( new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)), user.Id, "Admin"); user.IsAdmin = false; data.SaveChanges(); FormsAuthentication.SignOut(); Session.Abandon(); // clear authentication cookie HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); cookie1.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie1); // clear session cookie (not necessary for your current problem but i would recommend you do it anyway) HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); cookie2.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie2); FormsAuthentication.RedirectToLoginPage(); return(RedirectToAction("SelectAdminUser", "Admin")); }
public void TestStringArrayToUserRolesWrongValuesCustom() { UserRoles expected = UserRoles.AppAdministrator | UserRoles.HRManager; string[] stringValues = new string[] { nameof(UserRoles.AppAdministrator), nameof(UserRoles.HRManager), "InexistantRole", "ImaginedRole" }; UserRoles obtained = UserManagerExtensions.ToUserRoles(stringValues); Assert.AreEqual(expected, obtained); }
public async Task <string> Login(string username, string password) { var passwordHash = UserManagerExtensions.EncodePasswordToBase64(password);//Encoding of passed Password and compare with PasswordHash in AspNetUsers table var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == username && u.PasswordHash == passwordHash); if (user != null) { return(GenerateToken(user.Id));//Generate token If Username and Password is valid } return(null); }
public ActionResult AddAdminUser([Bind(Include = "Email")] string email) { NavbarInfo(); var context = new TipstersContext(); var user = data.Users.Find(x => x.Email == email).First(); UserManagerExtensions.AddToRole( new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)), user.Id, "Admin"); user.IsAdmin = true; data.SaveChanges(); return(RedirectToAction("SelectAdminUser", "Admin")); }
private async Task <bool> UpdateUserRoles(IdentityUser employee, ICollection <string> userRoles) { if (userRoles == null) { return(true); } bool updateResult = true; UserRoles newRoles = UserManagerExtensions.ToUserRoles(userRoles); UserRoles oldRoles = await _UserManager.GetUserRolesAsync(employee); var addedRoles = UserManagerExtensions.FromUserRoles((oldRoles ^ newRoles) & newRoles); var removedRoles = UserManagerExtensions.FromUserRoles((oldRoles ^ newRoles) & oldRoles); updateResult &= (await _UserManager.AddToRolesAsync(employee, addedRoles)).Succeeded; updateResult &= (await _UserManager.RemoveFromRolesAsync(employee, removedRoles)).Succeeded; return(updateResult); }
private async Task <bool> ValidateRoles(Employee employee, EmployeeCreationVM employeeVM, bool allow) { bool validRoles; UserRoles employeeRoles = await _UserManager.GetUserRolesAsync(employee); if (employeeVM.Roles == null || !employeeVM.RolesListEnabled) { return(true); } UserRoles employeeVmRoles = UserManagerExtensions.ToUserRoles(employeeVM.Roles); validRoles = allow || (employeeRoles == employeeVmRoles); if (validRoles) { validRoles |= allow && ((await ValidateAssignedRoles(employeeVmRoles, employee)) == employeeVmRoles); } return(validRoles); }
public static async Task <bool> SetEmployeesRoles(this IRepository <Employee> repository, UserManager <IdentityUser> userManager, Employee employee, UserRoles roles) { bool hasEmployee = (await repository.FindAsync(x => x == employee)) != null; if (!hasEmployee) { return(false); } ICollection <string> oldUserRoles = await userManager.GetRolesAsync(employee); bool updateResult = true; UserRoles newRoles = roles; UserRoles oldRoles = await userManager.GetUserRolesAsync(employee); var addedRoles = UserManagerExtensions.FromUserRoles((oldRoles ^ newRoles) & newRoles); var removedRoles = UserManagerExtensions.FromUserRoles((oldRoles ^ newRoles) & oldRoles); updateResult &= (await userManager.AddToRolesAsync(employee, addedRoles)).Succeeded; updateResult &= (await userManager.RemoveFromRolesAsync(employee, removedRoles)).Succeeded; return(updateResult); }
public async Task <IHttpActionResult> ChangeUsername(ChangeUsernameBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = UserManagerExtensions.FindByName(UserManager, model.UserName); if (user == null) { ApplicationUser currentUser = await UserManager.FindByIdAsync(User.Identity.GetUserId()); currentUser.UserName = model.UserName; UserManager.Update(currentUser); return(await GetUserInfo()); } return(BadRequest(String.Format("Username {0} is already taken", model.UserName))); }
private async Task <bool> ValidateCompanyData(Employee consernedEmployee, EmployeeCreationVM employeeVM, bool allow) { bool result = allow || consernedEmployee.CompanyId == employeeVM.CompanyId; UserRoles consernedEmployeeRoles; if (employeeVM.Roles == null) { consernedEmployeeRoles = await _UserManager.GetUserRolesAsync(consernedEmployee); } else { consernedEmployeeRoles = UserManagerExtensions.ToUserRoles(employeeVM.Roles); } bool isAppAdministrator = (consernedEmployeeRoles & UserRoles.AppAdministrator) == UserRoles.AppAdministrator; if (!isAppAdministrator && employeeVM.CompanyId == default) { ModelState.AddModelError("", _DataLocalizer["Company is required for all employees who is not app administrator"]); return(false); } return(result || isAppAdministrator); }
private async Task <EmployeeCreationVM> PrepareEmployeeEditionViewModel(EmployeeCreationVM employeeCreationVM, Employee concernedEmployee, UserRoles concernedEmployeesRoles, EditionPermissions editionPermissions) { var currentUserData = await GetCurrentUserData(); if (editionPermissions == null) { editionPermissions = await GetEditionPermission(concernedEmployee); } employeeCreationVM = await SetEmployeeCompanyAndManagerState(employeeCreationVM, editionPermissions); employeeCreationVM.ProfileDataEnabled = editionPermissions.AllowEditProfile; employeeCreationVM.ContactDataEnabled = editionPermissions.AllowEditContacts; employeeCreationVM.RolesListEnabled = editionPermissions.AllowEditAccess; //!concernedEmployee.Id.Equals(currentUserData.Item1.Id); employeeCreationVM.RolesList = await GetListAllowedRoles(currentUserData.Item3); employeeCreationVM.Roles = UserManagerExtensions.FromUserRoles(concernedEmployeesRoles).ToList(); employeeCreationVM.ManagerEnabled = editionPermissions.AllowChangeManager; employeeCreationVM.CompanyEnabled = editionPermissions.AllowChangeCompany; return(employeeCreationVM); }
/// <summary> /// Updates user data /// </summary> /// <param name="user">The user to change the data for</param> /// <returns>An identity result indicating success or failure and any errors that occurred</returns> public IdentityResult Update(User user) { try { SecuritySession.Current.VerifyAccess(Actions.UPDATE_USER_DATA, userId: user.Id); if (user.UserName.Length > 450) { throw this.manager.MessageHandler.GetError(ErrorCodes.USERNAME_LENGTH_EXCEEDED); } User tmpUser = this.FindById(user.Id); if (!tmpUser.IsExternalUser && (user.UserName.Contains("\\") || user.UserName.Contains("/"))) { throw this.manager.MessageHandler.GetError(ErrorCodes.USERNAME_CONTAINS_ILLEGAL_CHARACTERS); } IdentityResult result; if (SecuritySession.Current.User.Id == user.Id && !SecuritySession.Current.User.UserName.Equals(user.UserName, StringComparison.CurrentCultureIgnoreCase)) { if (this.Users.Where(u => u.UserName != user.UserName).FirstOrDefault() != null) { throw this.manager.MessageHandler.GetError(ErrorCodes.USERNAME_ALREADY_INUSE); } } result = UserManagerExtensions.Update(this, user); if (result.Succeeded) { this.manager.NotificationHandler.CreateNotification(NotificationType.UserDetailsChanged, user.Id); } Logger.Audit(new Audit(Actions.UPDATE_USER_DATA, AuditEventType.MODIFIED, user)); return(result); } catch (Exception ex) { Logger.Audit(new Audit(Actions.UPDATE_USER_DATA, AuditEventType.MODIFIED, user, false, ex.Message)); throw ex; } }
/// <summary> /// Changes a users password /// </summary> /// <param name="userId">The Id of the user</param> /// <param name="currentPassword">The current password</param> /// <param name="newPassword">The new password</param> /// <param name="authenticationToken">The authentication code send to the user. If the user has No two factor authentication provider set, this value can be ignored</param> /// <returns>The result indicating success or failure</returns> public IdentityResult ChangePassword(string userId, string currentPassword, string newPassword, string authenticationToken = null) { try { SecuritySession.Current.VerifyAccess(Actions.CHANGE_PASSWORD, userId: userId); User u = this.FindById(userId); if (u == null) { throw this.manager.MessageHandler.GetError(ErrorCodes.USER_UNKNOWN); } if (u.TwoFactorAuthenticationProvider != null && this.TwoFactorProviders.ContainsKey(u.TwoFactorAuthenticationProvider) && string.IsNullOrWhiteSpace(authenticationToken)) { throw this.manager.MessageHandler.GetError(ErrorCodes.CODE_INCORRECT); } if (u.TwoFactorAuthenticationProvider != null && this.TwoFactorProviders.ContainsKey(u.TwoFactorAuthenticationProvider)) { if (!this.VerifyTwoFactorToken(userId, u.TwoFactorAuthenticationProvider, authenticationToken)) { Logger.Audit(new Audit(Actions.COMPLETE_REGISTRATION, AuditEventType.MODIFIED, u, false, "The provided code is not correct")); return(new IdentityResult("The provided code is not correct")); } } this.manager.NotificationHandler.CreateNotification(NotificationType.PasswordChanged, userId); IdentityResult result = UserManagerExtensions.ChangePassword(this, userId, currentPassword, newPassword); Logger.Audit(new Audit(Actions.CHANGE_PASSWORD, AuditEventType.MODIFIED, u)); return(result); } catch (Exception ex) { Logger.Audit(new Audit(Actions.CHANGE_PASSWORD, AuditEventType.MODIFIED, typeof(User), "Id", userId, false, ex.Message)); throw ex; } }
public Users FindById(string userId) { return(UserManagerExtensions.FindById(this, userId)); }
public virtual ClaimsIdentity CreateIdentity(ApplicationUser user, string authenticationType) { return(UserManagerExtensions.CreateIdentity(this, user, authenticationType)); }
public virtual IdentityResult ChangePassword(string userId, string currentPassword, string newPassword) { return(UserManagerExtensions.ChangePassword(this, userId, currentPassword, newPassword)); }
public virtual IdentityResult AddPassword(string userId, string password) { return(UserManagerExtensions.AddPassword(this, userId, password)); }
public virtual IdentityResult Create(ApplicationUser user, string password) { return(UserManagerExtensions.Create(this, user, password)); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, IApiVersionDescriptionProvider provider) { UserManagerExtensions.Configure( app.ApplicationServices.GetRequiredService <IHttpContextAccessor>(), Configuration); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } // forwarded Header middleware var fordwardedHeaderOptions = new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }; fordwardedHeaderOptions.KnownNetworks.Clear(); fordwardedHeaderOptions.KnownProxies.Clear(); app.UseForwardedHeaders(fordwardedHeaderOptions); app.UseSwagger(); app.UseSwaggerUI(c => { foreach (var description in provider.ApiVersionDescriptions) { c.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } c.DefaultModelRendering(ModelRendering.Example); c.DefaultModelsExpandDepth(-1); c.InjectStylesheet("/css/swagger-ui.min.css"); c.InjectJavascript("/js/swagger.min.js"); }); var nonce = Guid.NewGuid().ToString("N"); app.Use(async(ctx, next) => { ctx.Items["csp-nonce"] = nonce; await next(); }); app.UseContentSecurityPolicy(new CspDirectiveList { DefaultSrc = CspDirective.Self.AddHttpsScheme(), StyleSrc = StyleCspDirective.Self.AddUnsafeInline().AddHttpsScheme(), ScriptSrc = ScriptCspDirective.Self.AddNonce(nonce).AddHttpsScheme() .AddSource("https://az416426.vo.msecnd.net") .AddSource("https://www.googletagmanager.com") .AddSource("https://www.google-analytics.com") .AddSource("https://connect.facebook.net") .AddSource("https://www.facebook.com/"), ImgSrc = CspDirective.Self.AddDataScheme().AddHttpsScheme(), FontSrc = CspDirective.Self.AddHttpsScheme(), ConnectSrc = CspDirective.Self.AddHttpsScheme() .AddSource("https://dc.services.visualstudio.com/") }); app.AddCustomHeaders("Report-To", "{\"group\":\"default\",\"max_age\":31536000,\"endpoints\":[{\"url\":\"https://ajtio.report-uri.com/a/d/g\"}],\"include_subdomains\":true}"); app.UseFeaturePolicy( new FeatureDirectiveList() .AddNone(PolicyFeature.Microphone) .AddNone(PolicyFeature.Camera) .AddSelf(PolicyFeature.FullScreen) ); app.UseFrameOptions(FrameOptionsPolicy.Deny); app.UseXContentTypeOptions(XContentTypeOptions.NoSniff); app.UseReferrerPolicy(ReferrerPolicy.Origin); app.UseXRobotsTag(false, false); app.UseExpectCT(true, new TimeSpan(7, 0, 0, 0), new Uri("https://ajtio.report-uri.com/r/d/ct/enforce")); app.UseSerilogRequestLogging(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseResponseCompression(); app.UseCookiePolicy(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); }); }
public virtual ApplicationUser FindByName(string email) { return(UserManagerExtensions.FindByName(this, email)); }
public virtual bool IsEmailConfirmed(string userId) { return(UserManagerExtensions.IsEmailConfirmed(this, userId)); }
public virtual IdentityResult ConfirmEmail(string userId, string token) { return(UserManagerExtensions.ConfirmEmail(this, userId, token)); }
public IList <string> GetRoles(string userId) { return(UserManagerExtensions.GetRoles(manager: this, userId: userId)); }
public virtual bool HasPassword(string userId) { return(UserManagerExtensions.HasPassword(this, userId)); }
/// <summary> /// Gets a user by identifier. /// </summary> /// <param name="userId">Identifier of target user.</param> /// <returns>An instance of <see cref="ApplicationUser"/>.</returns> public ApplicationUser FindById(string userId) { return(UserManagerExtensions.FindById(this, userId)); }
public static bool HasClaim(string username, string password, string claimValue) { var user = UserManagerExtensions.Find(NHibernateHelper.userManager, username, password); return(user.Claims.Select(c => c.ClaimValue).Contains(claimValue)); }