/// <summary> /// Creates a new user avatar. /// </summary> /// <param name="user">A user.</param> /// <param name="server">A server object.</param> /// <returns></returns> protected async Task CreateNewAvatarAsync(MedioClinicUser user, HttpServerUtilityBase server) { var path = server.MapPath($"{AppConfig.ContentDirectory}/{AppConfig.AvatarDirectory}/{AppConfig.DefaultAvatarFileName}"); user.AvatarId = AvatarRepository.CreateUserAvatar(path, $"Custom {user.UserName}"); await UserManager.UpdateAsync(user); }
GetProfileAsync(string userName, RequestContext requestContext) { var profileResult = new IdentityManagerResult <GetProfileResultState, (IUserViewModel, string)>(); MedioClinicUser user = null; try { user = await UserManager.FindByNameAsync(userName); } catch (Exception ex) { var pr = profileResult as IdentityManagerResult <GetProfileResultState>; HandleException(nameof(GetProfileAsync), ex, ref pr); profileResult.ResultState = GetProfileResultState.UserNotFound; return(profileResult); } (var model, var title) = GetViewModelByUserRoles(user, requestContext); if (model != null) { profileResult.Success = true; profileResult.ResultState = GetProfileResultState.UserFound; profileResult.Data = (model, title); } return(profileResult); }
/// <summary> /// Creates a <see cref="UserInfo"/> out of a <see cref="MedioClinicUser"/> one. /// </summary> /// <param name="medioClinicUser">The original <see cref="MedioClinicUser"/> object.</param> /// <returns>The <see cref="UserInfo"/> object.</returns> public static UserInfo ToUserInfo(this MedioClinicUser medioClinicUser) { var userInfo = new UserInfo(); UserHelper.UpdateUserInfo(ref userInfo, medioClinicUser); return(userInfo); }
public void UploadUserAvatar(MedioClinicUser user, byte[] avatarBinary) { var avatarInfo = AvatarInfoProvider.GetAvatarInfo(user.AvatarId); if (avatarInfo != null) { avatarInfo.AvatarBinary = avatarBinary; AvatarInfoProvider.SetAvatarInfo(avatarInfo); } }
public (string fileName, byte[] binary) GetUserAvatar(MedioClinicUser user) { var avatarInfo = AvatarInfoProvider.GetAvatarInfo(user.AvatarId); if (avatarInfo != null) { return($"{avatarInfo.AvatarGUID}{avatarInfo.AvatarFileExtension}", avatarInfo.AvatarBinary); } return(null, null); }
public async Task <IdentityManagerResult <SignInResultState> > SignInAsync(SignInViewModel uploadModel) { var accountResult = new IdentityManagerResult <SignInResultState, SignInViewModel>(); MedioClinicUser user = null; try { user = await UserManager.FindByNameAsync(uploadModel.EmailViewModel.Email); } catch (Exception ex) { var ar = accountResult as IdentityManagerResult <SignInResultState>; accountResult.ResultState = SignInResultState.UserNotFound; HandleException(nameof(SignInAsync), ex, ref ar); return(accountResult); } // Registration: Confirmed registration (begin) if (user != null && !await UserManager.IsEmailConfirmedAsync(user.Id)) { accountResult.ResultState = SignInResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) SignInStatus signInStatus = SignInStatus.Failure; try { signInStatus = await SignInManager.PasswordSignInAsync(uploadModel.EmailViewModel.Email, uploadModel.PasswordViewModel.Password, uploadModel.StaySignedIn, false); } catch (Exception ex) { var ar = accountResult as IdentityManagerResult <SignInResultState>; accountResult.ResultState = SignInResultState.NotSignedIn; HandleException(nameof(SignInAsync), ex, ref ar); return(accountResult); } if (signInStatus == SignInStatus.Success) { accountResult.Success = true; accountResult.ResultState = SignInResultState.SignedIn; } return(accountResult); }
/// <summary> /// Updates the custom fields of the <see cref="UserInfo"/> object with strongly-typed properties of the <see cref="MedioClinicUser"/> object. /// </summary> /// <param name="userInfo">The object to update.</param> /// <param name="medioClinicUser">The input object.</param> /// <remarks>Omits properties that need special handling (e.g. <see cref="MedioClinicUser.AvatarId"/>).</remarks> public static void UpdateUserInfo(ref UserInfo userInfo, MedioClinicUser medioClinicUser) { userInfo.UserName = medioClinicUser.UserName; userInfo.FullName = UserInfoProvider.GetFullName(medioClinicUser.FirstName, null, medioClinicUser.LastName); userInfo.FirstName = medioClinicUser.FirstName; userInfo.LastName = medioClinicUser.LastName; userInfo.Email = medioClinicUser.Email; userInfo.Enabled = medioClinicUser.Enabled; userInfo.UserSecurityStamp = medioClinicUser.SecurityStamp; userInfo.UserNickName = userInfo.GetFormattedUserName(true); userInfo.UserAvatarID = medioClinicUser.AvatarId; userInfo.SetValue("UserPassword", medioClinicUser.PasswordHash); userInfo.UserSettings.UserDateOfBirth = medioClinicUser.DateOfBirth; userInfo.UserSettings.UserGender = (int)medioClinicUser.Gender; userInfo.UserSettings.UserPhone = medioClinicUser.Phone; userInfo.SetValue("City", medioClinicUser.City); userInfo.SetValue("Street", medioClinicUser.Street); userInfo.SetValue("Nationality", medioClinicUser.Nationality); }
/// <summary> /// Computes the user view model, based on roles. /// </summary> /// <param name="user">User to compute the view model by.</param> /// <param name="requestContext">Request context.</param> /// <param name="forceAvatarFileOverwrite">Flag that signals the need to update the app-local physical avatar file.</param> /// <returns>The view model and a page title.</returns> protected (IUserViewModel UserViewModel, string PageTitle) GetViewModelByUserRoles( MedioClinicUser user, RequestContext requestContext, bool forceAvatarFileOverwrite = false) { if (user != null) { var roles = user.Roles.ToMedioClinicRoles(); string avatarPhysicalPath = EnsureAvatarPhysicalPath(user, requestContext, forceAvatarFileOverwrite); var avatarRelativePath = avatarPhysicalPath != null ? FileManager.GetServerRelativePath(requestContext.HttpContext.Request, avatarPhysicalPath) : string.Empty; var commonUserModelCustomMappings = new Dictionary <(string propertyName, Type propertyType), object> { { (nameof(CommonUserViewModel.EmailViewModel), typeof(EmailViewModel)), new EmailViewModel { Email = user.Email } },
/// <summary> /// Updates the user in Kentico. /// </summary> /// <param name="user">The user to update.</param> /// <returns>A <see cref="Task"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="user"/> is <see langword="null"/>.</exception> /// <exception cref="Exception">Thrown when there's no <see cref="UserInfo"/> for the <paramref name="user"/>.</exception> public Task UpdateAsync(MedioClinicUser user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var userInfo = UserInfoProvider.GetUserInfo(user.Id); if (userInfo == null) { throw new Exception(ResHelper.GetString("General.UserNotFound")); } UserHelper.UpdateUserInfo(ref userInfo, user); UserInfoProvider.SetUserInfo(userInfo); return(Task.FromResult(0)); }
/// <summary> /// Create a user. /// </summary> /// <param name="user">A user to create.</param> /// <returns>A <see cref="Task"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="user"/> is <see langword="null"/>.</exception> public Task CreateAsync(MedioClinicUser user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var userInfo = user.ToUserInfo(); userInfo.UserGUID = user.GUID; userInfo.PasswordFormat = UserInfoProvider.NewPasswordFormat; userInfo.UserPasswordLastChanged = DateTime.Now; userInfo.IsExternal = user.IsExternal; UserInfoProvider.SetUserInfo(userInfo); UserInfoProvider.AddUserToSite(userInfo.UserName, SiteContextService.SiteName); user.Id = userInfo.UserID; return(Task.FromResult(0)); }
public Task RemoveFromRoleAsync(MedioClinicUser user, string roleName) => KenticoUserStore.RemoveFromRoleAsync(user, roleName);
public Task AddToRoleAsync(MedioClinicUser user, string roleName) => KenticoUserStore.AddToRoleAsync(user, roleName);
public async Task <IdentityManagerResult <RegisterResultState> > RegisterAsync(RegisterViewModel uploadModel, bool emailConfirmed, RequestContext requestContext) { var user = new MedioClinicUser { UserName = uploadModel.EmailViewModel.Email, Email = uploadModel.EmailViewModel.Email, FirstName = uploadModel.FirstName, LastName = uploadModel.LastName, Enabled = !emailConfirmed }; var accountResult = new IdentityManagerResult <RegisterResultState>(); IdentityResult identityResult = null; try { identityResult = await UserManager.CreateAsync(user, uploadModel.PasswordConfirmationViewModel.Password); } catch (Exception ex) { HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (identityResult != null && identityResult.Succeeded) { // Registration: Confirmed registration (begin) if (emailConfirmed) { string token = null; try { token = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); } catch (Exception ex) { accountResult.ResultState = RegisterResultState.TokenNotCreated; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (!string.IsNullOrEmpty(token)) { var confirmationUrl = new UrlHelper(requestContext).AbsoluteUrl( requestContext.HttpContext.Request, "ConfirmUser", routeValues: new { userId = user.Id, token }); await UserManager.SendEmailAsync(user.Id, Dependencies.LocalizationService.Localize("AccountManager.Register.Email.Confirm.Subject"), Dependencies.LocalizationService.LocalizeFormat("AccountManager.Register.Email.Confirm.Body", confirmationUrl)); accountResult.Success = true; accountResult.ResultState = RegisterResultState.EmailSent; } } // Registration: Confirmed registration (end) // Registration: Direct sign in (begin) else { identityResult = await AddToPatientRoleAsync(user.Id); try { await CreateNewAvatarAsync(user, requestContext.HttpContext.Server); await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); accountResult.ResultState = RegisterResultState.SignedIn; accountResult.Success = true; } catch (Exception ex) { accountResult.ResultState = RegisterResultState.NotSignedIn; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } } // Registration: Direct sign in (end) } accountResult.Errors.AddNonNullRange(identityResult.Errors); return(accountResult); }
public Task SetEmailAsync(MedioClinicUser user, string email) => KenticoUserStore.SetEmailAsync(user, email);
public async Task <IdentityManagerResult <ForgotPasswordResultState> > ForgotPasswordAsync(EmailViewModel uploadModel, RequestContext requestContext) { var accountResult = new IdentityManagerResult <ForgotPasswordResultState>(); MedioClinicUser user = null; try { user = await UserManager.FindByEmailAsync(uploadModel.Email); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.UserNotFound; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } // Registration: Confirmed registration (begin) if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { accountResult.ResultState = ForgotPasswordResultState.EmailNotConfirmed; return(accountResult); } // Registration: Confirmed registration (end) string token = null; try { token = await UserManager.GeneratePasswordResetTokenAsync(user.Id); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.TokenNotCreated; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } var resetUrl = new UrlHelper(requestContext).AbsoluteUrl( requestContext.HttpContext.Request, "ResetPassword", "Account", new { userId = user.Id, token }); try { await UserManager.SendEmailAsync(user.Id, Dependencies.LocalizationService.Localize("PassReset.Title"), Dependencies.LocalizationService.LocalizeFormat("AccountManager.ForgotPassword.Email.Body", resetUrl)); } catch (Exception ex) { accountResult.ResultState = ForgotPasswordResultState.EmailNotSent; HandleException(nameof(ForgotPasswordAsync), ex, ref accountResult); return(accountResult); } accountResult.Success = true; accountResult.ResultState = ForgotPasswordResultState.EmailSent; return(accountResult); }
public Task SetTwoFactorEnabledAsync(MedioClinicUser user, bool enabled) => KenticoUserStore.SetTwoFactorEnabledAsync(user, enabled);
public Task RemoveLoginAsync(MedioClinicUser user, UserLoginInfo login) => KenticoUserStore.RemoveLoginAsync(user, login);
public Task <bool> GetEmailConfirmedAsync(MedioClinicUser user) => KenticoUserStore.GetEmailConfirmedAsync(user);
public Task <string> GetEmailAsync(MedioClinicUser user) => KenticoUserStore.GetEmailAsync(user);
public Task <bool> GetTwoFactorEnabledAsync(MedioClinicUser user) => KenticoUserStore.GetTwoFactorEnabledAsync(user);
public Task DeleteAsync(MedioClinicUser user) => KenticoUserStore.DeleteAsync(user);
public Task <string> GetSecurityStampAsync(MedioClinicUser user) => KenticoUserStore.GetSecurityStampAsync(user);
public Task SetSecurityStampAsync(MedioClinicUser user, string stamp) => KenticoUserStore.SetSecurityStampAsync(user, stamp);
public Task <IList <UserLoginInfo> > GetLoginsAsync(MedioClinicUser user) => KenticoUserStore.GetLoginsAsync(user);
public Task <bool> IsInRoleAsync(MedioClinicUser user, string roleName) => KenticoUserStore.IsInRoleAsync(user, roleName);
PostProfileAsync(IUserViewModel uploadModel, RequestContext requestContext) { var profileResult = new IdentityManagerResult <PostProfileResultState, (IUserViewModel, string)>(); var userTitle = Dependencies.LocalizationService.Localize("General.User"); var userDoesntExistTitle = Dependencies.LocalizationService.Localize("Adm.User.NotExist"); profileResult.Data = (uploadModel, userTitle); MedioClinicUser user = null; try { user = await UserManager.FindByIdAsync(uploadModel.CommonUserViewModel.Id); } catch (Exception ex) { HandlePostProfileException(ref profileResult, ex, PostProfileResultState.UserNotFound); profileResult.Data = (uploadModel, userDoesntExistTitle); return(profileResult); } var commonUserModelCustomMappings = new Dictionary <(string propertyName, Type propertyType), object> { { (nameof(MedioClinicUser.Email), typeof(string)), uploadModel.CommonUserViewModel.EmailViewModel.Email }, }; try { // Map the common user properties. user = UserModelService.MapToMedioClinicUser(uploadModel.CommonUserViewModel, user, commonUserModelCustomMappings); // Map all other potential properties of specific models (patient, doctor, etc.) user = UserModelService.MapToMedioClinicUser(uploadModel, user); } catch (Exception ex) { HandlePostProfileException(ref profileResult, ex, PostProfileResultState.UserNotMapped); return(profileResult); } try { // We need to use the user store directly due to the design of Microsoft.AspNet.Identity.Core.UserManager.UpdateAsync(). await UserStore.UpdateAsync(user); var avatarFile = uploadModel.CommonUserViewModel.AvatarFile; if (avatarFile != null) { var avatarBinary = FileManager.GetPostedFileBinary(avatarFile); AvatarRepository.UploadUserAvatar(user, avatarBinary); } } catch (Exception ex) { HandlePostProfileException(ref profileResult, ex, PostProfileResultState.UserNotUpdated); return(profileResult); } (var model, var title) = GetViewModelByUserRoles(user, requestContext, true); if (model != null) { profileResult.Success = true; profileResult.ResultState = PostProfileResultState.UserUpdated; profileResult.Data = (model, title); } return(profileResult); }
public Task <IList <string> > GetRolesAsync(MedioClinicUser user) => KenticoUserStore.GetRolesAsync(user);
public async Task <IdentityManagerResult <RegisterResultState> > RegisterAsync(RegisterViewModel uploadModel, bool emailConfirmed, HttpRequest request) { var user = new MedioClinicUser { UserName = uploadModel.EmailViewModel.Email, Email = uploadModel.EmailViewModel.Email, FirstName = uploadModel.FirstName, LastName = uploadModel.LastName, Enabled = !emailConfirmed }; var accountResult = new IdentityManagerResult <RegisterResultState>(); IdentityResult?identityResult = default; try { identityResult = await _userManager.CreateAsync(user, uploadModel.PasswordConfirmationViewModel.Password !); } catch (Exception ex) { HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (identityResult?.Succeeded == true) { // Registration: Confirmed registration (begin) if (emailConfirmed) { string?token = default; try { token = await _userManager.GenerateEmailConfirmationTokenAsync(user); } catch (Exception ex) { accountResult.ResultState = RegisterResultState.TokenNotCreated; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } if (!string.IsNullOrEmpty(token)) { var confirmationUrl = _urlHelperFactory .GetUrlHelper(_actionContextAccessor.ActionContext) .AbsoluteUrl(request, uploadModel.PasswordConfirmationViewModel.ConfirmationAction !, routeValues: new { userId = user.Id, token }); var subject = ResHelper.GetString("Identity.Account.Register.Email.Confirm.Subject"); var body = ResHelper.GetStringFormat("Identity.Account.Register.Email.Confirm.Body", confirmationUrl); await _messageService.SendEmailAsync(user.Email, subject, body); accountResult.Success = true; accountResult.ResultState = RegisterResultState.EmailSent; } } // Registration: Confirmed registration (end) // Registration: Direct sign in (begin) else { identityResult = await AddToPatientRoleAsync(user.Id); try { await _signInManager.SignInAsync(user, isPersistent : false); accountResult.ResultState = RegisterResultState.SignedIn; accountResult.Success = true; } catch (Exception ex) { accountResult.ResultState = RegisterResultState.NotSignedIn; HandleException(nameof(RegisterAsync), ex, ref accountResult); return(accountResult); } } // Registration: Direct sign in (end) } accountResult.Errors.AddNonNullRange(identityResult?.Errors.Select(error => error.Description)); return(accountResult); }
public object MapToCustomModel( MedioClinicUser user, Type targetModelType, Dictionary <(string propertyName, Type propertyType), object> customMappings = null)
public Task SetEmailConfirmedAsync(MedioClinicUser user, bool confirmed) => KenticoUserStore.SetEmailConfirmedAsync(user, confirmed);