public DataSet USP_UpdateRegUserDetails(UserRegistrationInfo objUserregisInfo) { bool returnValue = false; string spNameString = string.Empty; DataSet dsUserInfo = new DataSet(); Database dbDatabase = DatabaseFactory.CreateDatabase(Global.INSTANCE_NAME); spNameString = "[USP_MobileUpdateRegUserDetails]"; DbCommand dbCommand = null; try { dbCommand = dbDatabase.GetStoredProcCommand(spNameString); dbDatabase.AddInParameter(dbCommand, "@UId", System.Data.DbType.Int32, objUserregisInfo.UId); dbDatabase.AddInParameter(dbCommand, "@Name", System.Data.DbType.String, objUserregisInfo.Name); dbDatabase.AddInParameter(dbCommand, "@PhoneNumber", System.Data.DbType.String, objUserregisInfo.PhoneNumber); dbDatabase.AddInParameter(dbCommand, "@StateID", System.Data.DbType.Int32, objUserregisInfo.StateID); dbDatabase.AddInParameter(dbCommand, "@City", System.Data.DbType.String, objUserregisInfo.City); dbDatabase.AddInParameter(dbCommand, "@Address", System.Data.DbType.String, objUserregisInfo.Address); dbDatabase.AddInParameter(dbCommand, "@Zip", System.Data.DbType.String, objUserregisInfo.Zip); dbDatabase.AddInParameter(dbCommand, "@BusinessName", System.Data.DbType.String, objUserregisInfo.BusinessName); dbDatabase.AddInParameter(dbCommand, "@AltEmail", System.Data.DbType.String, objUserregisInfo.AltEmail); dbDatabase.AddInParameter(dbCommand, "@AltPhone", System.Data.DbType.String, objUserregisInfo.AltPhone); dsUserInfo = dbDatabase.ExecuteDataSet(dbCommand); //blnSuccess = objUserLog.SaveUserLog(UserLogInfo, ref lngReturn, ""); return(dsUserInfo); } catch (Exception ex) { throw ex; } }
private (UserCredentials validCredentials, UserCredentials invalidCredentials, UserRegistrationInfo registrationInfo) GetTestUserData() { var correctUsername = "******"; var correctPassword = "******"; var incorrectPassword = "******"; var validCredentials = new UserCredentials { Username = correctUsername, Password = correctPassword, }; var invalidCredentials = new UserCredentials { Username = correctUsername, Password = incorrectPassword, }; var registrationInfo = new UserRegistrationInfo { Username = correctUsername, Password = correctPassword, ConfirmedPassword = correctPassword, Email = "*****@*****.**" }; return(validCredentials, invalidCredentials, registrationInfo); }
private void ValidateUser(UserRegistrationInfo userToValidate) { if (!FieldsAreFilled(userToValidate)) { throw new AppException("Недостаточно информации про пользователя"); } if (!LengthIsCorrect(userToValidate.Login, MinimumLoginLength, MaximumLoginLength)) { throw new AppException($"Длина логина не правильная, должна быть от {MinimumLoginLength}" + $" и до {MaximumLoginLength}"); } if (!LengthIsCorrect(userToValidate.Password, MinimumPassLength, MaximumPassLength)) { throw new AppException($"Длина пароля не правильная, должна быть от {MinimumPassLength}" + $" и до {MaximumPassLength}"); } if (!LengthIsCorrect(userToValidate.EmailAdress, MinimumEmailLength, MaximumEmailLength)) { throw new AppException($"Длина почты не правильная, должна быть от {MinimumEmailLength}" + $" и до {MaximumEmailLength}"); } if (!IsEmailValid(userToValidate.EmailAdress)) { throw new AppException($"Почтовый адрес указан в неправильном формате"); } }
//UnComment if you want to debug the Custom Authentication Bug //protected override IAuthentication CreateClientInternal(Binding binding, // EndpointAddress endpointAddress, // WulkaClientCredentialsBase credentials) //{ // return GetInstance(binding, endpointAddress, credentials); //} /// <summary> /// Registers the new user async. /// </summary> /// <param name="item">The item.</param> /// <param name="act">The act.</param> public void RegisterNewUserAsync(UserRegistrationInfo item, Action <UserRegistrationInfo> act = null) { var res = (UserRegistrationInfo)null; using (var wrk = new BackgroundWorker()) { wrk.DoWork += (s, e) => { try { res = RegisterNewUser(item); } catch (Exception ex) { wrk.Dispose(); throw ex; } }; wrk.RunWorkerCompleted += (sender, args) => { wrk.Dispose(); if (act != null) { act(res); } }; wrk.RunWorkerAsync(); } }
private void UserRegistrate(string name, string surname, string phoneNumber) { UserRegistrationInfo newUser = new UserRegistrationInfo() { Name = name, Surname = surname, PhoneNumber = phoneNumber, }; try { usersService.RegisterNewUser(newUser); int ID = usersService.GetUserId(newUser); int stockID = r.Next(1, 10); int stockAmount = r.Next(1, 5); BalanceInfo balance = new BalanceInfo() { UserID = ID, StockID = stockID, StockAmount = stockAmount, Balance = stocksService.GetStock(stockID).Price *stockAmount }; balancesService.CreateBalance(balance); Logger.Log.Info($"User registration success. New user is {name} {surname} ID: {ID}"); Console.WriteLine("Registration successful!"); } catch (ArgumentException e) { Logger.Log.Error($"Registration failed. Message: {e.Message}"); } }
public async Task <IActionResult> Register([FromBody] UserRegistrationInfo userDto, CancellationToken cancellationToken) { try { var user = userService.CreateUser(userDto); await userService.ValidateUserAsync(user); await userService.AddUserAsync(user, userDto.Password, cancellationToken); var resultUser = new View.UserRegistredInfo { Id = user.Id, Username = user.Login }; MailingService emailService = new MailingService(); await emailService.SendEmailAsync(userDto.EmailAdress, "Успешная регистрация", "Поздравляем, " + user.Login + ", вы зарегистрировались и можете зайти в профиль на https://pr42.ru/login ! \n P.S. Подтверждения почты пока нет, но скоро будет! \n С уважением, администрация pr42.ru"); Console.WriteLine("Email to {0} was sent", userDto.EmailAdress); return(Ok(resultUser)); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); } }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await _signInManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return(View("customers/login", WorkContext)); } User user = null; // Sign in the user with this external login provider if the user already has a login. var externalLoginResult = await _signInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent : false, bypassTwoFactor : true); if (!externalLoginResult.Succeeded) { //TODO: Locked out not work. Need to add some API methods to support lockout data. if (externalLoginResult.IsLockedOut) { return(View("lockedout", WorkContext)); } //Register new user user = new User() { Email = loginInfo.Principal.FindFirstValue(ClaimTypes.Email), UserName = $"{loginInfo.LoginProvider}--{loginInfo.ProviderKey}", StoreId = WorkContext.CurrentStore.Id, }; user.ExternalLogins.Add(new ExternalUserLoginInfo { ProviderKey = loginInfo.ProviderKey, LoginProvider = loginInfo.LoginProvider }); var identityResult = await _signInManager.UserManager.CreateAsync(user); if (!identityResult.Succeeded) { foreach (var error in identityResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(View("customers/login", WorkContext)); } } user = await _signInManager.UserManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); if (!externalLoginResult.Succeeded) { await _signInManager.SignInAsync(user, isPersistent : false); var registrationInfo = new UserRegistrationInfo { FirstName = loginInfo.Principal.FindFirstValue(ClaimTypes.GivenName), LastName = loginInfo.Principal.FindFirstValue(ClaimTypes.Surname), UserName = user.UserName, Email = user.Email }; await _publisher.Publish(new UserRegisteredEvent(WorkContext, user, registrationInfo)); } await _publisher.Publish(new UserLoginEvent(WorkContext, user)); return(StoreFrontRedirect(returnUrl)); }
public void SaveRegistrationDate(UserRegistrationInfo userRegInfo) { XmlDocument xmlEmloyeeDoc = new XmlDocument(); xmlEmloyeeDoc.Load(_dbPath); XmlElement parentElement = xmlEmloyeeDoc.CreateElement("User"); XmlElement userId = xmlEmloyeeDoc.CreateElement("UserId"); userId.InnerText = userRegInfo.UserId.ToString(); XmlElement login = xmlEmloyeeDoc.CreateElement("Login"); login.InnerText = userRegInfo.Login; XmlElement password = xmlEmloyeeDoc.CreateElement("Password"); password.InnerText = userRegInfo.Password; XmlElement hasAdminPermission = xmlEmloyeeDoc.CreateElement("HasAdminPermission"); hasAdminPermission.InnerText = "false"; parentElement.AppendChild(userId); parentElement.AppendChild(login); parentElement.AppendChild(password); parentElement.AppendChild(hasAdminPermission); xmlEmloyeeDoc.DocumentElement.AppendChild(parentElement); xmlEmloyeeDoc.Save(_dbPath); }
public bool ContainsInfo(UserRegistrationInfo userInfo) { return(this.dbContext.Users.Any(f => f.Name == userInfo.Name && f.Surname == userInfo.Surname && f.PhoneNumber == userInfo.PhoneNumber)); }
/// <summary> /// Registers the new user. /// </summary> /// <param name="item">The item.</param> /// <returns>NewUserRegistrationInfo.</returns> public UserRegistrationInfo RegisterNewUser(UserRegistrationInfo item) { _logger.Info("Registering user {0}", item.UserName); try { var ait = AuthenticationProvider .Accounts. GetAccountForUser(item.UserName); if (ait != null) { return(ait.ToUserRegistrationInfo()); } ait = new Account { Id = item.Id, FirstName = item.FirstName, LastName = item.LastName, Email = item.Email, AuthModeId = item.AuthMode, Pwd = item.Password, Username = item.Email }; ait = AuthenticationProvider .Accounts .SaveAccountItem(ait); SendConfirmationEmail(ait); return(ait.ToUserRegistrationInfo()); } catch (Exception ex) { _logger.Error(ex.GetCombinedMessages()); item.AddError(ex.Message); return(item); } }
public HttpResponseMessage Auth([FromBody] UserRegistrationInfo userRegisterInfo) { if (!ModelState.IsValid) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } try { var session = authenticator.Authenticate(userRegisterInfo.Login, userRegisterInfo.Password); var cookie = new CookieHeaderValue("SessionId", session.SessionId.ToString()); cookie.Expires = DateTimeOffset.Now.AddMonths(1); cookie.Domain = Request.RequestUri.Host; cookie.Path = "/"; var response = Request.CreateResponse <SessionState>(HttpStatusCode.OK, session); response.Headers.AddCookies(new CookieHeaderValue[] { cookie }); return(response); } catch (UserNotFoundException) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.Conflict)); } }
public int GetUserId(UserRegistrationInfo userInfo) { if (!this.userTableRepository.ContainsInfo(userInfo)) { throw new ArgumentException("Can't find user with this Info. May it hasn't been registered"); } return(this.userTableRepository.GetId(userInfo)); }
private bool InputRegistrationDataValid(UserRegistrationInfo user) { return(Utils.IsEmailValid(user.Email) && !string.IsNullOrEmpty(user.Password) && !string.IsNullOrEmpty(user.FirstName) && !string.IsNullOrEmpty(user.LastName) && !string.IsNullOrEmpty(user.UserName)); }
public async Task Token1([FromBody] UserRegistrationInfo registrationInfo, CancellationToken cancellationToken) { var username = registrationInfo.Login; var password = registrationInfo.Password; var creationInfo = new UserCreationInfo(username, this.HashPassword(password)); var getUser = this.userRepository.Get(username); if (getUser != null) { Response.StatusCode = 400; await Response.WriteAsync("user already exists"); throw new UserDuplicationException(registrationInfo.Login); } try { this.userRepository.Create(creationInfo); } catch (UserNotFoundException) { throw new AuthenticationException(); } var identity = this.GetIdentity(username, password); if (identity == null) { this.Response.StatusCode = 400; await this.Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; // сериализация ответа this.Response.ContentType = "application/json"; await this.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); }
public int GetId(UserRegistrationInfo userInfo) { var entity = this.dbContext.Users.First(f => f.Name == userInfo.Name && f.Surname == userInfo.Surname && f.PhoneNumber == userInfo.PhoneNumber); return(entity.ID); }
/// <summary> /// Registers the new user completed. /// </summary> /// <param name="item">The item.</param> private void RegisterNewUserCompleted(UserRegistrationInfo item) { PleaseWaitDialog.Close(); DataContext = item; DialogResult = !item.HasErrors; if (Convert.ToBoolean(DialogResult)) { Close(); } }
public IActionResult Register([FromBody] UserRegistrationInfo user) { Result result = authorizationService.Register(user); if (result.ResultOk) { return(Ok(result)); } return(BadRequest(result)); }
public static bool IsRegFieldsCompleted(UserRegistrationInfo userRegInfo) { userRegInfo.Login = userRegInfo.Login.Trim(); userRegInfo.Password = userRegInfo.Password.Trim(); userRegInfo.ConfirmPassword = userRegInfo.ConfirmPassword.Trim(); return(!(string.IsNullOrEmpty(userRegInfo.Login)) && !(string.IsNullOrEmpty(userRegInfo.Password)) && !(string.IsNullOrEmpty(userRegInfo.ConfirmPassword))); }
public UserAddedMessage AddUserAddedMessage(UserRegistrationInfo user) { var userAddedMessage = new UserAddedMessage() { UserId = user.EmailID, UserName = user.Name, DateOfBirth = user.DateOfBirth }; _userMessageStream.OnNext(userAddedMessage); return(userAddedMessage); }
public virtual UserRegistrationInfo ToUserRegistrationInfo(Register registerForm) { var result = new UserRegistrationInfo { Email = registerForm.Email, FirstName = registerForm.FirstName, LastName = registerForm.LastName, Password = registerForm.Password, UserName = registerForm.UserName }; return(result); }
public bool AddUser(UserRegistrationInfo userInfo) { if (IsUserExists(userInfo.EmailID)) { return(false); } var userDetails = userInfo.MapToEntity(); _context.Users.Add(userDetails.Item1); _context.UserCredentials.Add(userDetails.Item2); _context.SaveChanges(); return(true); }
public IActionResult AddUser([FromBody] UserRegistrationInfo userRegistrationInfo) { var registrationInfo = userRegistrationInfo.ToEntity(); var isUserRegistered = _dataStore.TryRegisteringUser(registrationInfo.Item1, registrationInfo.Item2); if (isUserRegistered) { _dataStore.SaveChanges(); return(StatusCode(201)); } return(BadRequest()); }
/// <summary> /// Registers the new user. /// </summary> /// <param name="item">The item.</param> /// <returns>NewUserRegistrationViewItem.</returns> public UserRegistrationInfo RegisterNewUser(UserRegistrationInfo item) { var clt = CreateClient(); try { return(clt.RegisterNewUser(item)); } finally { CloseClient(clt); } }
public User CreateUser(UserRegistrationInfo userToCreate) { ValidateUser(userToCreate); var user = new User { EmailAdress = userToCreate.EmailAdress, Login = userToCreate.Login, RegistrationDate = DateTime.Now }; return(user); }
public async Task <string> RegisterUser([FromBody] UserRegistrationInfo userInfo) { var result = await _userManager.CreateAsync( new AppUser { UserName = userInfo.Username, Email = userInfo.Email }, userInfo.Password ); if (result.Succeeded) { return(userInfo.Username); } throw new UserIdentityException(result.Errors); }
public bool Registrate(UserRegistrationInfo userInfo) { bool isValid = ValidationHelper.IsRegFieldsCompleted(userInfo) && ValidationHelper.IsPasswordSame(userInfo.Password, userInfo.ConfirmPassword) && !_authenticationRepository.LoginExists(userInfo.Login); if (isValid) { userInfo.UserId = GetUnicId.GetNewGuid(); _authenticationRepository.SaveRegistrationDate(userInfo); } return(isValid); }
private void btnRegister_Click(object sender, EventArgs e) { UserRegistrationInfo userInfo = Maper.MapingRegistrationModel(textBoxLogin.Text, textBoxPass.Text, textBoxConfPass.Text); if (_regController.Registrate(userInfo)) { //TODO Add message routing MessageBox.Show("Successfully completed."); } else { MessageBox.Show("Invalid registration!!!"); } }
private bool FieldsAreFilled(UserRegistrationInfo userToCheck) { var type = userToCheck.GetType(); foreach (var property in type.GetProperties()) { if (property.GetValue(userToCheck) == null) { return(false); } } return(true); }
/// <summary> /// Registers the new user completed. /// </summary> /// <param name="obj">The object.</param> private void RegisterNewUserCompleted(UserRegistrationInfo obj) { Registering = false; Feedback = !obj.HasErrors ? String.Format("Your registration is received.\nA confirmation email has been sent to '{0}'.", UserInfo.Email) : obj.Error; Application.Current.DoEvents(); Thread.Sleep(3000); Messenger.Default.Send(new NavigateMvvmMessage() { Header = LoginView.HEADER, ViewName = LoginView.ID }); }
public static UserRegistrationInfo ToRegInfo(this WsConnection con) { var res = new UserRegistrationInfo() { UserID = con.Client.SubjectID, DeviceType = con.Client.DeviceType, Payload = new UserRegistrationInfoPayload() { ServerInstanceID = con.Server.ServerInstanceID, PingTimeUtc = DateTime.UtcNow } }; return(res); }