public async Task <IHttpActionResult> Register(UserLoginData userLogin) { var username = userLogin.Username ?? string.Empty; var password = userLogin.Password ?? string.Empty; username = username.Trim(); if (username.Any() == false) { return(BadRequest("Username can't be blank.")); } if (await _userStore.GetUserAsync(username) != null) { return(BadRequest("Username already exists.")); } if (password.Length < _userSettings.UserPasswordMinLength) { return(BadRequest($"Password must be {_userSettings.UserPasswordMinLength} or more characters long.")); } int passwordHash = password.GetAsPasswordHash(); await _userStore.AddUserAsync(username, passwordHash); _log.LogInfo($"User '{username}' registered."); return(Ok("User registered.")); }
public override async Task <int> RunAsync(List <string> remaining) { if (remaining.Count < 1) { ShowHelp(Console.Error, "User command required", null, null); return(1); } string command = remaining[0]; remaining.RemoveAt(0); switch (command) { case "add": { string username = null; string password = null; OptionSet p = new OptionSet() .Add("user|username|u=", "User name", u => username = u) .Add("password|pwd|p=", "password", v => password = v); remaining = p.Parse(remaining); if (remaining.Count != 0) { ShowHelp(Console.Error, $"Unrecognized argument '{remaining[0]}'", p, null); return(1); } await _userStore.AddUserAsync(username, password, CancellationToken.None); return(0); } default: ShowHelp(Console.Error, $"Unrecognized user command '{command}'", null, null); return(1); } }
public async Task <User> UserLogin(string provider, string subjectId, List <Claim> claims, string clientId) { //check if the external user is already provisioned var user = await _userStore.FindByExternalProviderAsync(provider, subjectId); if (user == null) { user = CreateNewUser(provider, subjectId, claims, clientId); _logger.Information($"User not found. Attempting to create user: {user}"); await _userStore.AddUserAsync(user); return(user); } //update certain user information on every login user.Claims = FilterClaims(claims); SetNamePropertiesFromClaims(user); user.SetLastLoginDateForClient(clientId); _userStore.UpdateUser(user); return(user); }
/// <summary> /// Validates submitted user details for creating new user /// </summary> /// <param name="userForRegister">User submitted details</param> /// <returns>Created user record</returns> public async Task <User> RegisterUserAsync(UserForRegister userForRegister) { if (userForRegister == null) { throw new ArgumentNullException(nameof(userForRegister)); } if (await _store.UserExistsAsync(userForRegister.Email)) { throw new ArgumentException("User already exists by that email address"); } var(passwordHash, passwordSalt) = _helpers.CreatePasswordHash(userForRegister.Password); var userToAdd = _mapper.Map <User>(userForRegister); userToAdd.CreatedAt = DateTime.Now; userToAdd.PasswordHash = passwordHash; userToAdd.PasswordSalt = passwordSalt; var user = await _store.AddUserAsync(userToAdd); return(user); }
public async Task <WebStatus> RegisterAsync(RegisterInputModel model) { var genericSuccessMessage = _localizer["Please check your email to complete the sign up process."]; _logger.LogDebug("Begin registration for {0}", model.Email); if (!ApplicationIdIsNullOrValid(model.ApplicationId)) { return(WebStatus.Error(_localizer["Invalid application id."], HttpStatusCode.BadRequest)); } if (!await _userStore.UsernameIsAvailable(model.Email)) { _logger.LogDebug("Existing user found."); var sendStatus = await _messageService.SendAccountAlreadyExistsMessageAsync(model.ApplicationId, model.Email); // Return a generic success message to prevent account discovery. Only the owner of // the email address will get a customized message. return(sendStatus.IsOk ? WebStatus.Success(genericSuccessMessage) : new WebStatus(sendStatus)); } if (await _oneTimeCodeService.UnexpiredOneTimeCodeExistsAsync(model.Email)) { // Although the username is available, there is a valid one time code // that can be used to cancel an email address change, so we can't // reuse the address quite yet return(WebStatus.Error(_localizer["Email address is temporarily reserved."], HttpStatusCode.Conflict)); } _logger.LogDebug("Email address not used by an existing user. Creating a new user."); // consider: in some cases may want to restricting claims to a list predefined by the system administrator var status = new WebStatus(); if (model.Claims == null) { model.Claims = new Dictionary <string, string>(); } var internalClaims = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>( PasswordlessLoginConstants.Security.EmailNotConfirmedClaimType, "!") }; var newUser = new User() { Email = model.Email, Claims = model.Claims .Where(x => !PasswordlessLoginConstants.Security.ForbiddenClaims.Contains(x.Key) && !PasswordlessLoginConstants.Security.ProtectedClaims.Contains(x.Key)) .Union(internalClaims) .Select(x => new UserClaim() { Type = x.Key, Value = x.Value }) }; var newUserResponse = await _userStore.AddUserAsync(newUser); if (newUserResponse.HasError) { return(new WebStatus(newUserResponse.Status)); } newUser = newUserResponse.Result; await _eventNotificationService.NotifyEventAsync(newUser.Email, EventType.Register); if (!string.IsNullOrEmpty(model.Password)) { var setPasswordStatus = await _passwordService.SetPasswordAsync(newUser.SubjectId, model.Password); if (setPasswordStatus.IsOk) { await _eventNotificationService.NotifyEventAsync(newUser.Email, EventType.SetPassword); } else { status.AddWarning(_localizer["Password was not set."]); } } status.AddSuccess(genericSuccessMessage); var nextUrl = !string.IsNullOrEmpty(model.NextUrl) ? model.NextUrl : _urlService.GetDefaultRedirectUrl(); if (model.SetPassword) { _logger.LogTrace("The user will be asked to set their password after confirming the account."); nextUrl = SendToSetPasswordFirst(nextUrl); } var oneTimeCodeResponse = await _oneTimeCodeService.GetOneTimeCodeAsync(model.Email, TimeSpan.FromMinutes(_options.ConfirmAccountLinkValidityMinutes), nextUrl); switch (oneTimeCodeResponse.Status.StatusCode) { case GetOneTimeCodeStatusCode.Success: var result = await _messageService.SendWelcomeMessageAsync(model.ApplicationId, model.Email, oneTimeCodeResponse.Result.ShortCode, oneTimeCodeResponse.Result.LongCode, model.Claims); SetNonce(oneTimeCodeResponse.Result.ClientNonce); return(new WebStatus(status)); case GetOneTimeCodeStatusCode.TooManyRequests: return(WebStatus.Error(_localizer["Please wait a few minutes and try again."], HttpStatusCode.TooManyRequests)); case GetOneTimeCodeStatusCode.ServiceFailure: default: return(ServerError(_localizer["Hmm. Something went wrong. Please try again."])); } }
public async Task <ActionResponse> RegisterAsync(RegisterInputModel model) { if (!string.IsNullOrEmpty(model.ApplicationId)) { var app = await _clientStore.FindEnabledClientByIdAsync(model.ApplicationId); if (app == null) { return(BadRequest("Invalid application id")); } } TimeSpan linkValidity; var existingUser = await _userStore.GetUserByEmailAsync(model.Email); if (existingUser == null) { var newUser = new User() { Email = model.Email, Claims = model.Claims?.Select(x => new UserClaim() { Type = x.Key, Value = x.Value }) //todo: filter these to claim types that are allowed to be set by user }; newUser = await _userStore.AddUserAsync(newUser); linkValidity = TimeSpan.FromHours(24); } else { linkValidity = TimeSpan.FromMinutes(5); //may want allow admins to configure a different email to send to existing users. However, it could be that the user // exists but just never got a welcome email? } var nextUrl = !string.IsNullOrEmpty(model.NextUrl) ? model.NextUrl : _urlHelper.Action("Apps", "Home"); if (model.InviteToSetPasword) { nextUrl = SendToSetPasswordFirst(nextUrl); } var oneTimeCodeResponse = await _oneTimeCodeService.GetOneTimeCodeAsync(model.Email, linkValidity, nextUrl); switch (oneTimeCodeResponse.Result) { case GetOneTimeCodeResult.Success: var result = await _messageService.SendWelcomeMessageAsync(model.ApplicationId, model.Email, oneTimeCodeResponse.ShortCode, oneTimeCodeResponse.LongCode, model.MailMergeValues); if (result.MessageSent) { return(Ok("Thanks for registering. Please check your email.")); } else { return(ServerError(result.ErrorMessageForEndUser)); } case GetOneTimeCodeResult.TooManyRequests: return(BadRequest("Please wait a few minutes and try again")); case GetOneTimeCodeResult.ServiceFailure: default: return(ServerError("Hmm, something went wrong. Can you try again?")); } }