public async void GeneratePasswordsWithExpectedLengths() { var dict = new WordDictionary(); await dict.LoadAsync(); var randomPasswordGenerator = new RandomPasswordGenerator(dict); randomPasswordGenerator.MaximumLength = 0; randomPasswordGenerator.MinimumLength = 12; foreach (var password in GeneratePasswords(randomPasswordGenerator)) { Assert.True(password.Length >= 12); } randomPasswordGenerator.MinimumLength = 24; foreach (var password in GeneratePasswords(randomPasswordGenerator)) { Assert.True(password.Length >= 24); } randomPasswordGenerator.MinimumLength = 10; randomPasswordGenerator.MaximumLength = 15; foreach (var password in GeneratePasswords(randomPasswordGenerator)) { Assert.InRange(password.Length, 10, 15); } randomPasswordGenerator.MinimumLength = 20; randomPasswordGenerator.MaximumLength = 30; foreach (var password in GeneratePasswords(randomPasswordGenerator)) { Assert.InRange(password.Length, 20, 30); } }
/// <summary> /// Inserts a client into the databsae with a unique uesrname an and a randomly generated password /// </summary> /// <param name="clientToInsert"></param> /// <returns></returns> public static int InsertClient(Client clientToInsert) { string storedProcedureName = "usp_insertClient"; string emailPattern = "^(?:(?!@).)*"; Regex email = new Regex(emailPattern); Match result = email.Match(clientToInsert.Email); int autoIncrement = GetClientAutoIncrement(); MySqlParameter[] parameterList = new MySqlParameter[] { new MySqlParameter("clientNameIn", clientToInsert.ClientName), new MySqlParameter("addressIn", clientToInsert.Address), new MySqlParameter("suburbIn", clientToInsert.Suburb), new MySqlParameter("stateIn", clientToInsert.State), new MySqlParameter("contactPhoneIn", clientToInsert.ContactPhone), new MySqlParameter("emailIn", clientToInsert.Email), new MySqlParameter("usernameIn", clientToInsert.ClientName[0] + result.Value + autoIncrement), new MySqlParameter("passwordIn", RandomPasswordGenerator.GeneratePassword() + autoIncrement), new MySqlParameter("notesIn", clientToInsert.Notes) }; return(ExecuteNonQuery(storedProcedureName, parameterList)); }
public string ResetPasswordAsAdmin(string userName) { lock (_lock) { var path = UserPropertySheetPath; if (path != null) { var propertySheet = UserPropertySheet; var user = propertySheet.Rules.FirstOrDefault(rule => rule.Name == "user" && rule.Parameter == userName); if (user == null) { //user doesn't exists! return(null); } var password = RandomPasswordGenerator.GeneratePassword(DEFAULT_PASS_LENGTH); var propRule = user.GetPropertyRule("password"); var pv = propRule.GetPropertyValue(string.Empty); pv.Add(HashPassword(password)); propertySheet.Save(path); return(password); } } return(null); }
protected void btPwd_Click(object sender, EventArgs e) { PasswordGenerator pwdGen = new RandomPasswordGenerator(PasswordOptions.Numbers | PasswordOptions.LowercaseCharacters); string pawd = pwdGen.Generate(6).ToString(); tbPwd.Attributes.Add("value", pawd); tbPwdC.Attributes.Add("value", pawd); }
public async Task <bool> RecoverPasswordAsync(RecoveryInfo recInfo) { string pwd = RandomPasswordGenerator.GeneratePassword(8); string hashPwd = _userManager.PasswordHasher.HashPassword(pwd); var update = Builders <User> .Update.Set(u => u.PasswordHash, hashPwd); User user = await _users.FindOneAndUpdateAsync(u => u.Email == recInfo.EmailAddress, update); if (user != null) { await Task.Factory.StartNew(() => { SmtpClient client = new SmtpClient() { Port = 25, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Host = ConfigurationManager.AppSettings.Get("smtpHost") }; MailMessage mail = new MailMessage(ConfigurationManager.AppSettings.Get("fromEmail"), user.Email) { Subject = "MRP Password Recovery", Body = String.Format("your temporary password is: {0}", pwd) }; client.Send(mail); }); return(true); } else { return(false); } }
public LoginViewModel(LoginView viewLogin) { login = viewLogin; RandomPasswordGenerator.WriteRandomPasswordToFile(); admin = new vwAdmin(); manager = new vwManager(); }
private void ConfirmCommandExecute(object obj) { try { string password = (obj as PasswordBox).Password; string filePassword = RandomPasswordGenerator.ReadManagerPassword(); if (password.Equals(filePassword)) { AddManagerView managerView = new AddManagerView(); managerPasswordEnterView.Close(); registration.Close(); managerView.Show(); return; } else { if (retryCounter == 0) { MessageBox.Show("You have exeeded maximum number of tries.\nReturning to registration screen."); RegistrationView registrationView = new RegistrationView(retryCounter); managerPasswordEnterView.Close(); registration.Close(); registrationView.Show(); } else { MessageBox.Show($"Wrong password. Remaining number of tries: {--retryCounter}"); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public void InsertAuctionParticipants(string vAuctionRefNo) { SqlParameter[] sqlParams = new SqlParameter[1]; sqlParams[0] = new SqlParameter("@auctionRefNo", SqlDbType.Int); sqlParams[0].Value = Int32.Parse(vAuctionRefNo.Trim()); DataTable dtVendors = SqlHelper.ExecuteDataset(connstring, CommandType.StoredProcedure, "s3p_EBid_GetAuctionItemSupplierID", sqlParams).Tables[0]; // Modified By: GA S. 06292006 if (dtVendors.Rows.Count > 0) { foreach (DataRow row in dtVendors.Rows) { SqlParameter[] sqlParams2 = new SqlParameter[3]; sqlParams2[0] = new SqlParameter("@auctionRefNo", SqlDbType.Int); sqlParams2[0].Value = Int32.Parse(vAuctionRefNo.Trim()); sqlParams2[1] = new SqlParameter("@vendorId", SqlDbType.Int); sqlParams2[1].Value = Int32.Parse(row["VendorID"].ToString().Trim()); sqlParams2[2] = new SqlParameter("@ticket", SqlDbType.NVarChar); sqlParams2[2].Value = EncryptionHelper.Encrypt(RandomPasswordGenerator.GenerateRandomPassword()); SqlHelper.ExecuteNonQuery(connstring, CommandType.StoredProcedure, "s3p_EBid_InsertAuctionParticipants", sqlParams2); } } }
public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model) { var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result; var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadAccountImage(userInfo.Picture); user = new DbUser { FirstName = userInfo.GivenName, LastName = userInfo.FamilyName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; var invalid = new Dictionary <string, string> { { "googleInvalid", "Error google login." } }; if (!result.Succeeded) { return(BadRequest(invalid)); } } else { _fileService.UploadAccountImageIfNotExists(user, userInfo.Picture); } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok( new { token = _jWTTokenService.CreateToken(user), refToken = _jWTTokenService.CreateRefreshToken(user) })); }
public void TestPasswordLength() { settings.SetupGet(t => t.PasswordLength).Returns(12); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); Assert.AreEqual(12, g.Generate().Length); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { RandomPasswordGenerator pg = new RandomPasswordGenerator(); string password = pg.GeneratePassword(true, true, true, true, 16); AsymmetricKeys keys = Encryption.GenerateAsymmetricKeys(); var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, Address = "", PrivateKey = keys.PrivateKey.ToString(), PublicKey = keys.PublicKey.ToString() }; var result = await _userManager.CreateAsync(user, password); if (result.Succeeded) { if (user != null) { await _userManager.AddToRoleAsync(user, "STUDENT"); //[email protected] //Testing_123 SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Testing_123"); MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(Input.Email); msg.Subject = "New Account"; msg.Body = "New Account with Password: "******"New Account with Password: []!"; client.Send(msg); TempData["message"] = "Student Created Successfully"; return(Page()); } //await _emailSender.SendEmailAsync(Input.Email, "New Account", $"Account Created. Passowrd: ["+password+"]"); _logger.LogInformation("User created a new account with password."); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> NewPersonHadBrew() { var localizationString = HttpContext.Request.GetTypedHeaders() .AcceptLanguage.OrderByDescending(x => x.Quality ?? 0.1).FirstOrDefault()?.Value.ToString() ?? "en-GB"; var user = await _dataStore.CreateNewUserAsync(localizationString, RandomPasswordGenerator.GeneratePassword(16)); return(Ok(user)); }
public string CreateUser(string userName) { var password = RandomPasswordGenerator.GeneratePassword(DEFAULT_PASS_LENGTH); if (CreateUserWithPassword(userName, password)) { return(password); } return(null); }
/// <summary> /// Sign up an user account. /// </summary> /// <param name="email"> /// Email /// </param> /// <param name="mobile"> /// Mobile /// </param> /// <param name="password"></param> /// <returns> /// Logged In user's detail /// </returns> public static async Task<User> SignupUser(string email, string mobile, string password) { if (string.IsNullOrEmpty(Config.SignUpId) || string.IsNullOrEmpty(Config.SignUpSecret)) { throw new ServiceException("Invalid Configuration: Client ID & Client Secret"); } if (string.IsNullOrEmpty(email)) { throw new ArgumentException("Invalid parameter", "email"); } if (string.IsNullOrEmpty(mobile)) { throw new ArgumentException("Invalid parameter", "mobile"); } if (string.IsNullOrEmpty(password)) { throw new ArgumentException("Invalid parameter", "password"); } await GetSignupToken(); var objectToPost = new User { Email = email, Mobile = mobile }; user = objectToPost; var rest = new RestWrapper(); var result = await rest.Post<User>(Service.Signup, AuthTokenType.SignUp, objectToPost); if (!(result is Error)) { user.UserName = ((User)result).UserName; if (!string.IsNullOrEmpty(user.UserName)) { var randomPasswordGenerator = new RandomPasswordGenerator(); user.Password = randomPasswordGenerator.Generate(user.Email, user.Mobile); var success = await SigninUser(user.UserName, user.Password); if (success) { success = await UpdatePassword(user.Password, password); if (success) { user.Password = password; return await GetBalance(); } } } } else { Utility.ParseAndThrowError((result as Error).Response); } return new User(); }
public void Generate_CreatesRandomPassword() { // Arrange var randomPasswordGenerator = new RandomPasswordGenerator(); // Act string password1 = randomPasswordGenerator.Generate(); string password2 = randomPasswordGenerator.Generate(); // Assert Assert.NotEqual(password1, password2); }
public void TestPasswordUseCustomCharSet() { settings.SetupGet(t => t.PasswordCharacters).Returns("a"); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); string password = g.Generate(); foreach (char c in password) { Assert.AreEqual('a', c); } }
public void TestPasswordUseNumeric() { settings.SetupGet(t => t.UseNumeric).Returns(true); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); string password = g.Generate(); foreach (char c in password) { Assert.IsTrue(char.IsNumber(c)); } }
public void TestPasswordUseSymbol() { settings.SetupGet(t => t.UseSymbol).Returns(true); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); string password = g.Generate(); foreach (char c in password) { Assert.IsFalse(char.IsLetterOrDigit(c)); } }
protected void lnkOK_Click(object sender, EventArgs e) { SupplierTransaction supp = new SupplierTransaction(); OtherTransaction oth = new OtherTransaction(); if (!(supp.VendorExists(oth.Replace(txtVendorName.Text.Trim())))) { string vUserName = tbUserName.Text.Replace(" ", ""); //if (vUserName.Length > 8) // vUserName = vUserName.Substring(0, 8).ToUpper(); //else // vUserName = vUserName.ToUpper(); if (supp.CheckUser(tbUserName.Text.Trim())) { string randomPwd = RandomPasswordGenerator.GenerateRandomPassword(); int vVendorId = supp.InsertUser(connstring, vUserName, EncryptionHelper.Encrypt(randomPwd), ((int)Constant.USERTYPE.VENDOR).ToString().Trim()); ViewState["sUserID"] = vVendorId; web_usercontrol_mobileno uctrlMobileNo1 = (web_usercontrol_mobileno)FindControl("uctrlMobileNo"); supp.InsertOneTimeSupplier(vVendorId.ToString().Trim(), txtVendorName.Text.Trim(), ((int)Constant.SUPPLIERTYPE.OneTimeSupplier).ToString().Trim(), txtEmailAddress.Text.Trim(), txtAddress1.Text.Trim(), txtAddress2.Text.Trim(), txtContactPerson.Text.Trim(), txtTelephoneNumber.Text.Trim(), uctrlMobileNo1.MobileNumber); supp.SaveCategoriesAndSubCategories(vVendorId, ViewState[Constant.QS_CATEGORYID].ToString(), ViewState[Constant.QS_SUBCATEGORYID].ToString()); string emailOk = ""; if (SendEmail()) { emailOk = " and notified"; } lblMessage.Text = txtVendorName.Text.Trim() + " has been successfully added" + emailOk + "."; lnkClose.Attributes.Add("onclick", "AddSuppliersB('" + vVendorId + "', '" + txtVendorName.Text.Trim() + "');"); DisableFields(); } else { lblMessage.Text = tbUserName.Text.Trim() + " already exists."; } } else { lblMessage.Text = txtVendorName.Text.Trim() + " already exists in the vendor list."; } }
public PasswordGeneratorViewModel(IResolver resolver) { this.resolver = resolver; randomGenerator = new RandomPasswordGenerator(); scanner = new PasswordScanner(); inAppAnalyitics = resolver.GetInstanceOf <IInAppAnalytics>(); CopyCommand = new RelayCommand(CopyButtonClick); CreatePasswordCommand = new RelayCommand(CreatePasswordClick); ShowHistoryCommand = new RelayCommand(ShowHistoryClick); HideHistoryCommand = new RelayCommand(HideHistoryClick); ShowHistoryVisibility = true; HideHistoryVisibility = false; AllGeneratedPasswords = new ObservableCollection <string>(); }
private int SaveBOC() { SqlConnection sqlConnect = new SqlConnection(connstring); SqlTransaction sqlTransact = null; int value = 0; try { sqlConnect.Open(); sqlTransact = sqlConnect.BeginTransaction(); SqlParameter[] sqlParams = new SqlParameter[9]; sqlParams[0] = new SqlParameter("@UserName", SqlDbType.VarChar); sqlParams[1] = new SqlParameter("@Password", SqlDbType.VarChar); sqlParams[2] = new SqlParameter("@FirstName", SqlDbType.VarChar); sqlParams[3] = new SqlParameter("@LastName", SqlDbType.VarChar); sqlParams[4] = new SqlParameter("@MidName", SqlDbType.VarChar); sqlParams[5] = new SqlParameter("@CommitteeId", SqlDbType.Int); sqlParams[6] = new SqlParameter("@EmailAdd", SqlDbType.VarChar); sqlParams[7] = new SqlParameter("@TempPwd", SqlDbType.VarChar); sqlParams[8] = new SqlParameter("@Clientid", SqlDbType.Int); string randomPwd = RandomPasswordGenerator.GenerateRandomPassword(); sqlParams[0].Value = tbUserName.Text.Trim(); sqlParams[1].Value = EncryptionHelper.Encrypt(randomPwd); sqlParams[2].Value = tbFirstName.Text.Trim(); sqlParams[3].Value = tbLastName.Text.Trim(); sqlParams[4].Value = tbMidInitial.Text.Trim(); sqlParams[5].Value = Int32.Parse(rbCommittee.SelectedValue.Trim()); sqlParams[6].Value = tbEmail.Text.Trim(); sqlParams[7].Value = EncryptionHelper.Encrypt(randomPwd); sqlParams[8].Value = Int32.Parse(HttpContext.Current.Session["clientid"].ToString()); value = Convert.ToInt32(SqlHelper.ExecuteScalar(sqlTransact, "sp_AddNewBOC", sqlParams)); sqlTransact.Commit(); } catch { sqlTransact.Rollback(); value = 0; } finally { sqlConnect.Close(); } return(value); }
public void TestPasswordUseUpperAndLower() { settings.SetupGet(t => t.UseUpper).Returns(true); settings.SetupGet(t => t.UseLower).Returns(true); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); string password = g.Generate(); foreach (char c in password) { Assert.IsTrue(char.IsUpper(c) || char.IsLower(c)); } }
public NovellOrganizationContactPerson(OrganizationContactPersonView person) { if (person.FirstName != null && person.LastName != null) { FirstName = TransliterateName(person.FirstName); Surname = TransliterateName(person.LastName); Email = person.Email; Login = ConstructLogin(TransliterateName(person.FirstName), TransliterateName(person.LastName)); Password = RandomPasswordGenerator.GeneratePassword(8); } else { return; } }
public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model) { var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result; var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadFacebookImage(userInfo.Picture); user = new DbUser { FirstName = userInfo.GivenName, LastName = userInfo.FamilyName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; await _signInManager.SignInAsync(user, isPersistent : false); if (!result.Succeeded) { return(BadRequest(new { invalid = "We can't create user" })); } } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok(_jWTTokenService.CreateToken(_configuration, user, _userManager))); }
private int SavePurchasing() { string query; SqlCommand cmd; SqlConnection conn; SqlTransaction sqlTransact = null; int value = 0; string randomPwd = RandomPasswordGenerator.GenerateRandomPassword(); try { query = "sp_AddNewPurchasing"; //##storedProcedure using (conn = new SqlConnection(connstring)) { using (cmd = new SqlCommand(query, conn)) { cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure cmd.Parameters.AddWithValue("@Username", tbUserName.Text.Trim()); cmd.Parameters.AddWithValue("@Password", EncryptionHelper.Encrypt(randomPwd)); cmd.Parameters.AddWithValue("@FirstName", tbFirstName.Text.Trim()); cmd.Parameters.AddWithValue("@LastName", tbLastName.Text.Trim()); cmd.Parameters.AddWithValue("@MidName", tbMidInitial.Text.Trim()); cmd.Parameters.AddWithValue("@DeptId", Int32.Parse(rbDepartments.SelectedValue.Trim())); cmd.Parameters.AddWithValue("@EmailAdd", tbEmail.Text.Trim()); cmd.Parameters.AddWithValue("@TempPwd", EncryptionHelper.Encrypt(randomPwd)); cmd.Parameters.AddWithValue("@ClientId", Int32.Parse(HttpContext.Current.Session["clientid"].ToString())); conn.Open(); sqlTransact = conn.BeginTransaction(); sqlTransact.Commit(); value = Convert.ToInt32(cmd.ExecuteScalar().ToString()); } } } catch (Exception ex) { //Response.Write(ex.Message); sqlTransact.Rollback(); value = 0; LogHelper.EventLogHelper.Log("Admin > Add User : " + ex.Message, EventLogEntryType.Error); } finally { //conn.Close(); } return(value); }
/// <summary> /// Handle method for create profile. /// </summary> /// <param name="createCommand"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <APIResponse> Handle(CreateUserProfileCommand createCommand, CancellationToken cancellationToken) { try { var profileRequest = mapper.Map <Core.Entity.Profile>(createCommand.Request); profileRequest.Password = RandomPasswordGenerator.GeneratePassword(true, true, true, true, 8); profileRequest.UserName = profileRequest.Email; profileRequest.Profilepermission?.ToList().ForEach(x => { x.CreatedBy = profileRequest.CreatedBy; x.RoleId = profileRequest.Role; }); profileRequest.Profileapprovalstatus?.ToList().ForEach(x => { x.Date = DateTime.UtcNow; x.CreatedBy = profileRequest.CreatedBy; x.CreatedAt = DateTime.UtcNow; }); profileRequest.Profilestatuses?.ToList().ForEach(x => { x.Date = DateTime.UtcNow; x.CreatedBy = profileRequest.CreatedBy; x.CreatedAt = DateTime.UtcNow; }); profileRequest.Companydistricts?.ToList().ForEach(x => { x.CreatedBy = profileRequest.CreatedBy; }); repository.ProfileRepository.CreateUserProfile(profileRequest); await repository.SaveAsync(); return(new APIResponse(new UserIdDetails { ProfileId = profileRequest.Id, UserId = profileRequest.UserId }, HttpStatusCode.Created)); } catch (Exception ex) { logger.Error(ex, "Exception in method 'CreateProfileHandler()'"); var exMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; return(new APIResponse(exMessage, HttpStatusCode.InternalServerError)); } }
public static async Task<bool> IsCitrusMemeber(string email, string mobile) { var newUser = await BindUser(email, mobile); var randomPasswordGenerator = new RandomPasswordGenerator(); newUser.Password = randomPasswordGenerator.Generate(newUser.Email, newUser.Mobile); var request = new SigninRequest { User = new User { UserName = newUser.UserName, Password = newUser.Password } }; var rest = new RestWrapper(); var result = await rest.Post<OAuthToken>(Service.Signin, AuthTokenType.None, request); if (!(result is Error)) { return false; } return true; }
public void TestPasswordUseReadibilitySeparator() { settings.SetupGet(t => t.UseReadibilitySeparator).Returns(true); settings.SetupGet(t => t.ReadabilitySeparatorInterval).Returns(3); settings.SetupGet(t => t.ReadabilitySeparator).Returns("_"); settings.SetupGet(t => t.PasswordLength).Returns(12); RandomPasswordGenerator g = new RandomPasswordGenerator(settings.Object, this.csp); string password = g.Generate(); Assert.AreEqual(15, password.Length); Assert.AreEqual(3, password.Where(t => t == '_').Count()); Assert.AreEqual('_', password[3]); Assert.AreEqual('_', password[7]); Assert.AreEqual('_', password[11]); }
public static string CheckUserNameAndEmail(string UserName, string EmailID) { try { DataTable DS = CRBusinessLogicLayer.ForgorPasswordSendCode(UserName, EmailID); if (DS.Rows[0]["USERID"].ToString() != "") { Login Method = new Login(); VerificationCode = RandomPasswordGenerator.Generate(); Method.SendMail(VerificationCode, EmailID); return("Please check above Registered Email for verification code"); } return("Please enter valid User Name and Email Id"); } catch (Exception ex) { return(ex.Message); } }
public async Task <IActionResult> AddUser([FromBody] UserToCreateDto userToCreteDto) { if (!ModelState.IsValid) { return(BadRequest()); } using (var session = _store.OpenAsyncSession()) { var user = await session.Query <User>() .Where(u => u.Email.Equals(userToCreteDto.Email, StringComparison.OrdinalIgnoreCase)) .FirstOrDefaultAsync(); if (user != null) { return(BadRequest(new { error = "The email is already in use." })); } var dbUser = _mapper.Map <User>(userToCreteDto); dbUser.Color = await GetColor(); var temporaryPassword = RandomPasswordGenerator.GeneratePassword(15); var salt = Convert.ToBase64String(PasswordHasher.GenerateSalt()); var hashedPassword = PasswordHasher.HashPassword(temporaryPassword, Convert.FromBase64String(salt)); dbUser.Salt = salt; dbUser.TemporaryPassword = hashedPassword; await session.StoreAsync(dbUser); await session.SaveChangesAsync(); string username = FormatUsername(dbUser.Email); string message = $"<b>Dear {dbUser.FirstName}</b></br><p>You're receiving this message because your Scheduler Account has been created.</p><p>Your <b>username</b>: {username}</p><p>Your <b>first-time login password</b>: {temporaryPassword}</p><p>Follow the link below to change your password and log in to Scheduler application:</p><p><a href={_dataServiceConfiguration.ClientUrl}>Login</a></p><p>Best</p><p>Scheduler Team</p>"; _schedulerMailer.SendMail("Scheduler-Notifications", dbUser.Email, "Scheduler Account", message, _dataServiceConfiguration.MailBoxPassword); var userToReturn = _mapper.Map <PostCreationUserToReturnDto>(dbUser); return(CreatedAtRoute("GetUser", new { userId = dbUser.Id }, userToReturn)); } }
/// <summary> /// Inserts specified coordinator into the database, does not require ID field /// </summary> /// <param name="coordinatorToInsert"></param> /// <returns></returns> public static int InsertCoordinator(Coordinator coordinatorToInsert) { string storedProcedureName = "usp_insertCoordinator"; int autoIncrement = GetCoordinatorAutoIncrement(); MySqlParameter[] parameterList = new MySqlParameter[] { new MySqlParameter("firstNameIn", coordinatorToInsert.FirstName), new MySqlParameter("lastNameIn", coordinatorToInsert.LastName), new MySqlParameter("addressIn", coordinatorToInsert.Address), new MySqlParameter("stateIn", coordinatorToInsert.State), new MySqlParameter("suburbIn", coordinatorToInsert.Suburb), new MySqlParameter("mobileIn", coordinatorToInsert.Mobile), new MySqlParameter("emailIn", coordinatorToInsert.Email), new MySqlParameter("usernameIn", coordinatorToInsert.FirstName[0] + coordinatorToInsert.LastName + autoIncrement), new MySqlParameter("passwordIn", RandomPasswordGenerator.GeneratePassword() + autoIncrement) }; return(ExecuteNonQuery(storedProcedureName, parameterList)); }