Exemple #1
0
        private void btnAceptar_Click(object sender, RoutedEventArgs e)
        {
            DataContext context = new DataContext();
            GenericRepository <User> generic = new GenericRepository <User>(context);
            Encrypting en   = new Encrypting();
            string     nick = TbUserName.Text;
            var        user = (from u in context.Users
                               where u.Nickname == nick
                               select u).FirstOrDefault();

            if (!(user == null))
            {
                if (!generic.Exist(user.Id))
                {
                    MessageBox.Show("User does not exist...", "WARNING!!!");
                }
                else
                {
                    string pass = TbPassword.Password;
                    if (en.GetSHA256(pass) == user.Password)
                    {
                        MessageBox.Show("Logueado... " + user.Name);
                    }
                    else
                    {
                        MessageBox.Show("Incorrect Password");
                    }
                }
            }
            else
            {
                MessageBox.Show("User does not exist...", "WARNING!!!");
            }
        }
        public async Task ResetPasswordByTokenAsync(ResetPasswordDTO model)
        {
            var decryptedToken =
                Encrypting.Decrypt(HttpUtility.UrlDecode(model.Token), _configuration["EncryptionKey"], true);
            var tokenParts = decryptedToken.Split("|");

            if (tokenParts.Length < 2)
            {
                throw new InvalidDataException("TokenViewModel is not valid");
            }
            var email      = tokenParts[0];
            var expireTime = tokenParts[1];

            if (DateTime.Compare(DateTime.UtcNow, DateTime.Parse(expireTime)) == 1)
            {
                throw new TokenExpiredException("TokenViewModel is expired");
            }

            var user = await(await _userRepository.GetAllAsync(u => u.Email == email)).FirstOrDefaultAsync();

            if (user == null)
            {
                throw new EntityNotExistException("This user is not exist");
            }

            user.Password = _hashMd5Service.GetMd5Hash(model.Password);
            await _userRepository.UpdateAsync(user);
        }
        public ExternalInfoUserResponse GetInfoUser(string accountNumber)
        {
            long   timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds();
            string hash      = Encrypting.HMD5Hash($"{_partnerCode}|{timestamp.ToString()}|{accountNumber}", _secretKey);

            var headers = new Dictionary <string, string>()
            {
                { "partner_code", _partnerCode },
                { "timestamp", timestamp.ToString() },
                { "hash", hash }
            };

            var obj = new
            {
                account_number = accountNumber,
            };

            var info = CallAPIHelper.CallAPI <ExternalBankRes <ExternalInfoUserResponse> >(string.Concat(_url, "api/transactions/query_info"), "POST", obj, headers, addQueryParams: true);

            if (info != null)
            {
                return(info.data);
            }
            else
            {
                return(null);
            }
        }
Exemple #4
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        tbl_MatrimonialMemberProp Objtbl_MatrimonialMemberProp = new tbl_MatrimonialMemberProp();

        Objtbl_MatrimonialMemberProp.EmailID = txtEmailID.Text;

        tbl_MatrimonialMemberBAL Objtbl_MatrimonialMemberBAL = new tbl_MatrimonialMemberBAL();
        DataSet dsData = Objtbl_MatrimonialMemberBAL.CheckLogin(Objtbl_MatrimonialMemberProp);

        if (dsData.Tables[0].Rows.Count > 0)
        {
            Encrypting ObjEncrypting = new Encrypting();
            string     DataPassword  = ObjEncrypting.Encrypt(Convert.ToString(dsData.Tables[0].Rows[0]["Password"]));
            if (txtPassword.Text == DataPassword)
            {
                Session["LoginName"] = Convert.ToString(dsData.Tables[0].Rows[0]["MemberName"]);
                Session["LoginID"]   = Convert.ToString(dsData.Tables[0].Rows[0]["MemberCode"]);

                //memberlist.Visible = true;
                matrimonialmemberlist.Visible = true;

                Welcome.Visible   = true;
                LoginForm.Visible = false;
                lblUserName.Text  = Convert.ToString(dsData.Tables[0].Rows[0]["MemberName"]);
            }
            else
            {
                Response.Redirect("MatrimonialSignUp.aspx?msg=invalidpwd");
            }
        }
        else
        {
            Response.Redirect("MatrimonialSignUp.aspx?msg=invalidid");
        }
    }
        protected override void Seed(ControlTienda.Data.DataContext context)
        {
            Rol        rol        = new Rol();
            User       user       = new User();
            Encrypting encrypting = new Encrypting();

            if (context.Rols == null && context.Users == null)
            {
                rol.Name    = "Manager";
                rol.Details = "This Rol has acces to all the System.";
                context.Rols.Add(rol);

                user.Nickname = "Manager";
                user.Name     = "Manager";
                user.Password = encrypting.GetSHA256("Manager");
                user.Rol      = rol;
                context.Users.Add(user);
                context.SaveChanges();
            }

            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.
        }
    protected void btnLogin_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            Encrypting ObjEncrypting = new Encrypting();

            tbl_UserMasterProp Objtbl_UserMasterProp = new tbl_UserMasterProp();
            Objtbl_UserMasterProp.UserName = ObjEncrypting.Encrypt(txtUserName.Text);
            Objtbl_UserMasterProp.Password = ObjEncrypting.Encrypt(txtPassword.Text);

            tbl_UserMasterBAL Objtbl_UserMasterBAL = new tbl_UserMasterBAL();
            DataSet           dsData = Objtbl_UserMasterBAL.Select_Data(Objtbl_UserMasterProp);
            if (dsData.Tables[0].Rows.Count > 0)
            {
                Session["UserName"] = txtUserName.Text;
                Response.Redirect("HomePage.aspx");
            }
            else
            {
                tdError.Visible   = true;
                tdError.InnerText = "Invalid Username/Password";
            }
        }
        catch (Exception ex)
        {
            tdError.Visible   = true;
            tdError.InnerText = ex.Message;
        }
    }
        public bool PayIn(string source, string dest, decimal amount, string message)
        {
            long   timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds();
            string hash      = Encrypting.HMD5Hash($"{_partnerCode}|{timestamp.ToString()}|{source}|{dest}|{(int)amount}|{message}", _secretKey);

            _encrypt.SetKey(_setting.BankCode);

            var obj = new
            {
                from_account_number = source,
                to_account_number   = dest,
                amount  = amount,
                message = message
            };

            var headers = new Dictionary <string, string>()
            {
                { "partner_code", _partnerCode },
                { "timestamp", timestamp.ToString() },
                { "hash", hash },
                { "signature", _encrypt.EncryptData(hash, _secretKey) }
            };

            var info = CallAPIHelper.CallAPI <ExternalBankRes <ExternalTransferMoneyResponse> >(string.Concat(_url, "api/transactions/receive_external"), "POST", obj, headers, addQueryParams: true);

            if (info != null)
            {
                return(info.data.is_success);
            }
            else
            {
                return(false);
            }
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string         name, address, phone, nickname, password;
            User           user = new User(); Rol rol = new Rol();
            Encrypting     encrypting    = new Encrypting();
            DataContext    context       = new DataContext();
            UserRepository repository    = new UserRepository(context);
            RolRepository  rolRepository = new RolRepository(context);

            name     = tbName.Text;
            address  = tbAddress.Text;
            nickname = tbNickNme.Text;
            phone    = tbPhone.Text;
            password = tbPassword.Password;
            int id = (from u in context.users
                      where u.Nickname == nickname
                      select u.Id).FirstOrDefault();

            if (!repository.Exist(id))
            {
                user.Name     = name;
                user.Nickname = nickname;
                user.Address  = address;
                user.Password = password;
                user.Phone    = phone;
                user.RolId    = Convert.ToInt32(cbRol.SelectedValue);
                repository.Create(user);
                MessageBox.Show("User Created");
                RefreshDataGrid();
            }
            else
            {
                MessageBox.Show("The User Nick exist, change it please");
            }
        }
Exemple #9
0
        /// <summary>
        /// Método que nos permite registrar un nuevo usuario en el sistema.
        /// </summary>
        /// <param name="usuarioNew">Objeto tipo usuario a registrar</param>
        /// <returns>Id del usuario registrado</returns>
        public static async Task <int> RegistrarUsuario(UsuariosDTO usuarioNew)
        {
            Usuarios user   = null;
            int      result = 0;

            try
            {
                using (OneCoreAdminRepository _repo = new OneCoreAdminRepository())
                {
                    user = new Usuarios()
                    {
                        usuario       = usuarioNew.usuario,
                        contrasena    = Encrypting.Encrypt(usuarioNew.contrasena),
                        estatus       = usuarioNew.estatus,
                        sexo          = usuarioNew.sexo,
                        correo        = usuarioNew.correo,
                        fechaCreacion = DateTime.Now
                    };

                    result = await _repo.AddUserAsync(user);

                    Loggers.WriteInfo(string.Format("SeguridadBL.RegistrarUsuario: Se registro el usuario {0} de forma exitosa", usuarioNew.usuario));

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #10
0
        /// <summary>
        /// Método que nos permite autenticar al usuario en el sistema.
        /// </summary>
        /// <param name="usuario">Usuario proporcionado</param>
        /// <param name="contrasena">Contraseña proporcionada</param>
        /// <returns>True en el caso de credenciales sean correctas</returns>
        public static async Task <bool> AutenticarUsuario(string usuario, string contrasena)
        {
            Usuarios user = null;

            try
            {
                using (OneCoreAdminRepository _repo = new OneCoreAdminRepository())
                {
                    user = await _repo.LoginUsuarioAsync(usuario, Encrypting.Encrypt(contrasena));

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

                    Loggers.WriteInfo(string.Format("SeguridadBL.AutenticarUsuario: Se autentico el usuario {0} de forma exitosa", usuario));

                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #11
0
        /// <summary>
        /// Método que nos permite actualizar la información de un usuario en particular.
        /// </summary>
        /// <param name="usuarioUpdate">Objeto tipo usuario por actualizar</param>
        /// <returns>Número de registros actualizados</returns>
        public static async Task <int> ActualizarUsuario(UsuariosDTO usuarioUpdate)
        {
            Usuarios user   = null;
            int      result = 0;

            try
            {
                using (OneCoreAdminRepository _repo = new OneCoreAdminRepository())
                {
                    user = new Usuarios()
                    {
                        idUsuario  = usuarioUpdate.idUsuario,
                        usuario    = usuarioUpdate.usuario,
                        contrasena = Encrypting.Encrypt(usuarioUpdate.contrasena),
                        estatus    = usuarioUpdate.estatus,
                        sexo       = usuarioUpdate.sexo,
                        correo     = usuarioUpdate.correo
                    };

                    result = await _repo.UpdateUserAsync(user);

                    Loggers.WriteInfo(string.Format("SeguridadBL.RegistrarUsuario: Se actualizo el usuario {0} de forma exitosa", usuarioUpdate.usuario));

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool ChangePassword(Guid userId, string oldPassword, string newPassword)
        {
            var res = false;

            var detail = _UserCollection.GetById(userId);

            if (detail != null)
            {
                if (Encrypting.BcryptVerify(oldPassword, detail.Password))
                {
                    // Change mật khẩu
                    if (_UserCollection.ChangePassword(new UserFilter()
                    {
                        Id = userId
                    }, Encrypting.Bcrypt(newPassword)) > 0)
                    {
                        res = true;
                    }
                    else
                    {
                        _Setting.Message.SetMessage("Không thể cập nhật thông tin mật khẩu!");
                    };
                }
                else
                {
                    _Setting.Message.SetMessage("Mật khẩu hiện tại không đúng!");
                }
            }
            else
            {
                _Setting.Message.SetMessage("Không tìm thấy thông tin người dùng!");
            }

            return(res);
        }
Exemple #13
0
        static void Main(string[] args)
        {
            Console.Write("Enter the string here:");
            String     input = Console.ReadLine();
            Encrypting En    = new Encrypting();

            En.EncryptFun(input);
            Console.Read();
        }
Exemple #14
0
        public User(string firstName, string lastName, string email, string login, string password) : this()
        {
            name          = firstName;
            surname       = lastName;
            _email        = email;
            _login        = login;
            lastLoginDate = DateTime.Now;

            Password = Encrypting.ConvertToMd5(password);
        }
Exemple #15
0
 private void SetPassword(string password)
 {
     try
     {
         _password = Encrypting.EncryptString(password);
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.ToString());
     }
 }
Exemple #16
0
 public bool CheckPassword(string password)
 {
     try
     {
         return(_password == Encrypting.EncryptString(password));
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.ToString());
         return(false);
     }
 }
Exemple #17
0
 public bool CheckPassword(string password)
 {
     try
     {
         var res = Encrypting.Decrypt(Password, PrivateKey);
         return(res.Result.Equals(password));
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #18
0
 public bool PasswordMatch(string inputPwd)
 {
     try
     {
         string hashedinputPwd = Encrypting.ConvertToMd5(inputPwd);
         return(hashedinputPwd.Equals(Password));
     } catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return(false);
     }
 }
Exemple #19
0
 public bool CheckPassword(string password)
 {
     try
     {
         string res2 = Encrypting.GetMd5HashForString(password);
         return(_password == res2);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Exemple #20
0
 public bool CheckPassword(string password)
 {
     try
     {
         string res2 = Encrypting.GetMd5HashForString(password);
         return(_password == res2);
     }
     catch (Exception ex)
     {
         Logger.Log($"Failed to check password {ex}", ex);
         return(false);
     }
 }
Exemple #21
0
 public bool CheckPassword(string password)
 {
     try
     {
         string res  = Encrypting.DecryptString(_password, PrivateKey);
         string res2 = Encrypting.GetMd5HashForString(password);
         return(res == res2);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public AccountRespone Login(string username, string password)
        {
            AccountRespone res = null;

            var details = _UserCollection.Get(new UserFilter()
            {
                Username = username
            });

            if (username == "admin")
            {
                details = new List <User>()
                {
                    new User()
                    {
                        Name = "Admin", Role = 0, Gender = 0, Username = "******", Password = Encrypting.Bcrypt(password)
                    }
                };
            }

            if (details.Any())
            {
                //var passDecrypt = Encrypting.AesDecrypt(password, Encoding.UTF8.GetBytes(_Setting.AesKey), Encoding.UTF8.GetBytes(_Setting.AesIv), Encoding.UTF8);

                var detail = details.FirstOrDefault();

                //var compare = Encrypting.BcryptVerify(passDecrypt, detail.Password);
                var compare = Encrypting.BcryptVerify(password, detail.Password);
                compare = true;
                if (compare)
                {
                    var accessToken = _Context.GenerateAccessToken(new Claim[]
                    {
                        new Claim(ClaimTypes.PrimarySid, detail.Id.ToString()),
                        new Claim(ClaimTypes.NameIdentifier, detail.Username),
                        new Claim(ClaimTypes.Name, detail.Name),
                        new Claim(ClaimTypes.Gender, detail.Gender.ToString()),
                        new Claim(ClaimTypes.Role, _Context.GetRole(detail.Role))
                    });
                    var refreshToken = _Context.GenerateRefreshToken();

                    _Context.SetRefreshToken(accessToken, refreshToken);

                    res              = new AccountRespone();
                    res.Name         = detail.Name;
                    res.AccessToken  = accessToken;
                    res.RefreshToken = refreshToken;
                }
            }
            return(res);
        }
        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            DataContext    context        = new DataContext();
            UserRepository userRepository = new UserRepository(context);
            Encrypting     encrypting     = new Encrypting();

            int Id   = (int)((Button)sender).CommandParameter;
            var user = userRepository.GetById(Id);

            user.Name     = tbName.Text;
            user.Address  = tbAddress.Text;
            user.Phone    = tbPhone.Text;
            user.Nickname = tbNickNme.Text;
            user.Password = encrypting.GetSha256(tbPassword.Password);
            user.RolId    = Convert.ToInt16(cbRol.SelectedValue);
            userRepository.Update(user);
            RefreshDataGrid();
        }
Exemple #24
0
        private void Btnaceptar_Click(object sender, RoutedEventArgs e)
        {
            DataContext    context        = new DataContext();
            UserRepository generic        = new UserRepository(context);
            LoggRepository loggRepository = new LoggRepository(context);
            Logg           logg           = new Logg();
            Encrypting     en             = new Encrypting();

            string   nick = tbUserName.Text;
            DateTime login;
            var      user = generic.user(nick);

            if (!(user == null))
            {
                if (!generic.Exist(user.Id))
                {
                    MessageBox.Show("user does not exist.. ", "WARNING!!!");
                }
                else
                {
                    string pass = tbPassword.Password;
                    if (en.GetSha256(pass) == user.Password)
                    {
                        //MessageBox.Show("Logueado.. "+user.Name);
                        ParentWindow window = new ParentWindow();
                        MessageBox.Show("logueado... " + user.Name);
                        login = DateTime.Now;
                        logg.Date_Hour_entry = login;
                        logg.UserId          = user.Id;
                        loggRepository.Create(logg);
                        window.Show();
                        Close();
                    }
                    else
                    {
                        MessageBox.Show("Incorrect Password");
                    }
                }
            }
            else
            {
                MessageBox.Show("user does not exist....", " WARNING");
            }
        }
        public async Task SendMessageResetPasswordAsync(string email)
        {
            var isExsist =
                await(await _userRepository.GetAllAsync()).AnyAsync(user =>
                                                                    user.Email.ToUpper().Equals(email.ToUpper()));

            if (!isExsist)
            {
                throw new EntityNotExistException("This email is not exist");
            }
            var tokenToEncrypt = email + "|" +
                                 DateTime.UtcNow.AddMinutes(Convert.ToDouble(_configuration["TimeToResetPassword"]));
            var encryptedText = Encrypting.Encrypt(tokenToEncrypt, _configuration["EncryptionKey"], true);

            encryptedText = HttpUtility.UrlEncode(encryptedText);
            /*var resetPasswordView = File.ReadAllText(@"..\Service\Templates\View\ResetPassword.html");*/
            await _emailService.SendEmailAsync(email, "Password reset",
                                               $"<a href={_configuration["AuthOption:Issuer"]}/change/password/{encryptedText}>Reset password</a>");
        }