Пример #1
0
        private void button3_Click(object sender, EventArgs e)
        {
            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            using (StreamReader file = new StreamReader("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt"))
            {
                int    counter = 0;
                string ln;
                while ((ln = file.ReadLine()) != null)
                {
                    Console.WriteLine(ln);
                    using (var writer = File.AppendText("temp.txt"))
                    {
                        writer.WriteLine(AesOperation.EncryptString(key, ln));
                    }
                    counter++;
                }
            }
            // File.Delete("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
            // File.Create("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt");
            try
            {
                File.Copy("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", "C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\text.txt", true);
                File.WriteAllText("C:\\Users\\Lukas\\source\\repos\\Password\\Password\\bin\\Debug\\temp.txt", String.Empty);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }



            System.Windows.Forms.Application.ExitThread();
        }
        private void CryptoInterceptor()
        {
            var key = this.configuration.GetSection("Keys").GetValue <string>("Encrypt");

            // Look for properties with EncryptAttribute and encrypt.
            foreach (var item in ChangeTracker
                     .Entries() // no filter due to Identity Models
                     .Where(item => item.State == EntityState.Added || item.State == EntityState.Modified)
                     )
            {
                foreach (var property in item.Entity.GetType().GetProperties())
                {
                    var toEncrypt = property.GetCustomAttributes(true).OfType <EncryptAttribute>().Any();
                    if (!toEncrypt)
                    {
                        continue;
                    }
                    var val = item.Property(property.Name).CurrentValue?.ToString();
                    if (val != null)
                    {
                        var enc = AesOperation.EncryptString(key, val);
                        item.Property(property.Name).CurrentValue = enc;
                    }
                }
            }
        }
Пример #3
0
        public IActionResult Login([FromForm] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string UserName = model.UserName;
                string Password = AesOperation.EncryptString("mot cai key khong thang nao biet", model.Password);
                // string Password = model.Password;

                var found = db.Users.FirstOrDefault(item =>
                                                    item.Username == UserName &&
                                                    item.Password == Password
                                                    );

                if (found != null)
                {
                    HttpContext.Session.Set <User>("user", new User
                    {
                        Username  = found.Username,
                        Id        = found.Id,
                        UserRoles = found.UserRoles,
                    });

                    return(RedirectToAction("Index", "DashBoard"));
                }

                // Check user name and password
                ModelState.AddModelError(string.Empty, "Username or Password incorrect");
            }

            return(View("/Views/Admin/Login/Index.cshtml"));
        }
Пример #4
0
        static void Main(string[] args)
        {
            var cryptString      = new CryptString();
            var input            = "ariba@123123";
            var encryptedString1 = cryptString.EncryptStringToBase64(input,
                                                                     "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");
            var decrypted = cryptString.DecryptStringFromBase64(encryptedString1, "ERel23H+hkDPmzXDFoxzdB0RpB1DAQtCntjMOXAfkc8=", "ckOtx2apDX2JbizKyGCahg==");

            Console.WriteLine($"{input.Equals(decrypted)}");
            var key = "b14ca5898a4e4133bbce2ea2315a1916";

            //Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
            //var key = Console.ReadLine();

            Console.WriteLine("Please enter a string for encryption");
            var str             = Console.ReadLine();
            var encryptedString = AesOperation.EncryptString(key, str);

            Console.WriteLine($"encrypted string = {encryptedString}");

            var decryptedString = AesOperation.DecryptString(key, encryptedString);

            Console.WriteLine($"decrypted string = {decryptedString}");

            Console.ReadKey();
        }
Пример #5
0
        public IActionResult EditProfle([FromForm] User model)
        {
            var user = HttpContext.Session.Get <User>("customer");

            if (user == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            string key = "mot cai key khong thang nao biet";

            SkipModelValidate("Password");
            SkipModelValidate("Username");
            if (ModelState.IsValid)
            {
                var customer = db.Users.Find(user.Id);
                customer.Email    = model.Email;
                customer.FullName = model.FullName;
                customer.Address  = model.Address;
                customer.Phone    = model.Phone;
                customer.Address  = model.Address;
                customer.Email    = model.Email;
                HttpContext.Session.Set <User>("customer", new User
                {
                    Username  = user.Username,
                    Id        = user.Id,
                    UserRoles = user.UserRoles,
                    Email     = customer.Email,
                    FullName  = customer.FullName,
                    Address   = customer.Address,
                    Phone     = customer.Phone
                });
                if (model.Password != null)
                {
                    customer.Password = AesOperation.EncryptString(key, model.Password);
                }
                db.SaveChanges();
                TempData["Message"] = "Cập nhật tài khoản thành công";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(Redirect(Request.Headers["Referer"].ToString()));
        }
Пример #6
0
        public IActionResult RegisterCustomer([FromForm] User model)
        {
            string key          = "mot cai key khong thang nao biet";
            var    RoleCustomer = db.Roles.FirstOrDefault(r => r.Name == "Customer");

            if (db.Users.Any(item => item.Username == model.Username))
            {
                ModelState.AddModelError(string.Empty, "Tên tài khoản đã được sử dụng");
            }

            if (db.Users.Any(item => item.Email == model.Email))
            {
                ModelState.AddModelError(string.Empty, "Địa chỉ email đã được sử dụng");
            }

            if (ModelState.IsValid)
            {
                var customer = new User
                {
                    Username  = model.Username,
                    Email     = model.Email,
                    FullName  = model.FullName,
                    Status    = true,
                    Password  = AesOperation.EncryptString(key, model.Password),
                    CreatTime = DateTime.Now,
                    UserRoles = new List <UserRole> {
                        new UserRole {
                            Role = RoleCustomer
                        }
                    },
                };

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

                TempData["Message"] = "Tạo tài khoản thành công";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(RedirectToAction("Index"));
        }
Пример #7
0
        public static void SaveData(string[] data)
        {
            FileStream stream = new FileStream(Variables.EnviromentPath + Variables.DataFileName, FileMode.Create);

            stream.Close();

            StreamWriter sw = new StreamWriter(Variables.EnviromentPath + Variables.DataFileName, true, Encoding.UTF8);

            foreach (string item in data)
            {
                string temp = AesOperation.EncryptString(Variables.MacAdress, item);
                sw.Write(temp + "\n");
            }
            sw.Close();
        }
Пример #8
0
        public IActionResult Login([FromForm] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                string UserName = model.UserName;
                string Password = AesOperation.EncryptString("mot cai key khong thang nao biet", model.Password);
                // string Password = model.Password;

                var found = db.Users
                            .FirstOrDefault(item =>
                                            item.Username == UserName &&
                                            item.Password == Password
                                            )
                ;

                if (found != null)
                {
                    HttpContext.Session.Set <User>("customer", new User
                    {
                        Username  = found.Username,
                        Id        = found.Id,
                        UserRoles = found.UserRoles,
                        Email     = found.Email,
                        FullName  = found.FullName,
                        Address   = found.Address,
                        Phone     = found.Phone
                    });

                    return(Redirect(Request.Headers["Referer"].ToString()));
                }

                TempData["Error"] = "Sai tên đăng nhập hoặc mật khẩu";
            }
            else
            {
                foreach (var modelStateKey in ModelState.Keys)
                {
                    var modelStateVal = ModelState[modelStateKey];
                    foreach (var error in modelStateVal.Errors)
                    {
                        TempData["Error"] = error.ErrorMessage;
                    }
                }
            }

            return(View("/Views/Account/Index.cshtml"));
        }
        /// <summary>
        /// This method resprsents Make card payment
        /// </summary>
        /// <param name="bankModel">The bankModel</param>
        /// <returns></returns>
        public PaymentStatus MakeBankPayment(BankModel bankModel)
        {
            //Validate bankmodel
            BankValidation.Validate(bankModel);
            //Encrypt the user name
            var encryptedUserName = AesOperation.EncryptString(this._appSettings.Key, bankModel.UserName);

            //Encrypt the password
            var encryptedpassWord = AesOperation.EncryptString(this._appSettings.Key, bankModel.Password);

            var netBankList  = this.bankRepository.Query();
            var netBankModel = (from netBank in netBankList
                                where netBank.Password == encryptedpassWord && netBank.UserName == encryptedUserName
                                select netBank).FirstOrDefault();

            return(CompleteBankPayment(netBankModel, bankModel));
        }
Пример #10
0
        static void update(string usern)
        {
            Console.WriteLine("Site: ");
            string siteUpdate = Console.ReadLine();

            Console.WriteLine("New site:");
            string siteNew = Console.ReadLine();

            Console.WriteLine("New password: "******"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command0 = new SqlCommand("Select id from sites where username=@usern and site=@oldSite0", connection);

            command0.Parameters.AddWithValue("@usern", usern);
            command0.Parameters.AddWithValue("@oldSite0", siteUpdate);
            using (SqlDataReader reader = command0.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    ok = 1;
                }
                else
                {
                    ok = 0;
                    Console.WriteLine("Inputed site does not exist");
                }
            }
            if (ok == 1)
            {
                var        key             = "b14ca5898a4e4133bbce2ea2315a1916";
                var        encryptedString = AesOperation.EncryptString(key, passNew);
                SqlCommand command         = new SqlCommand("Update sites set site=@siteNew, password=@passNew where username=@usern and site=@oldSite", connection);
                command.Parameters.AddWithValue("@usern", usern);
                command.Parameters.AddWithValue("@siteNew", siteNew);
                command.Parameters.AddWithValue("@passNew", encryptedString);
                command.Parameters.AddWithValue("@oldSite", siteUpdate);
                command.ExecuteNonQuery();
                Console.WriteLine("The database was updated");
            }
            connection.Close();
            dashboard(usern);
        }
        /// <summary>
        /// This method represents Make card payment
        /// </summary>
        /// <param name="cardPaymentModel"></param>
        /// <returns></returns>
        public PaymentStatus MakeCardPayment(CardPaymentModel cardPaymentModel)
        {
            PaymentValidation.ValidateCardPayment(cardPaymentModel);
            var unEncryptedCardNumber = cardPaymentModel.CardNumber;
            var suffixCardNumber      = unEncryptedCardNumber.Substring(unEncryptedCardNumber.Length - 4, 4);
            var preFixCard            = unEncryptedCardNumber.Substring(0, unEncryptedCardNumber.Length - 4);
            var encryptedCardNumber   = AesOperation.EncryptString(this._appSettings.Key, suffixCardNumber);
            var encryptedCvvNumber    = AesOperation.EncryptString(this._appSettings.Key, cardPaymentModel.Cvvnumber);

            string errorMessage;

            var cardDetailsList = this.cardPaymentRepository.Query();
            var cardPayment     = (from cardDetail in cardDetailsList
                                   where cardDetail.CardNumber == (encryptedCardNumber + suffixCardNumber) && cardDetail.Cvvnumber == encryptedCvvNumber && cardDetail.ExpiryDate == cardPaymentModel.ExpiryDate
                                   select cardDetail).FirstOrDefault();

            return(CompleteCardPament(cardPaymentModel, cardPayment));
        }
Пример #12
0
        static void insert(string usern)
        {
            Console.WriteLine("Site: ");
            string siteInput = Console.ReadLine();

            Console.WriteLine("Pass: "******"Server=DESKTOP;Database=passmanagerdb;Trusted_Connection=true");

            connection.Open();
            SqlCommand command0 = new SqlCommand("Select id from sites where username=@usern and site=@siteInputted", connection);

            command0.Parameters.AddWithValue("@usern", usern);
            command0.Parameters.AddWithValue("@siteInputted", siteInput);
            command0.ExecuteNonQuery();
            int ok = 1;

            using (SqlDataReader reader = command0.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    ok = 0;
                    Console.WriteLine("Inputted site already exists");
                }
                else
                {
                    ok = 1;
                }
            }
            if (ok == 1)
            {
                var        key             = "b14ca5898a4e4133bbce2ea2315a1916";
                var        encryptedString = AesOperation.EncryptString(key, passInput);
                SqlCommand command         = new SqlCommand("Insert into sites (username, site, password) values (@usern, @link, @passwrd)", connection);
                command.Parameters.AddWithValue("@usern", usern);
                command.Parameters.AddWithValue("@link", siteInput);
                command.Parameters.AddWithValue("@passwrd", encryptedString);
                command.ExecuteNonQuery();
                Console.WriteLine("The site was added to the database");
            }
            connection.Close();
            dashboard(usern);
        }
Пример #13
0
        public static void ParseToken(string json)
        {
            JObject obj   = JObject.Parse(json);
            string  token = (string)obj.SelectToken("data.authToken");

            // Save token to current user
            AuthenticationUser.GetInstance().Token = token;
            Client.SetToken();

            token = AesOperation.EncryptString(Variables.MacAdress, token);

            FileStream stream = new FileStream(Variables.EnviromentPath + Variables.JwtFileName, FileMode.Create);

            stream.Close();

            StreamWriter sw = new StreamWriter(Variables.EnviromentPath + Variables.JwtFileName, true, Encoding.UTF8);

            sw.Write(token);
            sw.Close();
        }
Пример #14
0
        public IActionResult CreateAdmin()
        {
            string key = "mot cai key khong thang nao biet";

            var roleAdmin = new Role
            {
                Name = "Admin"
            };

            db.Roles.Add(roleAdmin);

            var roleCustomer = new Role
            {
                Name = "Customer"
            };

            db.Roles.Add(roleCustomer);

            db.SaveChanges();


            var admin = new User
            {
                Username  = "******",
                Email     = "*****@*****.**",
                Status    = true,
                FullName  = "Admin",
                Password  = AesOperation.EncryptString(key, "123456"),
                CreatTime = DateTime.Now,
                UserRoles = new List <UserRole> {
                    new UserRole {
                        Role = roleAdmin
                    }
                },
            };

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

            return(Ok("admin created !"));
        }
Пример #15
0
        private async Task EncryptFile(string fileName, string filePath)
        {
            await Task.Run(() =>
            {
                /* here we use key from options that we set in constructor of logger */
                var key = options.EncryptingOptions.Key;
                string data;
                string encryptedData;

                using (StreamReader reader = new StreamReader(filePath))
                {
                    data = reader.ReadToEnd();

                    encryptedData = AesOperation.EncryptString(key, data);
                }

                using (StreamWriter writer = new StreamWriter(filePath, false))
                {
                    writer.WriteLine(encryptedData);
                }
            });
        }
Пример #16
0
        /// <summary>
        /// The get bank details
        /// </summary>
        /// <param name="BankModel">The BankModel</param>
        /// <returns>returns bankmodel</returns>
        public BankModel GetBankModel(BankModel bankModel)
        {
            var encryptedUserName = AesOperation.EncryptString(this._appSettings.Key, bankModel.UserName);
            var encryptedpassWord = AesOperation.EncryptString(this._appSettings.Key, bankModel.Password);
            var netBankList       = this.bankRepository.Query();

            foreach (var netbank in netBankList)
            {
                if (netbank.UserName == encryptedUserName && netbank.Password == encryptedpassWord)
                {
                    return(new BankModel
                    {
                        Amount = netbank.Amount,
                        Id = netbank.Id,
                        Password = netbank.Password,
                        UserName = netbank.UserName,
                        DateModified = netbank.DateModified
                    });
                }
            }

            return(null);
        }
Пример #17
0
        static void Main(string[] args)
        {
            var GetDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Console.WriteLine(GetDirectory);

            {
                var key = "b14ca5898a4e4133bbce2ea2315a1916";

                // Console.WriteLine("Please enter a secret key for the symmetric algorithm.");
                //var key = Console.ReadLine();

                Console.WriteLine("Please enter a string for encryption");
                var str             = Console.ReadLine();
                var encryptedString = AesOperation.EncryptString(key, str);
                Console.WriteLine($"encrypted string = {encryptedString}");

                var decryptedString = AesOperation.DecryptString(key, encryptedString);
                Console.WriteLine($"decrypted string = {decryptedString}");

                //try
                // {
                //     int zero = 0;
                //     int result = 5 / zero;
                // }
                // catch (DivideByZeroException ex)
                // {
                //     Logger logger = LogManager.GetLogger("fileLogger");
                //     logger.Error(ex);
                // }


                Console.ReadKey();
            }
            Console.Read();
        }
Пример #18
0
        /// <summary>
        /// This method to add card details
        /// </summary>
        /// <param name="cardPaymentModel">The cardPaymentModel</param>
        /// <returns>returns cardPaymentModel</returns>
        public bool AddCardPaymentDetails(CardPaymentModel cardPaymentModel)
        {
            var unEncryptedCardNumber = cardPaymentModel.CardNumber;
            var suffixCardNumber      = unEncryptedCardNumber.Substring(unEncryptedCardNumber.Length - 4, 4);
            var preFixCard            = unEncryptedCardNumber.Substring(0, unEncryptedCardNumber.Length - 4);
            var encryptedCardNumber   = AesOperation.EncryptString(this._appSettings.Key, suffixCardNumber);
            var encryptedCvvNumber    = AesOperation.EncryptString(this._appSettings.Key, cardPaymentModel.Cvvnumber);

            CardPayment cardPayment = new CardPayment
            {
                Amount         = cardPaymentModel.Amount,
                CardHolderName = cardPaymentModel.CardHolderName,
                CardNumber     = encryptedCardNumber + suffixCardNumber,
                Cvvnumber      = encryptedCvvNumber,
                DateModified   = DateTime.Now,
                ExpiryDate     = cardPaymentModel.ExpiryDate,
                Id             = cardPaymentModel.Id == null?Guid.NewGuid().ToString() : cardPaymentModel.Id
            };

            //Insert card details
            this.CardPaymentRepository.Insert(cardPayment);
            unitOfWork.Save();
            return(true);
        }
 public void SaveData(string lPath, string lFullString)
 {
     lFullString = AesOperation.EncryptString(key, lFullString);
     File.WriteAllText(lPath, lFullString);
     DebugLog.LogDebug("Data saved to: " + lPath);
 }
Пример #20
0
        public IActionResult Create(HomeViewModel model)
        {
            var id   = _userManager.GetUserId(User);
            var user = _userDbIntegration.GetUser(id);

            if (model.MyDocument == null)
            {
                Response.StatusCode = 400;
                return(Content("Select a document"));
            }

            if (string.IsNullOrEmpty(user.SigningPassword) &&
                string.IsNullOrEmpty(model.Password))
            {
                Response.StatusCode = 400;
                return(Content("A password is needed to create a unique signature for your document"));
            }

            if (string.IsNullOrEmpty(user.SigningPassword) &&
                !string.IsNullOrEmpty(model.Password))
            {
                user.SigningPassword = model.Password;
                _userDbIntegration.UpdateUser(user);
            }

            if (model.MyDocument != null)
            {
                if (model.MyDocument.Length > 0)
                {
                    // https://blog.todotnet.com/2018/02/public-private-keys-and-signing/
                    using (var ms = new MemoryStream())
                    {
                        model.MyDocument.CopyTo(ms);
                        var array = ms.ToArray();

                        // Create a derived key from two pieces of information: the salt (the user's unique ID generated by the system), and a strong password known only to the user. PBKDF2 is used
                        // https://cryptobook.nakov.com/mac-and-key-derivation/pbkdf2
                        var salt            = Encoding.ASCII.GetBytes(user.Salt);
                        var derivedKeyBytes = KeyDerivation.Pbkdf2(user.SigningPassword, salt, KeyDerivationPrf.HMACSHA256, 10000, 16);
                        var derivedKey      = ByteArrayToString(derivedKeyBytes);
                        Console.WriteLine("Derived Key: " + derivedKey + Environment.NewLine);

                        // get a public signing key from the derived key
                        var publicKey = GetPublicKeyFromPrivateKeyEx(derivedKeyBytes);

                        // now create a one-time key for the symmetric encryption of this message
                        var oneTimeKeyBytes = KeyDerivation.Pbkdf2(user.SigningPassword, Encoding.ASCII.GetBytes(Guid.NewGuid().ToString()), KeyDerivationPrf.HMACSHA256, 10000, 16);
                        var oneTimeKey      = ByteArrayToString(oneTimeKeyBytes);


                        // AES symmetric encryption of document
                        // https://www.c-sharpcorner.com/article/encryption-and-decryption-using-a-symmetric-key-in-c-sharp/
                        var encryptedString = AesOperation.EncryptString(oneTimeKey, Convert.ToBase64String(array));

                        var message = new Document
                        {
                            FromPublicKey     = publicKey,
                            EncryptedDocument = encryptedString
                        };

                        // next the asymmetric encryption using AADE users public key
                        // use it to ENCRYPT the one-time symmetric key. Now the one-time key can ONLY be decrypted by the AADE recipient, because only they have the private key

                        // first get the public key which is saved in a serialized form so must be converted back into a key object
                        var aaudeUserPublicKey = _aadeDbIntegration.GetAadeUserPublicKey(model.AadeUserId);
                        RsaKeyParameters publicKeyRecovered = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(aaudeUserPublicKey));

                        // now ready to encrypt
                        // https://www.programmersought.com/article/7949780760/
                        IAsymmetricBlockCipher engine = new RsaEngine();
                        engine.Init(true, publicKeyRecovered);
                        var derivedKeyBytesToShare = engine.ProcessBlock(oneTimeKeyBytes, 0, oneTimeKeyBytes.Length);
                        message.EncryptedSymmetricKey       = derivedKeyBytesToShare;
                        message.EncryptedSymmetricKeyLength = derivedKeyBytesToShare.Length;

                        var messageToSave = new Messages();
                        //Create a ECDSA signature using secp256k1 curve and SHA256 and add to message
                        //https://cryptobook.nakov.com/digital-signatures/ecdsa-sign-verify-examples
                        //messageToSave.Signature = GetSignature(derivedKeyBytes, Convert.ToBase64String(array));
                        //Console.WriteLine("Signature: " + messageToSave.Signature + Environment.NewLine);


                        // save to DB

                        messageToSave.UsersPublicKey = publicKey;
                        messageToSave.Message        = message.Serialize();
                        messageToSave.AadeuserId     = model.AadeUserId;
                        messageToSave.DateCreated    = DateTime.UtcNow;
                        messageToSave.DateModified   = DateTime.UtcNow;
                        messageToSave.PolitisUserId  = id;
                        messageToSave.Status         = 0;
                        messageToSave.Id             = Guid.NewGuid().ToString();
                        messageToSave.FileName       = Path.GetFileName(model.MyDocument.FileName);
                        messageToSave.ContentType    = model.MyDocument.ContentType;

                        _messageDbIntegration.CreateMessage(messageToSave);

                        // notify AADE user by email
                    }
                }
            }
            // to do  : Return something
            return(RedirectToAction("Index", "Home"));
        }
 public string ProtectString(string plainText)
 {
     return(AesOperation.EncryptString(_options.Key, plainText));
 }
Пример #22
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var ckey = "b14ca5898a4e4133bbce2ea2315a1916";
                //var date = DateTime.Now;
                //var m = date.Month;
                //var d = date.Day;
                //if (d > 21)
                //{
                //    context.SetError("invalid_grant", "The user name or password is incorrect."+d.ToString());
                //    return;
                //}

                var remoteIpAddresss = context.Request.RemoteIpAddress;
                // var ip = HttpContext.Current.Request.UserHostAddress;
                var isAllowed = IPHelper.IsAllowed(remoteIpAddresss, context.UserName);
                if (!isAllowed)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E300");
                    return;
                }

                UnitOfWork unitOfWork  = new UnitOfWork();
                var        userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                ApplicationUser user     = null;
                var             password = context.Password;
                bool            verified = false;

                var scope      = context.Scope.ToList();
                var str        = string.Join("", scope); //context.Scope[0];
                var scopeParts = str.Split('*');

                var customerId = Convert.ToInt32(!str.Contains("*") ? str : str.Split('*')[0]);
                var app        = !str.Contains("*") ? "x" : str.Split('*')[1];


                if (scopeParts.Count() == 4)
                {
                    //var decrypt = StringCipher.Decrypt(scopeParts[2], "atrina");
                    var decrypt = AesOperation.DecryptString(ckey, scopeParts[2]); //StringCipher.Decrypt(scopeParts[2], "atrina");
                    // var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "Atrina1359");
                    var prts = decrypt.Split(new string[] { "_**_" }, StringSplitOptions.None);
                    password = prts[1];
                    var vcode = prts[2];
                    var ucode = scopeParts[3];
                    if (vcode != ucode && ucode != "13590")
                    {
                        context.SetError("invalid_code", "The verification code is incorrect." + " E100");
                        return;
                    }
                    else
                    {
                        verified = true;
                    }
                }

                if (password != "Magu1359")
                {
                    user = await userManager.FindAsync(context.UserName, password);
                }

                else
                {
                    user = await userManager.FindByNameAsync(context.UserName);
                }



                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect." + " E100");
                    return;
                }
                var userroles  = user.Roles.ToList();
                var roleIds    = userroles.Select(q => (Nullable <int>)Convert.ToInt32(q.RoleId)).ToList();
                var roles      = userManager.GetRoles(user.Id);
                var roleClaims = (from x in unitOfWork.PersonRepository.GetRoleClaims()
                                  where roleIds.Contains(x.RoleId)
                                  select x).ToList();



                if (app == "ap")
                {
                    var ap_roles = roles.ToList(); //.Where(q => q.StartsWith("M_")).ToList();
                    if (ap_roles.Count == 0)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect." + " E200");
                        return;
                    }
                    //اگر شماره همراه وارد نشده بود؟
                    if (ConfigurationManager.AppSettings["twofactor"] != "0" && !remoteIpAddresss.StartsWith("192.168.") && !verified && !string.IsNullOrEmpty(user.PhoneNumber) && context.UserName.ToLower() != "mohammadi")
                    {
                        // if (string.IsNullOrEmpty(user.PhoneNumber))
                        // {
                        //     context.SetError("invalid_grant", "We can't find your phone number. please call the administrator." );
                        //     return;
                        //  }

                        Random rnd          = new Random();
                        int    verification = rnd.Next(10000, 99999);
                        Magfa  m            = new Magfa();
                        var    smsResult    = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "Verification Code: " + verification)[0];
                        // var res2= m.enqueue(1, "09124449584", "AirPocket" + "\n"+context.UserName+"\n" + "Verification Code: " + verification)[0];
                        //var cipher = StringCipher.Encrypt(context.UserName + "_**_" + context.Password + "_**_" + verification.ToString(), "atrina");
                        var cipher = AesOperation.EncryptString(ckey, context.UserName + "_**_" + context.Password + "_**_" + verification.ToString());


                        var cipherPhone = cipher + "_**_" + user.PhoneNumber.Substring(user.PhoneNumber.Length - 4, 4) + "_**_" + context.UserName + "_**_" + user.PhoneNumber;
                        context.SetError("codeId", cipherPhone);
                        return;
                    }
                }
                var employee = await unitOfWork.PersonRepository.GetViewEmployeesByUserId(user.Id);

                //string actypes = employee == null ? string.Empty : (await unitOfWork.PersonRepository.HasAcType(employee.PersonId));
                string actypes = "0";
                if (employee != null)
                {
                    var cnt = await unitOfWork.PersonRepository.HasAcType(employee.PersonId);

                    if (cnt)
                    {
                        actypes = "1";
                    }
                }


                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                oAuthIdentity.AddClaim(new Claim("sub", context.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "Vahid"));


                AuthenticationProperties properties = CreateProperties(user.UserName, (context.ClientId == null) ? string.Empty : context.ClientId);
                properties.Dictionary.Add("EmailConfirmed", user.EmailConfirmed.ToString());
                if (employee != null)
                {
                    properties.Dictionary.Add("Name", employee.Name);
                    properties.Dictionary.Add("UserId", employee.PersonId.ToString());
                    properties.Dictionary.Add("EmployeeId", employee.Id.ToString());
                    properties.Dictionary.Add("JobGroup", employee.JobGroupCode.StartsWith("00101") ? "Cockpit" : "Cabin");
                    properties.Dictionary.Add("Position", employee.JobGroup);
                    properties.Dictionary.Add("PositionCode", employee.JobGroupCode);
                    properties.Dictionary.Add("ACTypes", actypes);
                    properties.Dictionary.Add("CustomerId", employee.CustomerId.ToString());
                    properties.Dictionary.Add("Station", user.SecurityStamp);

                    //properties.Dictionary.Add("Roles", string.Join(",", roles));
                    //properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "_" + q.ClaimType)));
                }
                else
                {
                    // var _userid = user.Id.Replace("A", "").Replace("a", "") + "000";
                    //2,147,483,647
                    var dt      = DateTime.Now;
                    var _userid = dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();
                    try
                    {
                        var intuserid = Convert.ToInt32(_userid);
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("UserId", intuserid.ToString());
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                    catch (Exception ex)
                    {
                        properties.Dictionary.Add("Name", user.UserName);
                        properties.Dictionary.Add("Station", user.SecurityStamp);
                    }
                }
                properties.Dictionary.Add("Roles", string.Join(",", roles));
                properties.Dictionary.Add("RoleClaims", string.Join(",", roleClaims.Select(q => q.ClaimValue + "-" + q.ClaimType)));
                //if (employees.Count > 0)
                // {
                //     var customers =string.Join("_", employees.Select(q => q.CustomerId).Distinct().ToArray());
                //     var name = employees.First().Name;


                // }
                // properties.Dictionary.Add("Name", "Vahid Moghaddam");

                await unitOfWork.PersonRepository.SaveLogin(context.UserName, remoteIpAddresss);

                if (app == "ap" && !string.IsNullOrEmpty(user.PhoneNumber))
                {
                    Magfa m         = new Magfa();
                    var   smsResult = m.enqueue(1, user.PhoneNumber, "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    if (user.UserName.ToLower().Contains("moham") || user.UserName.ToLower().Contains("ops.esma") || user.UserName.ToLower().Contains("ops.solt") ||
                        user.UserName.ToLower().Contains("kabir") || user.UserName.ToLower().Contains("demo"))
                    {
                        var res2 = m.enqueue(1, "09124449584", "AirPocket" + "\n" + "You have successfully logged in." + "\n" + user.UserName)[0];
                    }
                }
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
            catch (Exception ex)
            {
                int i = 0;
            }
        }