public virtual async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { UserRegistrationResult Result = _userRegistrationService.RegisterUser(model); if (Result.Success) { //await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent: false); //return RedirectToAction("Index", "Dashboard"); var code = await _userManager.GenerateEmailConfirmationTokenAsync(Result.NewlyRegistredUser); var callbackUrl = Url.Action( action: "RegistrationConfirmation", controller: "Authentication", values: new { userId = Result.NewlyRegistredUser.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(model.UserEmail, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); model.RegistrationConfirmationSent = true; } else { foreach (var item in Result.Errors) { ModelState.AddModelError(string.Empty, item); } } } return(View(model)); }
public UserRegistrationResult RegisterUser(User user) { if (user == null) { throw new ArgumentException("当前用户为空"); } var result = new UserRegistrationResult(); if (IsRegistered(user.UserName)) { result.AddError("用户名已经存在"); return(result); } if (String.IsNullOrEmpty(user.Email)) { result.AddError("邮箱不能为空"); return(result); } //if (user.Email.IsValidEmail()) //{ // result.AddError("邮件格式错误"); // return result; //} //if (user.Password.IsNullOrEmpty()) //{ // result.AddError("密码不能为空"); // return result; //} InsertUser(user); return(result); }
private IHttpActionResult GetErrorResult(UserRegistrationResult result) { if (result == null) { return(InternalServerError()); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { return(BadRequest()); } return(BadRequest(ModelState)); } return(null); }
public void RegisterNewUser_should_return_success_when_email_address_available() { CreateUserRegistrationService(); UserRegistrationResult result = Service.RegisterNewUser("*****@*****.**", "password"); result.IsError.Should().Be.False(); }
public void RegisterNewUser_should_return_new_user_instance_when_successful() { CreateUserRegistrationService(); UserRegistrationResult result = Service.RegisterNewUser("*****@*****.**", "password"); Assert.IsNotNull(result.CreatedUser); result.CreatedUser.EmailAddress.Should().Be.EqualTo("*****@*****.**"); }
public void RegisterNewUser_should_return_error_when_email_address_already_taken() { CreateUserRegistrationService(); AddUserToRepository("*****@*****.**"); UserRegistrationResult result = Service.RegisterNewUser("*****@*****.**", "password"); result.IsError.Should().Be.True(); }
public void RegisterNewUser_should_create_salt_and_hash_password() { CreateUserRegistrationService(); PasswordHashService.Stub(o => o.HashSaltAndPassword(null, null)) .IgnoreArguments() .Return("hashedpwd"); UserRegistrationResult result = Service.RegisterNewUser("*****@*****.**", "password"); result.CreatedUser.Salt.Should().Not.Be.Null(); result.CreatedUser.Salt.Should().Not.Be.Empty(); result.CreatedUser.Password.Should().Be.EqualTo("hashedpwd"); }
public virtual async Task <IActionResult> Register(RegisterViewModel model) { RedirectToActionResult RedirectNextPage = RedirectToAction("Register", "Home"); if (ModelState.IsValid) { UserRegistrationResult Result = _userRegistrationService.RegisterUser(model); if (Result.Success) { await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent : false); RedirectNextPage = RedirectToUserPortalByRole(model.RoleDefault); } } return(RedirectNextPage); }
public async Task <IHttpActionResult> Register(UserRegistrationInput userModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserRegistrationResult result = await _authenticationService.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return(errorResult); } return(Ok(result)); }
public void Execute() { using (IContainer context = NewContext()) { const string newUserEmail = "*****@*****.**"; const string newUserPassword = "******"; var userRegistrationService = context.Resolve <UserRegistrationService>(); UserRegistrationResult registrationResult = userRegistrationService.RegisterNewUser(newUserEmail, newUserPassword); registrationResult.IsError.Should().Be.False(); context.Resolve <IUnitOfWork>().Flush(); User loadedNewUser = context.Resolve <IUserRepository>().Get(registrationResult.CreatedUser.Id); Assert.IsNotNull(loadedNewUser); var authenticationService = context.Resolve <AuthenticationService>(); AuthenticationResult authResult = authenticationService.Authenticate(newUserEmail, newUserPassword); authResult.IsError.Should().Be.False(); } }
public virtual async Task <IActionResult> RegisterAgent(RegisterViewModel model) { if (ModelState.IsValid) { UserRegistrationResult Result = _userRegistrationService.RegisterUser(model); if (Result.Success) { await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent : false); return(RedirectToAction("Index", "Dashboard")); } else { foreach (var item in Result.Errors) { ModelState.AddModelError(string.Empty, item); } } } return(View()); }
public async Task <IActionResult> Post([FromBody] UserRegistrationRequest model) { // non-forced-to-disposal UserRegistrationResult result = new UserRegistrationResult { IsSucceded = true, ResultId = (int)UserRegistrationResultEnum.Success }; // forced-to-disposal MongoDBConnectionInfo mongoDBConnectionInfo = null; KeyVaultConnectionInfo keyVaultConnectionInfo = null; User user = null; try { if (string.IsNullOrEmpty(model.Fullname)) { throw new BusinessException((int)UserRegistrationResultEnum.FailedEmptyFullname); } if (string.IsNullOrEmpty(model.Email)) { throw new BusinessException((int)UserRegistrationResultEnum.FailedEmptyEmail); } if (string.IsNullOrEmpty(model.Password)) { throw new BusinessException((int)UserRegistrationResultEnum.FailedEmptyPassword); } using (ValidationHelper validationHelper = new ValidationHelper()) { bool validationEmail = validationHelper.IsValidEmail(model.Email); if (!validationEmail) { throw new BusinessException((int)UserRegistrationResultEnum.FailedNotValidEmail); } } mongoDBConnectionInfo = new MongoDBConnectionInfo() { ConnectionString = Settings.ConnectionString, DatabaseId = Settings.DatabaseId, UserCollection = Settings.UserCollection }; using (UserRegistrationDataHelper userRegistrationDataHelper = new UserRegistrationDataHelper(mongoDBConnectionInfo)) { user = userRegistrationDataHelper.GetUser(model.Email); } if (user != null) { throw new BusinessException((int)UserRegistrationResultEnum.FailedEmailAlreadyExists); } string password = string.Empty; using (HashHelper hashHelper = new HashHelper()) { password = hashHelper.GetSha256Hash(model.Password); } keyVaultConnectionInfo = new KeyVaultConnectionInfo() { CertificateName = Settings.KeyVaultCertificateName, ClientId = Settings.KeyVaultClientId, ClientSecret = Settings.KeyVaultClientSecret, KeyVaultIdentifier = Settings.KeyVaultIdentifier }; using (MessageQueueHelper messageQueueHelper = new MessageQueueHelper()) { UserRegistrationMessage userRegistrationMessage = new UserRegistrationMessage() { fullname = model.Fullname, email = model.Email, password = password }; await messageQueueHelper.QueueMessageAsync(userRegistrationMessage, Settings.UserRegistrationQueueName, keyVaultConnectionInfo); } } catch (Exception ex) { result.IsSucceded = false; if (ex is BusinessException) { result.ResultId = ((BusinessException)ex).ResultId; } else { result.ResultId = (int)UserRegistrationResultEnum.Failed; this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } } finally { mongoDBConnectionInfo = null; keyVaultConnectionInfo = null; user = null; GC.Collect(); } string message = EnumDescription.GetEnumDescription((UserRegistrationResultEnum)result.ResultId); this.logger.LogInformation($">> Message information: {message}"); return((result.IsSucceded) ? (ActionResult) new OkObjectResult(new { message = message }) : (ActionResult) new BadRequestObjectResult(new { message = message })); }
/// <summary> /// Register user /// </summary> /// <param name="request">Request</param> /// <returns>Result</returns> public virtual UserRegistrationResult RegisterUser(UserRegistrationRequest request) { if (request == null) throw new ArgumentNullException("request"); if (request.User == null) throw new ArgumentException("Can't load current user"); var result = new UserRegistrationResult(); if (request.User.IsSearchEngineAccount()) { result.AddError("Search engine can't be registered"); return result; } if (request.User.IsBackgroundTaskAccount()) { result.AddError("Background task account can't be registered"); return result; } if (request.User.IsRegistered()) { result.AddError("Current user is already registered"); return result; } if (String.IsNullOrEmpty(request.Email)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided")); return result; } if (!CommonHelper.IsValidEmail(request.Email)) { result.AddError(_localizationService.GetResource("Common.WrongEmail")); return result; } if (String.IsNullOrWhiteSpace(request.Password)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided")); return result; } if (_userSettings.UsernamesEnabled) { if (String.IsNullOrEmpty(request.Username)) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided")); return result; } } //validate unique user if (_userService.GetUserByEmail(request.Email) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists")); return result; } if (_userSettings.UsernamesEnabled) { if (_userService.GetUserByUsername(request.Username) != null) { result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists")); return result; } } //at this point request is valid request.User.Username = request.Username; request.User.Email = request.Email; request.User.PasswordFormat = request.PasswordFormat; switch (request.PasswordFormat) { case PasswordFormat.Clear: { request.User.Password = request.Password; } break; case PasswordFormat.Encrypted: { request.User.Password = _encryptionService.EncryptText(request.Password); } break; case PasswordFormat.Hashed: { string saltKey = _encryptionService.CreateSaltKey(5); request.User.PasswordSalt = saltKey; request.User.Password = _encryptionService.CreatePasswordHash(request.Password, saltKey, _userSettings.HashedPasswordFormat); } break; default: break; } request.User.Active = request.IsApproved; //add to 'Registered' role var registeredRole = _userService.GetUserRoleBySystemName(SystemUserRoleNames.Registered); if (registeredRole == null) throw new CmsException("'Registered' role could not be loaded"); request.User.UserRoles.Add(registeredRole); //remove from 'Guests' role var guestRole = request.User.UserRoles.FirstOrDefault(cr => cr.SystemName == SystemUserRoleNames.Guests); if (guestRole != null) request.User.UserRoles.Remove(guestRole); _userService.UpdateUser(request.User); return result; }
private static void Main(string[] args) { Task.Run(() => { try { // initialize settings Init(); Console.WriteLine($"Take it easy, the console will display important messages, actually, it's running!! :)"); ConnectionFactory factory = new ConnectionFactory(); factory.UserName = Settings.RabbitMQUsername; factory.Password = Settings.RabbitMQPassword; factory.HostName = Settings.RabbitMQHostname; factory.Port = Settings.RabbitMQPort; factory.RequestedHeartbeat = 60; factory.DispatchConsumersAsync = true; var connection = factory.CreateConnection(); var channel = connection.CreateModel(); channel.QueueDeclare(queue: Settings.UserRegistrationQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new AsyncEventingBasicConsumer(channel); consumer.Received += async(model, ea) => { UserRegistrationResult result = new UserRegistrationResult { IsSucceded = true, ResultId = (int)UserRegistrationResultEnum.Success }; // forced-to-disposal WalletRegistrationInfo walletInfo = null; NBitcoin.Wordlist nwordlist = null; Nethereum.HdWallet.Wallet wallet = null; Nethereum.Web3.Accounts.Account account = null; string jsonDecrypted = string.Empty; string jsonEncrypted = string.Empty; User user = null; UserActivationDataHelper userActivationDataHelper = null; MailHelper mailHelper = null; try { byte[] body = ea.Body; var message = Encoding.UTF8.GetString(body); var decrypted = string.Empty; decrypted = NETCore.Encrypt.EncryptProvider.AESDecrypt(message, secret); var obj_decrypted = JsonConvert.DeserializeObject <UserRegistrationMessage>(decrypted); var aeskey_wallet = NETCore.Encrypt.EncryptProvider.CreateAesKey(); var key_wallet = aeskey_wallet.Key; nwordlist = new NBitcoin.Wordlist(wordlist.ToArray(), ' ', "english"); wallet = new Nethereum.HdWallet.Wallet(nwordlist, NBitcoin.WordCount.Eighteen, key_wallet); account = wallet.GetAccount(0); walletInfo = new WalletRegistrationInfo(); walletInfo.address = account.Address; walletInfo.privateKey = account.PrivateKey; walletInfo.password = key_wallet; walletInfo.mnemonic = string.Join(" ", wallet.Words); jsonDecrypted = JsonConvert.SerializeObject(walletInfo); var aeskey_data = NETCore.Encrypt.EncryptProvider.CreateAesKey(); var key_data = aeskey_data.Key; jsonEncrypted = NETCore.Encrypt.EncryptProvider.AESEncrypt(jsonDecrypted, key_data); string identicon = string.Empty; try { Identicon.FromValue($"{account.Address}", size: 160).SaveAsPng($"{account.Address}.png"); byte[] binary = System.IO.File.ReadAllBytes($"{account.Address}.png"); identicon = Convert.ToBase64String(binary); System.IO.File.Delete($"{account.Address}.png"); Console.WriteLine($">> Identicon deleted from local storage"); } catch (Exception ex) { Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } try { System.IO.File.Delete($"{account.Address}.png"); Console.WriteLine($">> Identicon deleted from local storage"); } catch { } } userActivationDataHelper = new UserActivationDataHelper(mongoDBConnectionInfo); // get user by email user = userActivationDataHelper.GetUser(obj_decrypted.email); if (user != null) { throw new BusinessException((int)UserRegistrationResultEnum.FailedEmailAlreadyExists); } user = new User(); user.fullname = obj_decrypted.fullname; user.email = obj_decrypted.email; user.password = obj_decrypted.password; user.role = "user"; user.address = account.Address; user.dataenc = jsonEncrypted; user.datakey = key_data; user.identicon = identicon; // register user await userActivationDataHelper.RegisterUserAsync(user); mailHelper = new MailHelper(); // send email await mailHelper.SendRegistrationEmailAsync(user.email, user.fullname); Console.WriteLine($">> Email: {user.email} activated successfully"); channel.BasicAck(ea.DeliveryTag, false); Console.WriteLine($">> Acknowledgement completed, delivery tag: {ea.DeliveryTag}"); } catch (Exception ex) { if (ex is BusinessException) { result.IsSucceded = false; result.ResultId = ((BusinessException)ex).ResultId; string message = EnumDescription.GetEnumDescription((UserRegistrationResultEnum)result.ResultId); Console.WriteLine($">> Message information: {message}"); } else { Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } } finally { nwordlist = null; wallet = null; account = null; walletInfo = null; jsonDecrypted = null; jsonEncrypted = null; user = null; userActivationDataHelper.Dispose(); mailHelper.Dispose(); } }; String consumerTag = channel.BasicConsume(Settings.UserRegistrationQueueName, false, consumer); } catch (Exception ex) { Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}"); } } }); // handle Control+C or Control+Break Console.CancelKeyPress += (o, e) => { Console.WriteLine("Exit"); // allow the manin thread to continue and exit... waitHandle.Set(); }; // wait waitHandle.WaitOne(); }
public virtual UserRegistrationResult RegisterUser(UserRegistrationRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var result = new UserRegistrationResult(); if (String.IsNullOrEmpty(request.Email)) { result.AddError("Email Address is missing!"); return(result); } if (!CommonHelper.IsValidEmail(request.Email)) { result.AddError("Email Address is not valid!"); return(result); } if (String.IsNullOrWhiteSpace(request.Password)) { result.AddError("Password is missing!"); return(result); } if (String.IsNullOrEmpty(request.Username)) { result.AddError("Username is missing!"); return(result); } //validate unique user if (GetUserByEmail(request.Email) != null) { result.AddError("Email Already Exists!"); return(result); } if (GetUserByUsername(request.Username) != null) { result.AddError("Username Already Exists!"); return(result); } //at this point request is valid request.User = new User(); request.User.UserName = request.Username; request.User.Email = request.Email; request.User.Password = request.Password; request.User.IsApproved = request.IsApproved; request.User.IsActive = request.IsActive; request.User.AddressLine1 = ""; request.User.AddressLine2 = ""; request.User.CityId = 0; request.User.CoverPictureId = 0; request.User.FirstName = ""; request.User.MiddleName = ""; request.User.ProfilePictureId = 0; request.User.SeoName = request.Username; request.User.UserGuid = Guid.NewGuid(); request.User.UserId = 1; request.User.CreatedOn = request.User.ModifiedOn = DateTime.Now; request.User.LastLoginDate = DateTime.Now; var registeredRole = _roleService.GetRoleByName("General"); if (registeredRole == null) { throw new Exception("'Registered' role could not be loaded"); } request.User.Roles.Add(registeredRole); Insert(request.User); result.User = request.User; return(result); }