예제 #1
0
        public async Task <BaseResponse> SaveAsync(RegisterUserRequest registerUser)
        {
            var appUser = await this.userManager.FindByEmailAsync(registerUser.Email);

            if (appUser != null)
            {
                return(new ErrorResponse($"User with email '{registerUser.Email}' already exists", 409));
            }

            var password = RandomPassword.Generate(8);

            appUser = new ApplicationUser
            {
                UserName       = registerUser.Email,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

            var identityResult = await this.userManager.CreateAsync(appUser, password);

            if (identityResult.Succeeded)
            {
                await this.userManager.AddToRoleAsync(appUser, registerUser.RoleCode.ToString("G"));

                await this.emailSender.SendEmailAsync(appUser.Email, "Welcome", $"You have the {registerUser.RoleCode.ToString("G")} role and your password is {password}.");

                return(new SuccessResponse($"User with email '{registerUser.Email}' was created", 201));
            }
            else
            {
                return(new ErrorResponse($"User with email '{registerUser.Email}' could not be created", 400, identityResult.Errors.Select(e => new Error(e.Code, e.Description))));
            }
        }
예제 #2
0
        public ActionResult PostUser(User user)
        {
            _logger.LogInformation("POST: api/User/PostUser  Invoke");
            user.Password = RandomPassword.RandomGeneratePassword();
            user.Password = EncryptionDecryptionHelper.EncryptString(user.Password);
            ResponseModel responseModel = new ResponseModel();
            var           result        = _userService.PostUser(user, _hostingEnvironment.ContentRootPath.ToString(), folderLocation);

            if (result == null)
            {
                responseModel.IsSuccess = false;
                responseModel.Message   = "Record Not Created";
            }
            else
            {
                EmailServiceHelper emailService = new EmailServiceHelper(_config, _email);
                //Azure SendGrid Email Grid
                if (_isSendMailBySendGrid)
                {
                    emailService.AdminRegMessage(result).Wait();
                }

                ////local Send Email Grid
                //if (!_isSendMailBySendGrid)
                //    emailService.localUserRegMessage(result);

                responseModel.Result = result;
            }

            return(Ok(responseModel));
        }
예제 #3
0
        public ActionResult Create([Bind(Include = "username,email,newpass,confpass")] RegisterUser regU)
        {
            if (ModelState.IsValid)
            {
                var crypto = new SimpleCrypto.PBKDF2();
                regU.newpass = crypto.Compute(regU.newpass);
                User user = new User();

                user.username  = regU.username;
                user.password  = regU.newpass;
                user.salt      = crypto.Salt;
                user.email     = regU.email;
                user.activated = false;

                string actKey = "/Activ?kstr=" + RandomPassword.Generate(44, PasswordGroup.Uppercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
                user.actString = actKey;

                regU = null;

                db.Users.Add(user);
                db.SaveChanges();

                Session["smsg"] = "User Created, You will recieve a verification email";
                genLog("Create", "User Created: Verify Link = " + actKey, user.username);

                return(RedirectToAction("Success"));
            }

            return(View(regU));
        }
예제 #4
0
        static void Main(string[] args)
        {
            var PasswordMode = (int)RandomPassword.Mode.ShufflePassword;
            var retPass      = RandomPassword.SetPassword(PasswordMode, 10, 15, 0, 0);

            Console.WriteLine(retPass);
        }
예제 #5
0
        public void RandomPassword_Generates_Correct_String_Length()
        {
            int    length   = 10;
            string password = RandomPassword.Generate(length);

            Assert.AreEqual(length, password.Length, "Password length is incorrect");
        }
예제 #6
0
        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            string user    = txtUser.Text;
            var    persona = instanciBD.tbl_persona.Where(x => x.usuarioPersona == user).FirstOrDefault();

            if (persona != null)
            {
                string newPasEncriptada = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric, PasswordGroup.Special); //la cantidad de argumentos, minusculas, mayusculas/ numeros y caracteres especiales

                string salt = encriptado.GenerateSalt();
                string contrasenaEncriptada = encriptado.Compute(newPasEncriptada);
                try
                {
                    persona.salt = salt;
                    persona.contrasenaPersona = contrasenaEncriptada;
                    instanciBD.SubmitChanges();
                    EnviarCorreo(persona.emailPersona, newPasEncriptada);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "aletarUsuario", "window.onload = function(){ alert ('Usuario No esta');};", true);
            }
        }
예제 #7
0
        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            int usuario = Convert.ToInt32(txtUsuario.Text.Trim());

            Usuario c = usu.BuscarUsuario(usuario);

            if (c != null)
            {
                ICryptoService cryptoService = new PBKDF2();

                string nuevaPass     = RandomPassword.Generate(10, PasswordGroup.Uppercase, PasswordGroup.Numeric);
                string nuevaPassEncr = Encriptacion.Encriptar(nuevaPass);

                try
                {
                    usu.ActualizarClave(nuevaPassEncr, c.IdUsuario);
                    EnviarEmail(c.Correo, nuevaPass);
                    MostrarMensaje("Correo Enviado con exito");
                }
                catch (Exception)
                {
                    MostrarMensajeError("Error al enviar el correo, intente mas tarde");
                }
            }
            else
            {
                MostrarMensajeError("El usuario no existe");
            }
        }
예제 #8
0
        public ActionResult ForgotPassword(string EmailId)
        {
            var auth = db.Users.Where(a => a.EmailId.Equals(EmailId)).FirstOrDefault();

            if (auth != null)
            {
                String      getranpass = RandomPassword.Generate(8, 10);
                MailMessage mail       = new MailMessage("*****@*****.**", EmailId.ToString());
                mail.Subject = "New Temporary Password has been created for you";
                string Body = "Hello,\n\nWe have generated a new password for you \nPassword:"******"\n\nRegards,\nNotes Marketplace";
                mail.Body       = Body;
                mail.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;

                NetworkCredential nc = new NetworkCredential("*****@*****.**", "12345678finalpatel");
                smtp.EnableSsl   = true;
                smtp.Credentials = nc;
                smtp.Send(mail);

                User user = db.Users.FirstOrDefault(x => x.EmailId.Equals(EmailId.ToString()));
                user.Password  = getranpass;
                user.Password2 = getranpass;
                db.SaveChanges();

                return(RedirectToAction("Login", "Home"));
            }
            return(RedirectToAction("Login", "Home"));
        }
예제 #9
0
        protected void BtnRecuperar_Click(object sender, EventArgs e)
        {
            string mail = TXTEmail.Text;

            var usuario = GestorUsuario.BuscarMail(mail);

            string Email = usuario.ToString();

            if (usuario != null)
            {
                // genera una contraseña automaticamente
                ICryptoService cryptoService = new PBKDF2();

                // conformada con letras mayusculas y minusculas y un tamaño de 10 caracteres
                // esta contraseña se la voy a mandar al usuario para que pueda entrar

                string nuevapassword = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase);

                // y la encriptamos
                string contraseaencriptada = ServicioSecurizacion.AplicarHash(nuevapassword);
                GestorUsuario.ActualizarPassword(mail, contraseaencriptada);
                EnviarEmail(usuario.Email, nuevapassword);
                Response.Redirect("IniciarSesion.aspx");
            }

            else
            {
                Response.Write("<script>alert('No se encontro el Usuario')</script>");
            }
        }
예제 #10
0
        public async Task <bool> ForgotPassword(string email, int number)
        {
            var confirm = await confirmRepository.GetAsync(x => x.Email == email);

            if (confirm == null)
            {
                return(false);
            }

            if (confirm.Rand == number)
            {
                if (confirm.CreatedAt.AddHours(24) >= DateTime.Now)
                {
                    string new_password = RandomPassword.Generate();
                    if (Mail.SendRandomPassword(email, new_password))
                    {
                        var user = await userRepository.GetAsync(u => u.Email == email);

                        if (user.DeletedAt != null)
                        {
                            return(false);
                        }

                        user.Password = Secure.Encryptpass(new_password);
                        confirmRepository.Delete(confirm);
                        await confirmRepository.SaveAsync();

                        return(true);
                    }
                }
            }

            return(false);
        }
예제 #11
0
    private void ReplaceSampleSitenameInConnStrings(string filename, string sitename)
    {
        if (File.Exists(filename))
        {
            string origText        = FileSystem.GetFileContents(filename);
            string appsettingsFile = origText;
            //Initial Catalog=codelibmvc;
            // note: this generated password is not used if the password has already been replaced out
            pwd = RandomPassword.Generate(12, 14);
            // dev
            appsettingsFile = appsettingsFile.Replace("Data Source=[datasource];Initial Catalog=codelibmvc;User Id=sa;Password=[password]", "Data Source=thatcher;Initial Catalog=sitename;User Id=sitename;Password="******"Initial Catalog=sitename;User Id=sitename;", "Initial Catalog=" + sitename + ";User Id=" + sitename + "_user;");
            appsettingsFile = appsettingsFile.Replace(";Password=pw", ";Password="******"updated conn strings setting[" + filename + "], <span style=\"color:red;\">you should create a user called " + sitename + "user, with a Password="******"</span><br />");
            }
            else
            {
                Log("didnt update the conn strings[" + filename + "]<br />");
            }
        }
    }
        public JsonResult RecuperarClave(String email, String tipoUsuario)
        {
            string obtenerEmail = ConsultaUsuario.Leer_Correo(email, tipoUsuario);
            String msj;
            bool   validar = false;

            if (obtenerEmail != null && obtenerEmail.Equals(email))
            {
                string clave = RandomPassword.Generate(8);
                ConsultaUsuario.Cambiar_clave(tipoUsuario, email, clave);
                EmailSender.Send(email, "Cambio de clave", "Su nueva clave temporal es: " + clave);
                validar = true;
                msj     = "Se ha enviado una clave temporal a su correo exitosamente. Recuerde modificar su clave.";
            }
            else
            {
                msj = "No se ha podido generar una clave temporal. Verifique que los datos ingresados sean correcto o que tenga conexión a internet e intentelo nuevamente. Si el problema persiste favor de contactarse con soporte.";
            }

            var datos = new
            {
                validar,
                msj
            };

            return(Json(datos));
        }
예제 #13
0
        public bool ResetPassword(string applicationId, string userName)
        {
            var user = Get(new User()
            {
                UserName = userName
            });

            if (user == null)
            {
                return(false);
            }
            var salt     = EncryptUtils.GenerateSalt();
            var rd       = new RandomPassword();
            var password = rd.Generate(8, 10);

            password = EncryptUtils.EncryptPassword(password, salt);
            var comm = GetCommand("acc_UserChangePassword");

            if (comm == null)
            {
                return(false);
            }
            comm.AddParameter <string>(this.Factory, "ApplicationId", applicationId);
            comm.AddParameter <string>(this.Factory, "UserId", user.UserId);
            comm.AddParameter <string>(this.Factory, "Password", password);
            comm.AddParameter <string>(this.Factory, "PasswordSalt", salt);
            return(comm.SafeExecuteNonQuery() != 0);
        }
예제 #14
0
        public ActionResult Forgot([Bind(Include = "username,email")] UserPassChange upc)
        {
            User user = db.Users.Find(upc.username);

            if (user == null)
            {
            }
            else if (user.email != upc.email)
            {
                user = null;
            }

            if (user != null)
            {
                String forKey = "/Reset?kstr=" + RandomPassword.Generate(44, PasswordGroup.Uppercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
                user.forString       = forKey;
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                genLog("Forgot", "Accout Reset Sent: link = " + forKey, user.username);
                return(RedirectToAction("Index", "Users"));
            }
            else
            {
                ModelState.AddModelError("Error", "User or Email not found");
            }

            return(View(upc));
        }
예제 #15
0
        public static ManagedClusterBuilder WithNewAppAndServicePrincipal(this ManagedClusterBuilder builder)
        {
            var adApp = new Application($"{builder.Arguments.ResourceName}-app");

            var adSp = new ServicePrincipal($"{builder.Arguments.ResourceName}-sp", new ServicePrincipalArgs
            {
                ApplicationId = adApp.Id
            });

            var password = new RandomPassword($"{builder.Arguments.ResourceName}-password", new RandomPasswordArgs
            {
                Length  = 20,
                Special = true
            });

            var adSpPassword = new ServicePrincipalPassword($"{builder.Arguments.ResourceName}-sp-password", new ServicePrincipalPasswordArgs
            {
                ServicePrincipalId = adSp.Id,
                Value           = password.Result,
                EndDateRelative = "8760h" // 1 year from the creation of this password
            });

            builder.Arguments.ServicePrincipalProfile = new ManagedClusterServicePrincipalProfileArgs
            {
                ClientId = adApp.ApplicationId,
                Secret   = adSpPassword.Value
            };
            return(builder);
        }
예제 #16
0
            //[LogAspect(typeof(DbLogger))]
            public async Task <IResult> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
            {
                var isbagisciExits = await _userDal.GetAsync(u => u.TCKimlikNo == Convert.ToInt64(request.TCKimlikNo) &&
                                                             u.Email == request.Email);

                if (isbagisciExits == null)
                {
                    return(new ErrorResult(Messages.WrongCID));
                }
                var generatedPassword = RandomPassword.CreateRandomPassword(14);

                HashingHelper.CreatePasswordHash(generatedPassword, out byte[] passwordSalt, out byte[] passwordHash);

                var user = new User
                {
                    Status      = true,
                    Email       = isbagisciExits.Email,
                    CepTelefonu = isbagisciExits.CepTelefonu,
                    UserId      = isbagisciExits.UserId
                };

                _userDal.Update(user);
                //TODO: Yeni Şifre SMS ya da Mail Atılsın
                return(new SuccessResult(Messages.SendPassword + " Yeni Parola:" + generatedPassword + "passwordHash" + passwordHash + "passwordSalt" + passwordSalt));
            }
		protected virtual async Task<LoginUserResult> PrepareOneTimePassword(AuthenticationProviderType providerType, string cellPhone, string externalUserId)
		{
			var oneTimePassword = await _logins.Query()
																			.Where(m => m.Provider == providerType && m.ExternalUserId == externalUserId && m.IsUsed == false)
																			.Select(m => m.Code)
																			.FirstOrDefaultAsync();
			int mobileCode;
			if (oneTimePassword == default)
			{
				mobileCode = RandomPassword.RandomNumberGenerator();
				try
				{
					var sendSms = await _smsService.SendAssist($"SAAT {DateTime.Now.ToShortTimeString()} TALEP ETTIGINIZ 24 SAAT GECERLI PAROLANIZ : {mobileCode}", cellPhone);
					_logins.Add(new MobileLogin
					{
						Code = mobileCode,
						IsSend = sendSms,
						SendDate = DateTime.Now,
						ExternalUserId = externalUserId,
						Provider = providerType,
						IsUsed = false
					});
					await _logins.SaveChangesAsync();
				}
				catch
				{
					return new LoginUserResult { Message = Messages.SmsServiceNotFound, Status = LoginUserResult.LoginStatus.ServiceError };
				}
			}
			else
			{
				mobileCode = oneTimePassword;
			}
			return new LoginUserResult { Message = Messages.SendMobileCode + mobileCode, Status = LoginUserResult.LoginStatus.Ok };
		}
예제 #18
0
        public byte[] GetCaptcha(string root = null)
        {
            byte[] CaptchaImage = null;
            using (Font font = new Font("Courier New", 21, FontStyle.Bold))
            {
                string password = RandomPassword.Generate(5, 5);
                if (root == "Login")
                {
                    Session[SessionName.CaptchaLogin.ToString()] = password;
                }
                else
                {
                    Session[SessionName.Captcha.ToString()] = password;
                }


                Size size = this.GetTextSize(font, password.ToString());

                Bitmap bmp = new Bitmap(size.Width + 20, (int)(size.Height * 2.1));

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.Clear(Color.White);

                    g.DrawString(Convert.ToString(password), font, Brushes.Blue, 3, 3);

                    CaptchaImage = bmp.ConvertByteArray();
                }
            }
            return(CaptchaImage);
        }
        public async Task <IActionResult> ResendConfirmation(string UserName)
        {
            var user = await _userManager.FindByNameAsync(UserName);

            if (user == null)
            {
                return(NotFound());
            }

            try
            {
                var password = RandomPassword.GenerateRandomPassword(8);

                var hash = _userManager.PasswordHasher.HashPassword(user, password);
                user.PasswordHash = hash;

                await _context.SaveChangesAsync();

                await this.SendEmail(user, password);

                this._flashMessage.Queue(FlashMessageType.Confirmation, $"Confirmación reenviada al email <b>{user.Email}</b>.", string.Empty, true);

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(View());
            }
        }
예제 #20
0
        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            string usuario = txtUsuario.Text.Trim();

            var persona = db.Persona.Where(x => x.usuario == usuario).FirstOrDefault();

            if (persona != null)
            {
                ICryptoService cryptoService = new PBKDF2();

                string contrasennaNueva = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric, PasswordGroup.Special);

                string salt = cryptoService.GenerateSalt();
                string contrasennaCryptada = cryptoService.Compute(contrasennaNueva);

                try
                {
                    persona.salt        = salt;
                    persona.contrasenna = contrasennaCryptada;
                    db.SubmitChanges();
                    enviarEmail(persona.email, contrasennaNueva);
                }
                catch (Exception) {
                    throw;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "alertaUsuario", "window.onload = function(){alert('El usuario no existe.');};", true);
            }
        }
예제 #21
0
        public async Task <ActionResult> ResetPassword(int id)
        {
            BL.UserInfo empBL = new BL.UserInfo();
            if (empBL.GetItemByIdForDelete(id) != null)
            {
                return(Redirect(Url.Action("HttpError", "Error", new { area = "" })));
            }
            IPasswordPolicy Password        = new RandomPassword();
            string          orginalPassword = Password.GeneratePassword();

            orginalPassword = "******";
            string md5Password = HashEncrypt.MD5(orginalPassword);

            VM.UserInfoItem model = new VM.UserInfoItem();
            model = empBL.GetItemById(id);
            //IdentityModel user = await UserManager.FindByNameAsync(model.LogonName);
            //string password = UserManager.PasswordHasher.HashPassword(md5Password);
            //UserStore store = new UserStore(UserHelper.GetCurrentUser().LogonName);
            //var set = store.SetPasswordHashAsync(user, password);
            //var result = store.UpdateAsync(user);

            model.Password = md5Password;
            empBL.UpdatePasswordDb(model);
            if (model != null)
            {
                // empBL.SendEmail(model, orginalPassword, "User_ResetPassword");
                return(Json(true, JsonRequestBehavior.AllowGet));
            }
            return(Json(false, JsonRequestBehavior.AllowGet));
        }
예제 #22
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                lblError.Text = "Por favor ingrese correctamente los datos de verificación!";
                return;
            }

            //Cargar sobre el objeto global de la clase controladora
            oUsuario = cAdministrador.Usuario_forget(txtUsuario.Text, txtEmail.Text);

            if (oUsuario != null)
            {
                //Update Password:
                string NewPassword = "";
                if (chkNewPass.Checked)
                {
                    NewPassword = cEncriptador.EncryptTripleDES(RandomPassword.Generate(8));
                    if (cAdministrador.Usuario_editPassword(oUsuario.IdUsuario, NewPassword))
                    {
                        oUsuario.Password = NewPassword;
                    }
                }

                string urlAdmin = ConfigurationSettings.AppSettings["Domain"].ToString() + ConfigurationSettings.AppSettings["WebRoot"].ToString() + "admin";
                string Asunto   = "Recuperación de Contraseña";
                string Mensaje  = "<p>Usted ha solicitado recepcionar sus datos de acceso al sistema de administración mediante este correo.</p>";

                Mensaje += "Usuario: " + oUsuario.UserName + "<br>";
                Mensaje += ((chkNewPass.Checked && (oUsuario.Password == NewPassword)) ? "Nueva " : "") + "Contraseña: " + cEncriptador.DecryptTripleDES(oUsuario.Password) + "<br>";

                Mensaje += "<p>Para acceder al sistema ingrese desde la siguiente ruta: <a href='http://" + urlAdmin + "'>" + urlAdmin + "</a></p>";
                Mensaje += "<p>Gracias,<br />Administrador del Sistema</p><p>&nbsp;</p>";
                Mensaje += "<p>NOTA:Por favor elimine este correo una vez que haya recepcionado los datos</p>";
                Mensaje += "<p>(*)Este mail ha sido generado automáticamente desde un sistema de información.</p>";

                //Send mail:
                liteCMS.Web.mail.smtpMail smtpMail = new liteCMS.Web.mail.smtpMail();
                smtpMail.FromEmail     = ConfigurationSettings.AppSettings["Postmaster"].ToString();
                smtpMail.FromNameEmail = ConfigurationSettings.AppSettings["Domain"].ToString();
                smtpMail.ToEmail       = oUsuario.Email;
                smtpMail.ToNameEmail   = oUsuario.Nombres + " " + oUsuario.Apellidos;
                smtpMail.Titulo        = Asunto;
                smtpMail.Subject       = Asunto;
                smtpMail.Texto         = Mensaje;
                smtpMail.setTemplate();
                smtpMail.SendMail();

                //Registrar log de incidencia:
                RegistrarLog(2, "El usuario \"" + oUsuario.UserName + "\" solicitó enviar su contraseña");

                lblEmailResponse.Text     = oUsuario.Email;
                mvwForget.ActiveViewIndex = 1;
            }
            else
            {
                lblError.Text = "El nombre de usuario y el correo no coinciden!";
            }
        }
예제 #23
0
 static void Main(string[] args)
 {
     // Print 100 randomly generated passwords (8-to-10 char long).
     for (int i = 0; i < 100; i++)
     {
         Console.WriteLine(RandomPassword.Generate(8, 10));
     }
 }
예제 #24
0
        public void RandomPassword_Generates_Single_Length_Uppercase()
        {
            int    length   = 15;
            string password = RandomPassword.Generate(length, PasswordGroup.Uppercase);

            Assert.IsTrue(Regex.IsMatch(password, "^[A-Z]+$"), "Non-uppercase found in in uppercase only");
            Assert.AreEqual(length, password.Length, "Password length is incorrect");
        }
예제 #25
0
        public static ListSet GetAirfields(String text)
        {
            ListSet aset = new ListSet();

            if (text.Contains("(") && text.Contains(")"))
            {
                String id = text.Substring(text.LastIndexOf("(") + 1, text.LastIndexOf(")") - text.LastIndexOf("(") - 1);
                if (id.Contains("Lat:") && id.Contains("Long:"))
                {
                    Airfield a = new Airfield();
                    a.ICAOCODE     = "T-T" + RandomPassword.Generate(5);
                    a.AirfieldName = text.Remove(text.IndexOf(",")).Trim();
                    a.Country      = text.Substring(text.IndexOf(",") + 1, text.IndexOf("(") - text.IndexOf(",") - 1).Trim();
                    foreach (String l in id.Split(",".ToCharArray()))
                    {
                        Double temp;
                        if (l.Contains("Lat:"))
                        {
                            temp = Double.Parse(l.Substring(l.LastIndexOf(":") + 1));
                            string[] parts = DDtoDMS(temp, CoordinateType.latitude).Split(".".ToCharArray());
                            a.LattitudeDegrees = Int32.Parse(parts[0]);
                            a.LattitudeMinutes = Int32.Parse(parts[1]);
                            a.NS = Char.Parse(parts[2]);
                        }
                        else if (l.Contains("Long:"))
                        {
                            temp = Double.Parse(l.Substring(l.LastIndexOf(":") + 1));
                            string[] parts = DDtoDMS(temp, CoordinateType.longitude).Split(".".ToCharArray());
                            a.LongitudeDegrees = Int32.Parse(parts[0]);
                            a.LongitudeMinutes = Int32.Parse(parts[1]);
                            a.EW = Char.Parse(parts[2]);
                        }
                    }
                    aset.Add(a);
                }
                else
                {
                    Airfield a = AirfieldDAO.FindAirfieldByID(id);
                    aset.Add(a);
                }
            }
            else
            {
                aset.AddAll(SearchAifields(text));
                if (aset.Count == 0)
                {
                    String[] keywords = text.Split(", ".ToCharArray());
                    foreach (String s in keywords)
                    {
                        if (s.Length >= 3)
                        {
                            aset.AddAll(SearchAifields(s));
                        }
                    }
                }
            }
            return(aset);
        }
예제 #26
0
        public async Task GeneratePasswordsAsync()
        {
            if (this.passwordLength < 8 || this.passwordCount < 1 || this.usableCharacters.Distinct().Count() < 1)
            {
                return;
            }

            this.generateButtonIsEnabled = false;
            this.cancelButtonIsEnabled   = true;
            this.passwordGeneratedCount  = 0;
            this.progressMax             = this.passwordCount;
            this.completeIconVisible     = false;

            var generator = new RandomPassword(passwordLength, this.usableCharacters);

            if (this.useCharacterOver3Kinds && RandomPassword.CalculateCharacterKindCount(this.usableCharacters) >= 3)
            {
                generator = generator.CharacterShuoldHaveOverThreeKinds();
            }
            if (this.useUniqueCharacter && this.passwordLength < (this.usableCharacters.Length / 3))
            {
                generator = generator.CharacterShouldNotDuplicate();
            }
            if (this.notStartWithExcelSpecialCharacter && this.passwordLength > 1)
            {
                generator = generator.NotStartWithExcelSpecialCharacter();
            }
            this.passwordGeneratedCount = 0;
            string result = string.Empty;

            this.generatedPasswordList = string.Empty;
            string passwordList = string.Empty;

            this.generatingIsCanceled = false;

            await foreach (var passwordWithRuby in generator.GeneratePasswordAsync(this.passwordCount))
            {
                passwordList += passwordWithRuby.Password + "\t" + passwordWithRuby.Ruby + "\r\n";
                this.passwordGeneratedCount++;

                if (this.passwordGeneratedCount % 10 == 0)
                {
                    if (this.generatingIsCanceled)
                    {
                        this.generatingIsCanceled = false;
                        break;
                    }
                    StateHasChanged();
                    await Task.Delay(10);
                }
            }

            this.generatedPasswordList   = passwordList;
            this.completeIconVisible     = true;
            this.generateButtonIsEnabled = true;
            this.cancelButtonIsEnabled   = false;
        }
예제 #27
0
        public async Task <IActionResult> Register([FromBody] RegisterViewModel model)
        {
            try
            {
                //Number to be registered
                var numberToBeRegistered = _candidate.GetNumberToBeRegistered("Enroll");
                //Number already registered
                var successfullyRegistered = _candidate.GetNumberSuccessfullyRegistered("Enroll");
                //Number already failed
                var failedRegistered = _candidate.GetNumberFailedRegistered("Enroll");
                //Total number of register and failed
                var totalRegistered     = successfullyRegistered + failedRegistered + 1;
                var totalRegisteredInDb = successfullyRegistered + failedRegistered;

                int success  = 0;
                int failed   = 0;
                var password = "";

                //Generated password that will be shown to the admin alone
                if (successfullyRegistered == 0)
                {
                    password = RandomPassword.GenerateRandomPassword(new PasswordOptions());
                }
                else
                {
                    password = _candidate.GetGeneratedPassword("Enroll");
                }

                if (totalRegisteredInDb < numberToBeRegistered)
                {
                    var user   = _candidate.GetUserViewModel(model);
                    var result = await _userManager.CreateAsync(user, password);

                    if (result.Succeeded)
                    {
                        //Update the number already registered and password
                        await _userManager.AddToRoleAsync(user, "UploadedStudent");

                        success = successfullyRegistered + 1;
                        _candidate.UpdateExamSettingAfterSuccessfulRegisteration(success, password, "Enroll");
                        return(Ok(new { success = RepsonseMessages.PrintResponseMessage("AuthRegister.Success") }));
                    }
                    else
                    {
                        //Update the number that failed and password
                        failed = failedRegistered + 1;
                        _candidate.UpdateExamSettingFailedRegisteration(failed, "Enroll");
                        return(BadRequest(new { error = result.Errors }));
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(new { error = ex.Message }));
            }
            return(BadRequest(new { error = RepsonseMessages.PrintResponseMessage("AuthRegister.Error") }));
        }
 public void GenerateRandom01()
 {
     for (int i = 0; i < 100; i++)
     {
         int    length = TestInfrastructure.RandomGen.Next(1, 1000);
         string s      = RandomPassword.Generate(length);
         Assert.AreEqual <int>(length, s.Length);
     }
 }
예제 #29
0
    private Output <string> GenerateRandomPassword()
    {
        var pw = new RandomPassword("pw", new RandomPasswordArgs
        {
            Length  = 20,
            Special = true
        });

        return(pw.Result);
    }
 public void GenerateRandom02()
 {
     for (int i = 0; i < 100; i++)
     {
         int    lower = TestInfrastructure.RandomGen.Next(1, 1000);
         int    upper = TestInfrastructure.RandomGen.Next(lower, 1000);
         string s     = RandomPassword.Generate(lower, upper);
         Assert.IsTrue((s.Length >= lower) && (s.Length <= upper));
     }
 }