public void ApplicationReturnsMessage() { var app2 = new Application("*****@*****.**", "password", "password"); _result = new Registrator().ApplyForMembership(app2); Assert.Contains("ex", _result.Application.UserMessage); }
/// <summary> /// Массовая перерегистрация сборок (разрегистрация и регистрация заново) (Разрегистрация для RegSvr32 е реализовано) /// </summary> /// <param name="assembly">Ссылка на файл сборки</param> /// <param name="context">Флаги регистрации</param> /// <param name="force">ФЛаг принудительной регистрации (true по умолчанию)</param> /// <returns>Возвращает результаты выполненных операций</returns> public static Result ReInstall(FileInfo assembly, AssemblyRegContext context, bool force = true) { RegistrationResult gacResult = RegistrationResult.UnKnown; if (context.ContainsFlag(AssemblyRegContext.GAC)) { UnInstall_GAC(assembly); gacResult = Install_GAC(assembly); } var regAsmResult = RegistrationResult.UnKnown; if (context.ContainsFlag(AssemblyRegContext.RegAsm)) { UnInstall_ByRegAsm(assembly); regAsmResult = Install_ByRegAsm(assembly); } var regSvrResult = RegistrationResult.UnKnown; if (context.ContainsFlag(AssemblyRegContext.RegSvr32)) { //regSvrResult = ResultFromExitcode(Install_ByRegSvr32(assembly)); regSvrResult = Install_ByRegSvr32(assembly); } return(new Result(gacResult, regAsmResult, regSvrResult)); }
/// <summary> /// Add a new player to the database /// </summary> /// <param name="firstName">User first name</param> /// <param name="lastName">User last name</param> /// <param name="nickName">User nick name</param> /// <param name="email">User email address</param> /// <param name="password">User password</param> /// <returns></returns> public RegistrationResult AddPlayer(string firstName, string lastName, string nickName, string email, string password) { logger.Info("AddPlayer"); // Generate password hash based on the user password and some salt. string passwordHash = GetHashString(password + salt); RegistrationResult result = new RegistrationResult(); try { if (matixData.IsPlayerEmailExist(email)) { // Error result.Status = OperationStatusnEnum.InvalidEmail; } // Add user credentials to the database matixData.AddPlayer(firstName, lastName, nickName, email, passwordHash); result.Status = OperationStatusnEnum.Success; } catch (System.InvalidOperationException ex) { logger.ErrorFormat("AddPlayer - Exception: {0}", ex); result.Status = OperationStatusnEnum.Failure; } return(result); }
public async Task <RegistrationResult> RegisterAsync(string username, string password, string confirmPassword, EmployeeDTO employee) { RegistrationResult result = RegistrationResult.Success; if (password != confirmPassword) { result = RegistrationResult.PasswordsDoNotMatch; return(result); } Account usernameAccount = await _accountRepository.GetByUsernameAsync(username); if (usernameAccount != null) { result = RegistrationResult.UsernameAlreadyExists; return(result); } if (result == RegistrationResult.Success) { Account account = new Account() { Employee = _mapper.Map <Employee>(employee), UserName = username, }; string hashedPassword = _passwordHasher.HashPassword(account, password); account.PasswordHash = hashedPassword; await _accountRepository.CreateAsync(account); } return(result); }
/// <summary> /// Index a package from its metadata /// </summary> /// <param name="nuspecReader">The nuspec reader instance to be used to read metadata</param> /// <returns>The <see cref="RegistrationResult"/> instance which correspond to the package</returns> public override async Task <RegistrationResult> IndexPackage(INuspecCoreReader nuspecReader) { if (nuspecReader == null) { throw new ArgumentNullException(nameof(nuspecReader)); } var indexingStopwatch = Stopwatch.StartNew(); string version = nuspecReader.GetVersion().ToNormalizedString(); string packageRegistrationBaseUrl = $"{registrationServiceUrl + nuspecReader.GetId()}/index.json"; logger.LogDebug(LoggingEvents.PackageIndexIndexingPackage, "Indexing package {packageId}, version {version}", nuspecReader.GetId(), version); RegistrationResult registrationIndex = this.packages.FirstOrDefault(p => p.Id == packageRegistrationBaseUrl); registrationIndex = await this.IndexPackageCore(nuspecReader, registrationIndex).ConfigureAwait(false); await this.SavePackageIndex().ConfigureAwait(false); indexingStopwatch.Stop(); logger.LogInformation(LoggingEvents.PackageIndexPackageIndexed, "Package {packageId}, version {version} indexed in {elapsed}", nuspecReader.GetId(), version, indexingStopwatch.Elapsed); var metricEvent = new EventTelemetry("PackageIndexed"); metricEvent.Metrics.Add("packageIndexed", indexingStopwatch.ElapsedMilliseconds); telemetryClient.TrackEvent(metricEvent); return(registrationIndex); }
public async Task <RegistrationResult> Register(string email, string username, string password, string passwordConfirm) { RegistrationResult result = RegistrationResult.Success; var emailAccount = await _accountDataService.GetByEmail(email); if (emailAccount != null) { result = RegistrationResult.EmailAlreadyExists; } var usernameAccount = await _accountDataService.GetByUsername(username); if (usernameAccount != null) { throw new Exception(); // TODO: use custom exception } if (!password.Equals(passwordConfirm)) { result = RegistrationResult.PasswordsDoNotMatch; } if (result == RegistrationResult.Success) { IPasswordHasher hasher = new PasswordHasher(); string passwordHash = hasher.HashPassword(password); Account account = new Account(_keyExchangeService, _messageEncryptionService, _messageDecryptionService, email, username, passwordHash); await _accountDataService.Create(account); } return(result); }
public async Task <IActionResult> ExternalLoginFormAction(ExternalLoginModel model) { if (ModelState.IsValid) { // Get the information about the user from the external login provider ExternalLoginInfo info = await _authentication.GetExternalLoginInfoAsync(); if (info == null) { throw new ApplicationException("Error loading external login information during confirmation."); } //var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; //var result = await _userManager.CreateAsync(user); RegistrationResult result = await _registration.RegisterAsync(model.Login, model.Email); if (result == RegistrationResult.Success) { IdentityResult identResult = await _moneyUserManager.AddLoginAsync(model.Login, info); if (identResult.Succeeded) { //await _signInManager.SignInAsync(user, isPersistent: false); await _authentication.SignInAsync(model.Login, false); await _logManager.WriteAsync(model.Login, $"New user '{model.Login}' was registered with {info.ProviderDisplayName}."); //_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); //return RedirectToLocal(returnUrl); return(RedirectToAction(nameof(HomeController.Index), "Home")); } } //AddErrors(result); } return(View(nameof(ExternalLogin), model)); }
public async Task <RegistrationResult> RegisterAsync(User newUser) { var existingUsers = await _storageService.GetAllUsers(); var userExists = existingUsers.Where(x => x.Email == newUser.Email).Any(); if (userExists) { return(new RegistrationResult { StatusCode = System.Net.HttpStatusCode.Ambiguous, Success = false, Messages = new[] { $"Uesr with this email {newUser.Email} address is already exists in the system" } }); } newUser.Id = Guid.NewGuid().ToString(); var userAdded = await _storageService.AddUser(newUser); var registerUserResponse = new RegistrationResult { StatusCode = userAdded ? System.Net.HttpStatusCode.OK : System.Net.HttpStatusCode.InternalServerError, Success = userAdded ? true : false, Messages = userAdded ? new[] { $"The uesr {newUser.Email} is created" } : new[] { $"The uesr {newUser.Email} is not created, Internel server error." } }; return(registerUserResponse); }
public async Task <RegistrationResult> RegisterAndSignInAsync(Registration registration) { if (registration == null) { throw new ArgumentNullException(nameof(registration)); } var result = new RegistrationResult(); var user = Mapper.Map <ApplicationUserEntity>(registration); user.UserName = registration.Email; var createResult = await UserManager.CreateAsync(user, registration.Password); if (!createResult.Succeeded) { result.ErrorMessages = createResult.Errors.ToList(); return(result); } await SignInAsync(user, isPersistent : false, rememberBrowser : false); return(result); }
public override async Task ExecuteAsync(object parameter) { _registerViewModel.ErrorMessage = ""; try { RegistrationResult registrationResult = await _authenticator.Register(_registerViewModel.Email, _registerViewModel.Username, _registerViewModel.Password, _registerViewModel.ConfirmPassword); switch (registrationResult) { case RegistrationResult.Success: _registerRenavigator.Renavigate(); break; case RegistrationResult.PasswordsNotMatch: _registerViewModel.ErrorMessage = "Passwords does not match."; break; case RegistrationResult.EmailAlreadyExists: _registerViewModel.ErrorMessage = "Email already exist. Please try again."; break; case RegistrationResult.UsernameAlreadyExists: _registerViewModel.ErrorMessage = "Username already exists. Please try again."; break; default: _registerViewModel.ErrorMessage = "Registration Failed!"; break; } } catch (Exception) { _registerViewModel.ErrorMessage = "Registration Failed!"; } }
public async Task RegistrationOK() { //Arrange string login = "******"; string password = "******"; string email = "*****@*****.**"; IRegistration registration = new Registration(_userManager, _signInManager, _dbContext); IAuthentication authentication = new Authentication(_signInManager, _userManager); ApplicationRole role = new ApplicationRole() { Name = "User" }; await _roleManager.CreateAsync(role); await _roleManager.UpdateAsync(role); //var prop = _roleManager.GetType().GetProperty("Store", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); //object store = prop.GetValue(_roleManager); //object dbcontext1 = store.GetType().GetProperty("Context").GetValue(store); ApplicationRole userRole = await _dbContext.Roles.FirstOrDefaultAsync(r => r.Name == "User"); IEnumerable <ApplicationRole> roles = _dbContext.Roles; //Act RegistrationResult regResult = await registration.RegisterAsync(login, email, password); //Assert ApplicationUser resultUser = await _dbContext.Users.FirstOrDefaultAsync(u => u.UserName == login); Assert.AreEqual(RegistrationResult.Success, regResult); Assert.NotNull(resultUser); }
public override async Task ExecuteAsync(object parameter) { _registerViewModel.ErrorMessage = string.Empty; RegistrationResult registrationResult = await _authenticator.Register( _registerViewModel.Email, _registerViewModel.Username, _registerViewModel.Password, _registerViewModel.ConfirmPassword); switch (registrationResult) { case RegistrationResult.Success: _renavigator.Renavigate(); break; case RegistrationResult.PasswordsDoNotMatch: _registerViewModel.ErrorMessage = "Confirm password does not match origin password."; break; case RegistrationResult.EmailAlreadyExists: _registerViewModel.ErrorMessage = "An account with this email already exists."; break; case RegistrationResult.UsernameAlreadyExists: _registerViewModel.ErrorMessage = "An account with this username already exists."; break; default: _registerViewModel.ErrorMessage = "Registration failed."; break; } }
public async Task <RegistrationResult> Register(string confirmPassword, User user) { RegistrationResult result = RegistrationResult.Success; if (user.Password != confirmPassword) { result = RegistrationResult.PasswordsDoNotMatch; } User emailAccount = await _accountService.GetByEmail(user.Email); if (emailAccount != null) { result = RegistrationResult.EmailAlreadyExists; } if (result == RegistrationResult.Success) { User user1 = new User { Email = user.Email, Password = _passwordHasher.HashPassword(user.Password), Type = 2, CreatedAt = DateTime.Now, }; } return(result); }
public async Task <IActionResult> OnPostRegister() { //var user = configuration.GetSection("SiteUser").Get<SiteUser>(); /*UserController userController = configuration.GetSection("UserController").Get<UserController>(); * LoginResult lResult = userController.LoginUser(UserName, Password);*/ UserController userController = new UserController(db); RegistrationResult rResult = userController.RegisterUser(Username, Password, Email); if (rResult.GetStatus() == RegistrationResult.RegistrationStatus.RegistrationSuccess) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, Username) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return(RedirectToPage("/User/Home")); } else { HasErrorMessage = true; Message = rResult.GetStatus().ToString(); } //Message = "Invalid attempt"; return(Page()); }
public RegistrationResult AddUser(User user, Guid role, Account ac) { RegistrationResult result = RegistrationResult.Successful; BAAccount baAccount = new BAAccount(); Account a = baAccount.GetAccountByUsername(ac.Username); User u = GetUserByEmail(user.Email); if (a == null && u == null) { baAccount.AddAccount(ac); new DAUser(this.Entities).AddUser(user); user.UserTypeID = role; result = RegistrationResult.Successful; } else { if (a != null) { result = RegistrationResult.UsernamExists; } else { result = RegistrationResult.EmailExists; } } return(result); }
public ActionResult <RegistrationResult> Create([FromBody] RegistrationForm form) { var pipeline = Pipeline .Create(new ValidateFormStep()) .Then(new VerifyUniqueAccountStep()) .Then(new CreateAccountObjectStep()) .Then(new ProvisionAccountStep()) .Then(new SendVerificationEmailStep()); var pipelineContext = new PipelineContext(); RegistrationResult result = null; try { result = pipeline.Execute(form, pipelineContext); } catch (Exception ex) { Console.WriteLine($"Something went terribly, terribly wrong: {ex}"); } if (result == null) { Console.WriteLine("Something failed."); return(StatusCode((int)HttpStatusCode.InternalServerError)); } return(Ok(result)); }
public RegistrationResult Register(string username, string password, string confirmPassword, double balance) { RegistrationResult result = RegistrationResult.Success; if (password != confirmPassword) { result = RegistrationResult.PasswordDoNotMatch; } Account potentiallyExistedUser = _accountRepository.GetByUsername(username); if (potentiallyExistedUser != null) { result = RegistrationResult.UsernameAlreadyExist; } if (result == RegistrationResult.Success) { string hashedPassword = _passwordHasher.HashPassword(password); Guid guid = new Guid(); Account user = new Account() { Id = guid, Username = username, Password = hashedPassword, Balance = balance, }; _accountRepository.Create(user); } return(result); }
public ConditionalResults(BaseConditionalRegistration registration, RegistrationResult result, Dictionary <PropertyDefinition, object> data) { this.Completed = (ExDateTime)TimeProvider.UtcNow; this.Registration = registration; this.Result = result; this.Data = data; }
public RegistrationResult Register(string client_ID, string name, string phone_Num, int?House_Num, int?Flat_Num, string Street, string City, string email, string login, string password, string confirmPassword, bool isAdmin) { RegistrationResult result = RegistrationResult.Success; if (_unitOfWork.Clients.GetByUsername(login) != null) //не зависает при удалении await, но возвращает !null при верных данных { result = RegistrationResult.LoginAlreadyExists; } else if (password == confirmPassword && result == RegistrationResult.Success) { Address addr = new Address(City, Street, House_Num, Flat_Num); _unitOfWork.Addresses.Add(addr); _unitOfWork.Complete(); string hashedPassword = _passwordHasher.HashPassword(password); Client client = new Client(name, phone_Num, _unitOfWork.Addresses.GetAddressByObj(addr).AddressID, email, login, hashedPassword, isAdmin); _unitOfWork.Clients.Add(client); _unitOfWork.Complete(); } else if (password != confirmPassword) { result = RegistrationResult.PasswordDoNotMatch; } return(result); }
public void ApplicationIsInvalid() { var app2 = new Application("*****@*****.**", "password", "password"); _result = new Registrator().ApplyForMembership(app2); Assert.True(app2.IsInvalid()); }
public async Task Register_NewUserAndMatchingPasswords() { RegistrationResult expected = RegistrationResult.Success; RegistrationResult real = await _authentication.Register(It.IsAny <string>(), It.IsAny <string>(), "testpass", "testpass"); Assert.AreEqual(expected, real); }
public ValidApplicationReceived() : base() { _reg = new Registrator(); var app = new Application(email: "*****@*****.**", password: "******", confirm: "password"); _result = _reg.ApplyForMembership(app); _user = _result.NewUser; }
public async Task Register_WithNonExistingUserAndMatchingPassword_ReturnsSuccess() { RegistrationResult expected = RegistrationResult.Success; RegistrationResult actual = await _autenticationService.Register(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()); Assert.AreEqual(expected, actual); }
public Result(RegistrationResult gac = RegistrationResult.UnKnown , RegistrationResult regAsm = RegistrationResult.UnKnown , RegistrationResult regSvr32 = RegistrationResult.UnKnown) { GAC = gac; RegAsm = regAsm; RegSvr32 = regSvr32; }
public RegisteredByExternalMethodEventHandler( Customer customer, ExternalAuthParam parameters, RegistrationResult registrationResult) { Customer = customer; AuthenticationParameters = parameters; RegistrationResult = registrationResult; }
public async Task <RegistrationResult> Register(string email, string username, string password, string confirmPassword) { RegistrationResult result = RegistrationResult.Success; if (password != confirmPassword) { result = RegistrationResult.PasswordsDoNotMatch; } Account emailAccount = await _accountService.GetByEmail(email); if (emailAccount != null) { result = RegistrationResult.EmailAlreadyExists; } Account usernameAccount = await _accountService.GetByUsername(username); if (usernameAccount != null) { result = RegistrationResult.UsernameAlreadyExists; } if (result == RegistrationResult.Success) { string hashedPassword = _passwordHasher.HashPassword(password); User user = new User() { Email = email, Username = username, PasswordHash = hashedPassword, DatedJoined = DateTime.Now }; Account account = new Account() { AccountHolder = user }; await _accountService.Create(account); } return(result); }
public async Task Register_WithNonExistingUsernameAndMatchingPasswords_ReturnsSucces() { RegistrationResult expected = RegistrationResult.Succes; RegistrationResult actual = await _authenticationSvc.Register(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()); // 断言 注册结果是否和异常相等 Assert.Equal(expected, actual); }
public async Task <IActionResult> RegistrationFormAction(RegistrationModel model) { if (ModelState.IsValid) { RegistrationResult result = await _registration.RegisterAsync(model.Login, model.Email, model.Password); if (result == RegistrationResult.Success) { await _logManager.WriteAsync(model.Login, $"New user '{model.Login}' was registered."); return(View("Login")); } else { return(View()); } } return(View("Registration")); ////////////////////////////// ///// OLD FORMS REGISTRATION ////////////////////////////// /* if (model.Password != model.ConfirmPassword) * { * ViewData["Error"] = "Password does not match the confirm password"; * return View("Registration", model); * } * * RegistrationResult result = await RegistrationProp.Register(model.Login, model.Email, model.Password); * * switch (result) * { * case RegistrationResult.LoginAlreadyExists: * { * ViewData["Error"] = "This login is already in use on Money"; * return View("Registration", model); * } * case RegistrationResult.EmailAlreadyExists: * { * ViewData["Error"] = "This email address is already in use on Money"; * return View("Registration", model); * } * case RegistrationResult.Success: * { * await LogWriterProp.Write(model.Login, $"New user '{model.Login}' was registered."); * return View("Login"); * } * default: * { * ViewData["Error"] = "Unknown error"; * return View("Registration", model); * } * }*/ }
public async Task Register_NotMatchingPassword() { string password = "******"; string confirmPassword = "******"; RegistrationResult expected = RegistrationResult.PasswordsNotMatch; RegistrationResult real = await _authentication.Register(It.IsAny <string>(), It.IsAny <string>(), password, confirmPassword); Assert.AreEqual(expected, real); }
public async Task Register_WithPasswordsNotMatching_ReturnsPasswordsDoNotMatch() { string password = "******"; string confirmPassword = "******"; RegistrationResult expected = RegistrationResult.PasswordsDoNotMatch; RegistrationResult actual = await _authenticationService.Register(It.IsAny <string>(), It.IsAny <string>(), password, confirmPassword); Assert.AreEqual(expected, actual); }
private void when_the_request_is_posted_to_the_service() { try { _response = (RegistrationResult)_sut.Post(_request); } catch (Exception e) { _testContext.Exception = e; } }
private void _tryLoginDriver(string loginName, BplRole role, RegistrationResult status, Action<LoginResult> onFinish) { if (status == RegistrationResult.Success && (role!=null && AuthServices.SetClientRole(loginName, role)) || role == null) { //user is ok here so, login status is Success and no new session _processLogin(loginName, LoginStatus.Success, onFinish); } else { Log.Warn("Driver registration: Unable to auto-login user {0} due to {1} upon registration", loginName, status != RegistrationResult.Success ? "invalid role ".Append(role.Description) : "status {0}".Substitute(status)); onFinish(new LoginResult { Status = LoginStatus.SessionBlocked }); } }