Exemple #1
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);
        }
        public void SaveUser()
        {
            string password = "******";
            var crypto = new PBKDF2();
            string enryptPass = crypto.Compute(password);
            string Email = "*****@*****.**";
            string City = "WWA";
            string Address = "Sik 41/12";
            bool IsAdmin = false;
            string Name = "Name";
            string Surname = "Surname";
            string ipAddress = "102.154.12.12";
            string ZipCode = "12-222";
            string Password = enryptPass;
            string PasswordSalt = crypto.Salt;

            var user = new Users(Name, Surname, Email, Password, City, Address, ZipCode, IsAdmin,
                PasswordSalt, ipAddress);

            var userGuid = user.ID;

            Assert.IsNotNull(user);
            _userRepository.Save(user);
            Assert.AreNotEqual(userGuid,user.ID);
        }
        // https://github.com/shawnmclean/SimpleCrypto.net
        public static bool IsPasswordValid(string password, string storedPasswordHash, string salt)
        {
            ICryptoService cryptoService = new PBKDF2();
            string hashedPassword2 = cryptoService.Compute(password, salt);

            return cryptoService.Compare(storedPasswordHash, hashedPassword2);
        }
 public ActionResult Registration(log_in user)
 {
     if (ModelState.IsValid)
     {
         using (var db = new login_simpleEntities())
         {
             var crypt = new SimpleCrypto.PBKDF2();
             int size = crypt.SaltSize;
             var cryptPass = crypt.Compute(user.pass);
             log_in newUser = new log_in()
             {
                 email = user.email,
                 pass = cryptPass,
                 passsalt = crypt.Salt
             };
             db.log_in.Add(newUser);
             try
             {
                 db.SaveChanges();
             }
             catch(Exception e)
             {
                 Debug.Print("Here is the error! " + e.Message);
             }
         }
     }
     return View();
 }
Exemple #5
0
 public ActionResult Registration(log_in user)
 {
     if (ModelState.IsValid)
     {
         using (var db = new login_simpleEntities())
         {
             var    crypt     = new SimpleCrypto.PBKDF2();
             int    size      = crypt.SaltSize;
             var    cryptPass = crypt.Compute(user.pass);
             log_in newUser   = new log_in()
             {
                 email    = user.email,
                 pass     = cryptPass,
                 passsalt = crypt.Salt
             };
             db.log_in.Add(newUser);
             try
             {
                 db.SaveChanges();
             }
             catch (Exception e)
             {
                 Debug.Print("Here is the error! " + e.Message);
             }
         }
     }
     return(View());
 }
Exemple #6
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));
        }
Exemple #7
0
        private static void EncryptPassword(ref User user, string password)
        {
            var crypto     = new SimpleCrypto.PBKDF2();
            var encrypPass = crypto.Compute(password);

            user.Password     = encrypPass;
            user.PasswordSalt = crypto.Salt;
        }
Exemple #8
0
        public static string GetPassword(string password, string passwordsalt)
        {
            string data   = string.Empty;
            var    crypto = new SimpleCrypto.PBKDF2();

            data = crypto.Compute(password, passwordsalt);
            return(data);
        }
        public SaltHashPair CreateLoginWithPassword(string username, string password)
        {
            var crypto = new PBKDF2();
            var salt = crypto.GenerateSalt();
            var hashedPassword = crypto.Compute(password, salt);

            return new SaltHashPair(salt, hashedPassword);
        }
        public static Tuple<string, string> HashPassword(string password)
        {
            ICryptoService cryptoService = new PBKDF2();

            string salt = cryptoService.GenerateSalt();
            string hashedPassword = cryptoService.Compute(password, salt);

            return new Tuple<string, string>(hashedPassword, salt);
        }
        public ActionResult ChangePassword(string newPassword)
        {
            var crypto = new PBKDF2();
            string encryptPass = crypto.Compute(newPassword);
            string passwordSalt = crypto.Salt;
            _myAccountLogic.ChangePassword(User.Identity.Name, encryptPass,passwordSalt);

            return RedirectToAction("AccountDetails");
        }
Exemple #12
0
        /// <summary>
        ///     Salt and encript the given password.
        /// </summary>
        /// <param name="password"> </param>
        private void EncryptPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password");

            var cryptoService = new PBKDF2();

            EncryptedPassword = cryptoService.Compute(password);
            Salt = cryptoService.Salt;
        }
 public bool FormIsValid(string name, string password)
 {
     var crypto = new PBKDF2();
     bool result = false;
     var user = GetUserByName(name);
     if (user != null && user.Password == crypto.Compute(password, user.PasswordSalt))
         result = true;
     return result;
 }
Exemple #14
0
        public void Create(User model)
        {
            ClearCache();

            var crypto = new SimpleCrypto.PBKDF2();

            model.PasswordSalt = crypto.GenerateSalt();

            model.Password = crypto.Compute(model.Password,model.PasswordSalt);

            provider.Create(model);
        }
 public override void Validate(string userName, string password)
 {
     using (var context = new AF_Context())
     {
         const string pepper = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";
         ICryptoService cryptoService = new PBKDF2();
         try
         {
             User u = context.Users.FirstOrDefault(c => c.Login == userName);
             if (u == null)
                 throw new SecurityTokenException("Wrong Username or Password");
             bool verified = cryptoService.Compare(cryptoService.Compute(cryptoService.Compute(password, u.Salt), pepper), u.Password);
             if (!verified)
                 throw new SecurityTokenException("Wrong Username or Password");
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
        static void Main(string[] args)
        {

            string pass = "";
            int id=0;
            ICryptoService cryptoService = new PBKDF2();
            const string pepper = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";

            Console.WriteLine("Select user by id:");
            if (int.TryParse(Console.ReadLine(),out id))
            {
                using (var context = new AF_Context())
                {
                    try
                    {
                        User user = context.Users.First(u => u.UserId == id);
                        if (user != null)
                        {
                            while (string.IsNullOrEmpty(pass))
                            {
                                Console.WriteLine("Input Password:");
                                pass = Console.ReadLine();
                            }
                            user.Salt = cryptoService.GenerateSalt();
                            user.Password = cryptoService.Compute(cryptoService.Compute(pass, user.Salt), pepper);

                        }
                        context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }



        }
Exemple #17
0
        /// <summary>
        /// Cadastra uma pessoa no banco de dados, dada as informacoes.
        /// </summary>
        /// <param name="Cpf">cpf/login da pessoa</param>
        /// <param name="Senha">senha do usuario</param>
        /// <param name="Nome">nome da pessoa</param>
        /// <param name="Telefone">telefone da pessoa</param>
        /// <param name="Email">email da pessoa</param>
        /// <param name="Curso">curso da pessoa</param>
        /// <param name="Matricula">matricula da pessoa</param>
        /// <param name="Pergunta">pergunta a ser feita caso esqueca a senha</param>
        /// <param name="Resposta">resposta da pergunta</param>
        public void InsertPerson(String Cpf, String Senha, String Nome, String Telefone, String Email, String Curso, String Matricula, String Pergunta, String Resposta)
        {
            var crypto        = new SimpleCrypto.PBKDF2(); // Criptografia
            var encryptPass   = crypto.Compute(Senha);     // Senha criptografada
            var encryptSalt   = crypto.Salt;               // Salt da senha
            var encryptAnswer = crypto.Compute(Resposta);  // Resposta criptografada
            var respsalt      = crypto.Salt;               // Salt da resposta

            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.Cnnval("DataBase")))
            {
                User newUser = new User {
                    cpf = Cpf, senha = encryptPass, senhasalt = encryptSalt, nome = Nome, telefone = Telefone, email = Email, curso = Curso, matricula = Matricula, pergunta = Pergunta, resposta = encryptAnswer, respostasalt = respsalt
                };

                var lista = connection.Query <User>("dbo.getUser @cpf", new { cpf = Cpf }).ToList();

                if (lista.Count == 0) // Se nao houver nenhum usuario cadastrado com o cpf, realiza o cadastro.
                {
                    connection.Execute("dbo.userRegister @Cpf, @Senha, @Senhasalt, @Nome, @Telefone, @Email, @Curso, @Matricula, @Pergunta, @Resposta, @Respostasalt", newUser);
                }
            }
        }
Exemple #18
0
        public ActionResult Edit([Bind(Include = "email,password,newpass,confpass")] UserPassChange upc)
        {
            var crypto = new SimpleCrypto.PBKDF2();

            upc.username = this.User.Identity.Name;
            User user = db.Users.Find(upc.username);

            upc.password = crypto.Compute(upc.password, user.salt);
            if (upc.password == user.password)
            {
                user.password        = crypto.Compute(upc.newpass);
                user.salt            = crypto.Salt;
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                Session["smsg"] = "Password Updated.";
                genLog("PassChange", "Password Updated", user.username);
                return(RedirectToAction("Success"));
            }

            ModelState.AddModelError("password", "Wrong Password");
            upc.password = "";
            return(View(upc));
        }
        public ActionResult ActivateAccount2(MultipleModel.AuthModelVM request)
        {
            if (ModelState.IsValid)
            {
                using (var db = new LibraryDbContext())
                {
                    MultipleModel.AuthModelVM vm = new MultipleModel.AuthModelVM();
                    vm.UserModel = db.Users.SingleOrDefault(u => u.Id == request.UserModel.Id);
                    var crypto     = new SimpleCrypto.PBKDF2();
                    var encrypPass = crypto.Compute(request.ActivationModel1.Password);

                    vm.UserModel.PasswordSalt   = crypto.Salt;
                    vm.UserModel.Password       = encrypPass;
                    vm.UserModel.SecretQuestion = request.ActivationModel1.SecretQuestion;
                    vm.UserModel.SecretAnswer   = request.ActivationModel1.SecretAnswer;
                    vm.UserModel.Status         = true;
                    vm.UserModel.Deleted        = false;
                    vm.UserModel.UpdatedAt      = DateTime.UtcNow;

                    vm.UserModel.Student.Birthday       = request.ActivationModel1.Birthday;
                    vm.UserModel.Student.StudentAddress = new LibraryDbContext.StudentAddressModel
                    {
                        ZipCode  = request.ActivationModel1.ZipCode, Address1 = request.ActivationModel1.Address1,
                        Address2 = request.ActivationModel1.Address2, City = request.ActivationModel1.City,
                        Country  = request.ActivationModel1.Country, CreatedAt = DateTime.UtcNow,
                    };
                    db.Entry(vm.UserModel).State = EntityState.Modified;
                    db.SaveChanges();

                    var ctx         = Request.GetOwinContext();
                    var authManager = ctx.Authentication;
                    authManager.SignOut("ApplicationCookie");

                    var loginVM = new MultipleModel.LoginModelVM();
                    loginVM.Error = false;
                    var    errorList = new List <string>();
                    string message   = "You have successfully activated your account. Please log in";
                    errorList.Add(message);
                    loginVM.Message     = errorList;
                    TempData["LoginTD"] = loginVM;

                    return(RedirectToAction("Login"));
                }
            }
            request.Error              = true;
            request.Message            = CustomValidationMessage.GetErrorList(ViewData.ModelState);
            TempData["UserActivation"] = request;
            return(RedirectToAction("ActivateAccount2", new { id = request.UserModel.Id }));
        }
        public void AddUser(User user)
        {
            var crypto = new PBKDF2();
            user.Password = crypto.Compute(user.Password);
            user.PasswordSalt = crypto.Salt;

            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(user);
                    transaction.Commit();
                }
            }
        }
        public ActionResult ActivateAccount(MultipleModel.LoginModelVM login)
        {
            if(ModelState.IsValid)
            {
                using (var db = new LibraryDbContext())
                {
                    var emailCheck = db.Users.Where(u => u.Email == login.ActivationModel.Email).ToList();
                    if(emailCheck[0] !=null)
                    {
                        var email = db.Users.SingleOrDefault(u => u.Email == login.ActivationModel.Email);
                        var crypto = new PBKDF2();
                        if ((email.Password != null) && (email.PasswordSalt != null))
                        {
                            login.Error = true;
                            ModelState.AddModelError("", "The account is already activated");
                            return View("Login", login);
                        }
                        else if ((email != null) && (email.Pincode == crypto.Compute(login.ActivationModel.PinCode, email.PincodeSalt)))
                        {
                            var ctx = Request.GetOwinContext();
                            var authManager = ctx.Authentication;

                            var identity = new ClaimsIdentity(new[] {
                            new Claim(ClaimTypes.Name, "acc_act"),
                            new Claim(ClaimTypes.Role, "activation")
                        }, "ApplicationCookie");

                            authManager.SignIn(identity);
                            return RedirectToAction("ActivateAccount2", new { id = email.Id });
                        }
                        else if ((email != null) && (email.Pincode != login.ActivationModel.PinCode))
                        {
                            login.Error = true;
                            ModelState.AddModelError("", "Incorrect pin entered");
                            return View("Login", login);
                        }
                    }
                    else if (emailCheck[0] == null)
                    {
                        login.Error = true;
                        ModelState.AddModelError("", "The account does not exist");
                    }

                }
            }
            login.Error = true;
            return View("Login", login);
        }
Exemple #22
0
        // Test User/Pass combination
        private bool IsValid(string username, string password)
        {
            var  crypto  = new SimpleCrypto.PBKDF2();
            bool isValid = false;

            User user = db.Users.Find(username);

            if (user != null)
            {
                if (user.password == crypto.Compute(password, user.salt))
                {
                    isValid = true;
                }
            }
            return(isValid);
        }
Exemple #23
0
        public ActionResult Reset([Bind(Include = "username,newpass,confpass")] UserPassChange upc)
        {
            var  crypto = new SimpleCrypto.PBKDF2();
            User user   = db.Users.Find(upc.username);

            upc.password   = crypto.Compute(upc.newpass);
            user.password  = upc.password;
            user.forString = "";
            user.salt      = crypto.Salt;

            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();

            genLog("Reset", "Password Reset", user.username);
            Session["smsg"] = "Your password has been reset.";

            return(RedirectToAction("Success"));
        }
Exemple #24
0
        /// <summary>
        /// Verifica se a senha passada é a mesma cadastrada no banco de dados.
        /// </summary>
        /// <param name="login"> login a ser procurado no banco de dados</param>
        /// <param name="password">senha a ser verificada</param>
        /// <returns>True caso seja a mesma senha, falso caso nao</returns>
        public Boolean GetPassword(String login, String password)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.Cnnval("DataBase")))
            {
                var lista = connection.Query <User>("dbo.getUser @cpf", new { cpf = login }).ToList();

                var crypto = new SimpleCrypto.PBKDF2(); // Criptografia

                Boolean validate = false;

                if (lista.Count > 0)
                {
                    if (lista[0].senha == crypto.Compute(password, lista[0].senhasalt))
                    {
                        validate = true;
                    }
                }

                return(validate);
            }
        }
Exemple #25
0
 public string ChangePassword(string strpass, string strnewpass, string memberid, string email) {
     MembersTableAdapters.MembersTableAdapter taMember = new MembersTableAdapters.MembersTableAdapter();
     if (taMember.GetDataByMemberID(memberid).Count > 0) {
         DataRow dtMember = taMember.GetDataByMemberID(memberid).Rows[0];
         ValidateLogin valLogin = new ValidateLogin();
         if (valLogin.isValid(email, strpass))
         {
             ICryptoService cryptoService = new PBKDF2();
             //save this salt to the database
             string PasswordSalt = cryptoService.GenerateSalt();
             //save this hash to the database
             string hashedPassword = cryptoService.Compute(strnewpass);
             taMember.UpdatePassword(hashedPassword, PasswordSalt, DateTime.Now, Convert.ToInt32(dtMember["AutoID"]));
             return "valid";
         }
         else
         {
             return "invalid";
         }
     }
     taMember.Dispose();
     return "invalid";
     
 } 
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                bool isNotExist = myAccountLogic.FindDuplicateUser(model.Email);

                if (isNotExist)
                {
                    var crypto = new PBKDF2();
                    string enryptPass = crypto.Compute(model.Password);
                    string passwordSalt = crypto.Salt;
                    string address = model.Street + " " + model.HouseNumber;
                    string ipaddress = System.Web.HttpContext.Current.Request.UserHostAddress;

                    if (model.FlatNumber != null)
                    {
                        address += "/" + model.FlatNumber;
                    }

                    if (myAccountLogic.IsSuccessedCreatedUser(model, enryptPass, address, false, passwordSalt, ipaddress))
                    {
                        return RedirectToAction("Login");
                    }
                    else
                    {
                       ModelState.AddModelError("", "Wystąpił problem z serwerem, proszę spróbować ponownie.");
                        return View("Register");
                    }
                }
                ModelState.AddModelError("", String.Format("Użytkownik o adresie email {0} już istnieje", model.Email));
                return View("Register");
            }
            ModelState.AddModelError("", "Wprowadzono błędne wartości");
            return View("Register");
        }
 private bool ValidPass(string email, string password)
 {
     var crypt = new PBKDF2();
     bool isValid = false;
     using (var db = new login_simpleEntities())
     {
         var user = db.log_in.FirstOrDefault(u => u.email == email);
         string deCryptPass = crypt.Compute(password, user.passsalt);
         bool validation = user.pass == deCryptPass;
         if (user != null)
         {
             if (validation)
             {
                 isValid = true;
             }
         }
     }
     return isValid;
 }
        public void USers()
        {
            var conn = new NHibernateConnection();
            var userRepo = new UserRepository(conn);
            string password = "******";

            var crypto = new PBKDF2();
            string enryptPass = crypto.Compute(password);

            string Email = "*****@*****.**";
            string City = "WWA";
            string FlatNumber = "1";
            string HouseNumber = "5";
            bool IsAdmin = false;
            string Name = "Name";
            string Surname = "Surname";
            string Street = "Street";
            string ZipCode = "12-222";
            string Password = enryptPass;
            string PasswordSalt = crypto.Salt;

            //var user = new Users(Name, Surname, Email, Password, City, Street, HouseNumber, FlatNumber, ZipCode, IsAdmin,
            //    PasswordSalt);

            //userRepo.Save(user);

            Users fromDb = userRepo.Get(Email);
            //Assert.AreEqual(user,fromDb);

            bool isValid = true;

            var login = new LoginModel
            {
                Email = "*****@*****.**",
                Password = "******"
            };

            bool result = CryptoHelpers.IsValid(fromDb, login.Password);

            Assert.AreEqual(isValid, result);
        }
        public ActionResult Login(MultipleModel.LoginModelVM user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new LibraryDbContext())
                {
                    var crypto = new SimpleCrypto.PBKDF2();
                    var emailCheck = db.Users.FirstOrDefault(u => u.Email == user.AuthModel.Email);
                    var getPasswordSalt = db.Users.Where(u => u.Email == user.AuthModel.Email).Select(u => u.PasswordSalt);

                    if ((emailCheck != null) && (getPasswordSalt != null) && (emailCheck.Deleted == false) && (emailCheck.Status == true))
                    {
                        var materializePasswordSalt = getPasswordSalt.ToList();
                        var passwordSalt = materializePasswordSalt[0];
                        var encryptedPassword = crypto.Compute(user.AuthModel.Password, passwordSalt);

                        if (user.AuthModel.Email != null && emailCheck.Password == encryptedPassword)
                        {
                            var name = emailCheck.Student.FirstName;

                            var getEmail = db.Users.Where(u => u.Id == emailCheck.Id).Select(u => u.Email);
                            var materializeEmail = getEmail.ToList();
                            var email = materializeEmail[0];

                            var getRole = db.Users.Where(u => u.Id == emailCheck.Id).Select(u => u.Role);
                            var materializeRole = getRole.ToList();
                            var role = materializeRole[0];

                            var identity = new ClaimsIdentity(new[] {
                            new Claim(ClaimTypes.Name, name),
                            new Claim(ClaimTypes.Email, email),
                            new Claim(ClaimTypes.Role, role)
                        }, "ApplicationCookie");

                            var ctx = Request.GetOwinContext();
                            var authManager = ctx.Authentication;
                            authManager.SignIn(identity);

                            if (emailCheck.Role == "administrator")
                            {
                                return RedirectToAction("GradesIndex", "Admin");
                            }
                            else
                            {
                                return RedirectToAction("Index", "Auth");
                            }
                        }
                        else
                        {
                            user.Error = true;
                            ModelState.AddModelError("", "Invalid email or password");
                        }
                    }
                    else if((emailCheck != null) && (emailCheck.Status == false) && (emailCheck.Deleted == false) )
                    {
                        user.Error = true;
                        ModelState.AddModelError("", "Please activate the account");
                    }
                    else if(emailCheck == null || ((emailCheck.Deleted == true) && (emailCheck.Status == false)))
                    {
                        user.Error = true;
                        ModelState.AddModelError("", "Account does not exist");
                    }
                }

            }
            user.Error = true;
            return View(user);
        }
        public ActionResult ActivateAccount2(MultipleModel.AuthModelVM request)
        {
            if(ModelState.IsValid)
            {
                using (var db = new LibraryDbContext())
                {
                    MultipleModel.AuthModelVM vm = new MultipleModel.AuthModelVM();
                    vm.UserModel = db.Users.SingleOrDefault(u => u.Id == request.UserModel.Id);
                    var crypto = new SimpleCrypto.PBKDF2();
                    var encrypPass = crypto.Compute(request.ActivationModel1.Password);

                    vm.UserModel.PasswordSalt = crypto.Salt;
                    vm.UserModel.Password = encrypPass;
                    vm.UserModel.SecretQuestion = request.ActivationModel1.SecretQuestion;
                    vm.UserModel.SecretAnswer = request.ActivationModel1.SecretAnswer;
                    vm.UserModel.Status = true;
                    vm.UserModel.Deleted = false;
                    vm.UserModel.UpdatedAt = DateTime.Now;

                    vm.UserModel.Student.Birthday = request.ActivationModel1.Birthday;
                    vm.UserAddressModel = db.UserAddresses.Create();
                    vm.UserAddressModel.UserId = vm.UserModel.Id;
                    vm.UserAddressModel.ZipCode = request.ActivationModel1.ZipCode;
                    vm.UserAddressModel.Address1 = request.ActivationModel1.Address1;
                    vm.UserAddressModel.Address2 = request.ActivationModel1.Address2;
                    vm.UserAddressModel.City = request.ActivationModel1.City;
                    vm.UserAddressModel.Country = request.ActivationModel1.Country;
                    vm.UserAddressModel.CreatedAt = DateTime.Now;
                    db.UserAddresses.Add(vm.UserAddressModel);
                    db.Entry(vm.UserModel).State = EntityState.Modified;
                    db.SaveChanges();

                    var ctx = Request.GetOwinContext();
                    var authManager = ctx.Authentication;
                    authManager.SignOut("ApplicationCookie");

                    var loginVM = new MultipleModel.LoginModelVM();
                    loginVM.Error = false;
                    var errorList = new List<string>();
                    string message = "You have successfully activated your account. Please log in";
                    errorList.Add(message);
                    loginVM.Message = errorList;
                    TempData["LoginTD"] = loginVM;

                    return RedirectToAction("Login");
                }
            }
            request.Error = true;
            request.Message = CustomValidationMessage.GetErrorList(ViewData.ModelState);
            TempData["UserActivation"] = request;
            return RedirectToAction("ActivateAccount2", new { id = request.UserModel.Id });
        }
        public ActionResult Login(MultipleModel.LoginModelVM user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new LibraryDbContext())
                {
                    var crypto          = new SimpleCrypto.PBKDF2();
                    var emailCheck      = db.Users.FirstOrDefault(u => u.Email == user.AuthModel.Email);
                    var getPasswordSalt = db.Users.Where(u => u.Email == user.AuthModel.Email).Select(u => u.PasswordSalt);

                    if ((emailCheck != null) && (getPasswordSalt != null) && (emailCheck.Deleted == false) && (emailCheck.Status == true))
                    {
                        var materializePasswordSalt = getPasswordSalt.ToList();
                        var passwordSalt            = materializePasswordSalt[0];
                        var encryptedPassword       = crypto.Compute(user.AuthModel.Password, passwordSalt);

                        if (user.AuthModel.Email != null && emailCheck.Password == encryptedPassword)
                        {
                            var name = emailCheck.Student.FirstName + " " + emailCheck.Student.MiddleInitial + ". " + emailCheck.Student.LastName;

                            var getEmail         = db.Users.Where(u => u.Id == emailCheck.Id).Select(u => u.Email);
                            var materializeEmail = getEmail.ToList();
                            var email            = materializeEmail[0];

                            var getRole         = db.Users.Where(u => u.Id == emailCheck.Id).Select(u => u.Role);
                            var materializeRole = getRole.ToList();
                            var role            = materializeRole[0];

                            var identity = new ClaimsIdentity(new[] {
                                new Claim(ClaimTypes.Name, name),
                                new Claim(ClaimTypes.Email, email),
                                new Claim(ClaimTypes.Role, role),
                                new Claim(ClaimTypes.NameIdentifier, emailCheck.Id.ToString())
                            }, "ApplicationCookie");

                            var ctx         = Request.GetOwinContext();
                            var authManager = ctx.Authentication;
                            authManager.SignIn(identity);

                            if (emailCheck.Role == "administrator")
                            {
                                return(RedirectToAction("GradesIndex", "Admin"));
                            }
                            else
                            {
                                return(RedirectToAction("Books", "User"));
                            }
                        }
                        else
                        {
                            user.Error = true;
                            ModelState.AddModelError("", "Invalid email or password");
                        }
                    }
                    else if ((emailCheck != null) && (emailCheck.Status == false) && (emailCheck.Deleted == false))
                    {
                        user.Error = true;
                        ModelState.AddModelError("", "Please activate the account");
                    }
                    else if (emailCheck == null || ((emailCheck.Deleted == true) && (emailCheck.Status == false)))
                    {
                        user.Error = true;
                        ModelState.AddModelError("", "Account does not exist");
                    }
                }
            }
            user.Error = true;
            return(View(user));
        }
Exemple #32
0
        public ActionResult Edit([Bind(Include = "email,password,newpass,confpass")] UserPassChange upc)
        {
            var crypto = new SimpleCrypto.PBKDF2();

                upc.username = this.User.Identity.Name;
                User user = db.Users.Find(upc.username);
                upc.password = crypto.Compute(upc.password,user.salt);
                if (upc.password == user.password) {
                    user.password = crypto.Compute(upc.newpass);
                    user.salt = crypto.Salt;
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                    Session["smsg"] = "Password Updated.";
                    genLog("PassChange", "Password Updated", user.username);
                    return RedirectToAction("Success");
                }

                ModelState.AddModelError("password", "Wrong Password");
                upc.password = "";
            return View(upc);
        }
        public ActionResult Create([Bind(Include = "UserName,UserPhone,UserEmail,UserPassword,UserPasswordConfirm,UserFullName,IAmOwner")] User user)
        {
            ModelState.Remove("UserGroupId");
            ModelState.Remove("UserPasswordSalt");
            if (ModelState.IsValid)
            {
                var crypto = new SimpleCrypto.PBKDF2();

                User suser = new User();
                User vusr = db.Users.Where(u=>u.UserName == user.UserName).FirstOrDefault();
                if(vusr != null)
                {
                    ModelState.AddModelError("UserName", "Acest nume de utilizator exista deja. Va rog alegeti altul!");
                    return View("Register", user);
                } 
                suser.UserName = user.UserName;
                if (user.UserPhone != null)
                    if (IsPhoneNumber(user.UserPhone))
                    {
                        suser.UserPhone = user.UserPhone;
                    }
                    else
                    {
                        ModelState.AddModelError("UserPhone", "Campul Numar de telefon trebuie sa respecte formatul unui numar de telefon!");
                        return View("Register", user);
                    }
                User vemail = db.Users.Where(u => u.UserEmail == user.UserEmail).FirstOrDefault();
                if (vemail != null)
                {
                    ModelState.AddModelError("UserEmail", "Aceasta adresa de email este deja utilizata. Va rog alegeti alta!");
                    return View("Register", user);
                }
                suser.UserEmail = user.UserEmail;
                suser.UserFullName = user.UserFullName;
                if(user.UserPassword.Length>20)
                {
                    ModelState.AddModelError("UserPassword", "Campul Parola trebuie sa aiba maxim 20 de caractere!");
                    return View("Register", user);
                }
                suser.UserPassword = crypto.Compute(user.UserPassword);
                suser.UserPasswordConfirm = suser.UserPassword;
                suser.UserPasswordSalt = crypto.Salt;
                string owner = user.IAmOwner ? "Proprietar" : "Jucator";
                suser.UserGroupID = db.UserGroups.Where(e => e.UserGroupName == owner).FirstOrDefault().IDUserGroup;
                suser.UserGroup = db.UserGroups.Where(e => e.IDUserGroup == suser.UserGroupID).FirstOrDefault();

                try
                {
                    db.Users.Add(suser);
                    db.SaveChanges();
                    FormsAuthentication.SetAuthCookie(suser.UserName, false);
                }
                catch(System.Data.Entity.Validation.DbEntityValidationException er)
                {
                    foreach (var validationErrors in er.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
                            
                        }
                    }
                    return View("Edit", user);
                }
                return RedirectToAction("Index", "Home");
            }

            ViewBag.UserGroupID = new SelectList(db.UserGroups, "IDUserGroup", "UserGroupName", user.UserGroupID);
            return View("Register",user);
        }
        public ActionResult ForgotPass(String adresademail)
        {
            User usr = db.Users.Where(u => u.UserEmail == adresademail).FirstOrDefault();
            if (usr!=null)
            {
                String newPass = RandomString(8);
                var crypto = new SimpleCrypto.PBKDF2();
                usr.UserPassword = crypto.Compute(newPass);
                usr.UserPasswordConfirm = usr.UserPassword;
                usr.UserPasswordSalt = crypto.Salt;

                usr.UserGroup = db.UserGroups.Where(u => u.IDUserGroup == usr.UserGroupID).FirstOrDefault();

                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException er)
                {
                    foreach (var validationErrors in er.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }

                Utilities.EmailSend(adresademail, "Schimbare parola WhereToPLay", "Salut, noua ta parola pentru userul "+usr.UserName+" este: "+ newPass);
                Utilities.SmsSend(usr.UserPhone, "Salut, noua ta parola pentru userul " + usr.UserName + " este: " + newPass);
                ModelState.AddModelError("", "Un mail/sms cu noua parola v-a fost trimis pe adresa de email "+ adresademail);
                return View("Login");
            }
            else
            {
                ModelState.AddModelError("", "Adresa de email nu a fost gasita!");
                return View();
            }
        }
Exemple #35
0
        public ActionResult Reset([Bind(Include = "username,newpass,confpass")] UserPassChange upc)
        {
            var crypto = new SimpleCrypto.PBKDF2();
            User user = db.Users.Find(upc.username);

            upc.password = crypto.Compute(upc.newpass);
            user.password = upc.password;
            user.forString = "";
            user.salt = crypto.Salt;

            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();

            genLog("Reset","Password Reset", user.username);
            Session["smsg"] = "Your password has been reset.";

            return RedirectToAction("Success");
        }
Exemple #36
0
        // Test User/Pass combination
        private bool IsValid(string username, string password)
        {
            var crypto = new SimpleCrypto.PBKDF2();
            bool isValid = false;

            User user = db.Users.Find(username);

            if (user != null)
            {
                if (user.password == crypto.Compute(password, user.salt))
                {
                    isValid = true;
                }
            }
            return isValid;
        }
Exemple #37
0
 public virtual bool Match(string password)
 {
     var cryptoService = new PBKDF2();
     return String.CompareOrdinal(cryptoService.Compute(password, Salt), EncryptedPassword) == 0;
 }
    protected void btn_newPassword_Click(object sender, EventArgs e)
    {
        ICryptoService cryptoService = new PBKDF2();
        string password = txtPassword.Text;

        //save this salt to the database
        string PasswordSalt = cryptoService.GenerateSalt();

        //save this hash to the database
        string hashedPassword = cryptoService.Compute(password);

        MembersTableAdapters.MembersTableAdapter taMember = new MembersTableAdapters.MembersTableAdapter();
        taMember.UpdatePassword(hashedPassword, PasswordSalt, DateTime.Now, Convert.ToInt32(hfAutoID.Value));
        taMember.Dispose();

        string strMsg = "<p class=\"header2\">Password Changed</p><p>Now you can login with your new password.</p>";
        strMsg += "<p style=\"text-align:right; margin-bottom:1px;\"><input type=button value=\"Log-In Now\" onclick=\"self.location.href='Login.aspx'\"></p><hr>";
        litMsgBody.Text = strMsg;
    }
        public ActionResult Edit([Bind(Include = "IDUser,UserName,UserPhone,UserEmail,PasswordChange,PasswordChangeConfirm,UserFullName")] User user)
        {
            User editedUser = db.Users.Where(u=>u.IDUser == user.IDUser).FirstOrDefault();
            if (user.UserPhone != null)
                if (IsPhoneNumber(user.UserPhone))
                {
                    editedUser.UserPhone = user.UserPhone;
                }
                else
                {
                    ModelState.AddModelError("UserPhone", "Campul Numar de telefon trebuie sa respecte formatul unui numar de telefon!");
                    return View("Edit", user);
                }
            editedUser.UserEmail = user.UserEmail;
            editedUser.UserFullName = user.UserFullName;
            editedUser.UserGroup = db.UserGroups.Where(u=>u.IDUserGroup == editedUser.UserGroupID).FirstOrDefault();

            if (user.PasswordChange!="" && user.PasswordChange != null)
            {
                var crypto = new SimpleCrypto.PBKDF2();
                if (user.PasswordChange.Length > 20)
                {
                    ModelState.AddModelError("PasswordChange", "Campul Parola trebuie sa aiba maxim 20 de caractere!");
                    return View("Edit", user);
                }
                editedUser.UserPassword = crypto.Compute(user.PasswordChange);
                editedUser.UserPasswordConfirm = editedUser.UserPassword;
                editedUser.UserPasswordSalt = crypto.Salt;
            }
            else
            {
                editedUser.UserPasswordConfirm = editedUser.UserPassword;
                ModelState.Remove("PasswordChange");
                ModelState.Remove("PasswordChangeConfirm");
            }

            try
            {
                if (db.Entry(editedUser).State == EntityState.Modified)
                {
                    db.SaveChanges();
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException er)
            {
                foreach (var validationErrors in er.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);

                    }
                }
                return View("Edit", user);
            }

            return RedirectToAction("Index", "Home");
        }
        public byte ValidateLogin(string usrName, string pass)
        {
            var crypto = new SimpleCrypto.PBKDF2();
            var usr = db.Users.Where(e => e.UserName == usrName).FirstOrDefault();
            byte isValid = 0;

            if(usr!=null && !usr.Hidden)
            { 
                if (usr.UserPassword == crypto.Compute(pass, usr.UserPasswordSalt))
                {
                    isValid = 3;
                }
            }
            else
            {
                if (usr == null) isValid = 2;
                else
                    if(usr.Hidden) isValid = 1;
            }
            return isValid;
        }
        public ActionResult Index()
        {
            _session.CreateSQLQuery("delete orderdetails").ExecuteUpdate();
            _session.CreateSQLQuery("delete shoppingcarts").ExecuteUpdate();
            _session.CreateSQLQuery("delete productimages").ExecuteUpdate();
            _session.CreateSQLQuery("delete orders").ExecuteUpdate();
            _session.CreateSQLQuery("delete  users").ExecuteUpdate();
            _session.CreateSQLQuery("delete products").ExecuteUpdate();
            _session.CreateSQLQuery("delete orderstate").ExecuteUpdate();
            _session.CreateSQLQuery("delete deliverytypes").ExecuteUpdate();
            _session.CreateSQLQuery("delete categories").ExecuteUpdate();
            _session.CreateSQLQuery("delete  manufacturers").ExecuteUpdate();

            #region OrderStates

            var orderState1 = new OrderState("Nowe zamówienie");
            var orderState2 = new OrderState("W trakcie realizacji");
            var orderState3 = new OrderState("Przekazano do doręczenia");

            #endregion

            #region manufacturers

            var manufacturer = new Manufacturers("Electronic Arts");
            var manufacturer2 = new Manufacturers("Ubisoft");
            var manufacturer3 = new Manufacturers("CD Projekt RED");
            var manufacturer4 = new Manufacturers("Blizzard");
            var manufacturer5 = new Manufacturers("SEGA");
            var manufacturer6 = new Manufacturers("RockstarGames");

            #endregion

            #region catregories

            var category1 = new Categories("Akcja", "");
            var category2 = new Categories("MMORpg", "Massively multiplayer online role-playing game");
            var category3 = new Categories("Sport", "");
            var category4 = new Categories("Klasyka", "");
            var category5 = new Categories("Pozostałe", "");

            #endregion

            #region products

            var productList = new List<Products>
            {
                new Products("Fifa", "", randomDecimal(5, 150), category3,
                    manufacturer, 15, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Need for speed", "", randomDecimal(5, 150), category3,
                    manufacturer, 15, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("The sims", "", randomDecimal(5, 150), category5,
                    manufacturer, 15, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Battlefield", "", randomDecimal(5, 150), category4,
                    manufacturer, 15, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Medal of honor", "", randomDecimal(5, 150), category4,
                    manufacturer, 15, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Watch dogs", "", randomDecimal(5, 150), category1,
                    manufacturer2, 5, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Far cry", "", randomDecimal(5, 150), category1,
                    manufacturer2, 12, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Heroes V", "", randomDecimal(5, 150), category4,
                    manufacturer2, 1, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Assassins Creed", "", randomDecimal(5, 150), category5,
                    manufacturer2, 4, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Wiedźmin", "", randomDecimal(5, 150), category1,
                    manufacturer3, 25, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Total war: Rome II", "", randomDecimal(5, 150), category1,
                    manufacturer4, 13, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Company of heroes", "", randomDecimal(5, 150), category4,
                    manufacturer4, 9, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("GTA", "", randomDecimal(5, 150), category5,
                    manufacturer5, 13, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), ""),
                new Products("Max payne", "", randomDecimal(5, 150), category4,
                    manufacturer5, 9, Common.GetRandomBool(), Common.GetRandomBool(),
                    Common.GetRandomBool(), "")
            };

            #endregion

            #region productImages

            string filename = Server.MapPath(Url.Content("~/FrontEnd/img/empty_gallery.png"));
            byte[] bytes = System.IO.File.ReadAllBytes(filename);
            var products = _productRepo.GetAll();

            #endregion

            #region users

            const string password = "******";
            var crypto = new PBKDF2();
            string enryptPass = crypto.Compute(password);
            string passwordSalt = crypto.Salt;

            const string email = "*****@*****.**";
            const string city = "Warszawa";
            const string address = "Sik 41/12";
            const bool isAdmin = false;
            const string userName = "******";
            const string surname = "Surname";
            const string ipAddress = "102.154.12.12";
            const string zipCode = "12-222";

            var user = new Users(userName, surname, email, enryptPass, city, address, zipCode, isAdmin,
                passwordSalt, ipAddress);

            var user2 = new Users(userName, surname, "*****@*****.**", enryptPass, "Łódź", address, zipCode, true,
                passwordSalt, ipAddress);

            var user3 = new Users(userName, surname, "*****@*****.**", enryptPass, "Katowice", address, zipCode,
                isAdmin,
                passwordSalt, ipAddress);

            #endregion

            #region deliveryTypes

            var deliveryType = new DeliveryTypes("Poczta", Convert.ToDecimal(8.99));
            var deliveryType2 = new DeliveryTypes("Kurier", Convert.ToDecimal(12.00));
            var deliveryType3 = new DeliveryTypes("Obiór osobisty", Convert.ToDecimal(0.00));

            #endregion

            _catRepo.Save(category1);
            _catRepo.Save(category2);
            _catRepo.Save(category3);
            _catRepo.Save(category4);
            _catRepo.Save(category5);

            _orderStateRepository.Save(orderState1);
            _orderStateRepository.Save(orderState2);
            _orderStateRepository.Save(orderState3);

            _manuRepo.Save(manufacturer);
            _manuRepo.Save(manufacturer2);
            _manuRepo.Save(manufacturer3);
            _manuRepo.Save(manufacturer5);
            _manuRepo.Save(manufacturer4);
            _manuRepo.Save(manufacturer6);

            _userRepo.Save(user);
            _userRepo.Save(user2);
            _userRepo.Save(user3);
            foreach (var item in productList)
            {
                item.Description =
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sem mi, efficitur eget nisi vitae, facilisis efficitur massa. Sed rhoncus vestibulum velit, sit amet sodales nisl semper id. Praesent non nisi vitae orci facilisis dapibus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sem mi, efficitur eget nisi vitae, facilisis efficitur massa. Sed rhoncus vestibulum velit, sit amet sodales nisl semper id. Praesent non nisi vitae orci facilisis dapibus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sem mi, efficitur eget nisi vitae, facilisis efficitur massa. Sed rhoncus vestibulum velit, sit amet sodales nisl semper id. Praesent non nisi vitae orci facilisis dapibus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam auctor.";
                item.ShortDescription =
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sem mi, efficitur eget nisi vitae, facilisis efficitur massa. Sed rhoncus vestibulum velit, sit amet sodales nisl semper id. Praesent non nisi vitae orci facilisis dapibus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam auctor.";
                _productRepo.Save(item);
            }
            foreach (var productse in products)
                _productImagesRepository.Save(new ProductImages(filename, bytes, productse));

            _deliveryRepo.Save(deliveryType);
            _deliveryRepo.Save(deliveryType2);
            _deliveryRepo.Save(deliveryType3);

            Random rnd = new Random();
            for (int i = 0; i < 150; i++)
            {
                System.Threading.Thread.Sleep(10);
                var order1 = new Orders(user, DateTime.Now.AddDays(-rnd.Next(1, 365)),
                    Convert.ToDecimal(rnd.Next(50, 400)), deliveryType, orderState1);
                var order2 = new Orders(user2, DateTime.Now.AddDays(-rnd.Next(1, 365)),
                    Convert.ToDecimal(rnd.Next(50, 400)), deliveryType, orderState2);
                var order3 = new Orders(user3, DateTime.Now.AddDays(-rnd.Next(1, 365)),
                    Convert.ToDecimal(rnd.Next(50, 400)), deliveryType, orderState2);
                _ordersRepository.Save(order1);
                _ordersRepository.Save(order2);
                _ordersRepository.Save(order3);
                var random = rnd.Next(1, productList.Count);
                var orderDetails = new OrderDetails(order1, productList[random], rnd.Next(1, 5),
                    productList[random].Price);
                var orderDetails2 = new OrderDetails(order2, productList[random], rnd.Next(1, 5),
                    productList[random].Price);
                var orderDetails3 = new OrderDetails(order3, productList[random], rnd.Next(1, 5),
                    productList[random].Price);

                _orderDetailsRepository.Save(orderDetails);
                _orderDetailsRepository.Save(orderDetails2);
                _orderDetailsRepository.Save(orderDetails3);
            }

            string[] myCookies = Request.Cookies.AllKeys;
            foreach (string cookie in myCookies)
            {
                Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
            }

            FormsAuthentication.SignOut();

            return RedirectToAction("index", "Home");
        }
        protected override void Seed(library_prototype.DAL.LibraryDbContext context)
        {
            var    crypto     = new SimpleCrypto.PBKDF2();
            var    encrypPass = crypto.Compute("rodnerraymundo");
            string pin        = RandomPassword.Generate(6, PasswordGroup.Lowercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
            var    cryptoPin  = new SimpleCrypto.PBKDF2();
            var    encrypPin  = crypto.Compute(pin);

            var grades = new List <library_prototype.DAL.LibraryDbContext.GradesModel>
            {
                new library_prototype.DAL.LibraryDbContext.GradesModel
                {
                    Grade    = "Administrator", CreatedAt = DateTime.UtcNow,
                    Sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel>
                    {
                        context.Sections.SingleOrDefault(s => s.Section == "Developer")
                    }
                }
            };

            grades.ForEach(g => context.Grades.AddOrUpdate(g));

            var sections = new List <library_prototype.DAL.LibraryDbContext.SectionsModel>
            {
                new library_prototype.DAL.LibraryDbContext.SectionsModel
                {
                    Section = "Developer", CreatedAt = DateTime.UtcNow,
                }
            };

            sections.ForEach(s => context.Sections.AddOrUpdate(s));

            var addresses = new List <library_prototype.DAL.LibraryDbContext.StudentAddressModel>
            {
                new DAL.LibraryDbContext.StudentAddressModel
                {
                    Address1 = "Lumang Dito", Address2 = "Banda Rito", City = "Pineapple City",
                    Country  = "Philippines", CreatedAt = DateTime.UtcNow, ZipCode = 1234
                },
                new DAL.LibraryDbContext.StudentAddressModel
                {
                    Address1  = "Matuwid na Daan", Address2 = "Pork Doon", City = "Apple City", Country = "Philippines",
                    CreatedAt = DateTime.UtcNow, ZipCode = 5678
                },
                new DAL.LibraryDbContext.StudentAddressModel
                {
                    Address1  = "Dating Dito", Address2 = "Banda Doon", City = "Pineapple City", Country = "Philippines",
                    CreatedAt = DateTime.UtcNow, ZipCode = 9012
                }
            };

            addresses.ForEach(a => context.StudentAddresses.AddOrUpdate(a));
            context.SaveChanges();

            var accounts = new List <library_prototype.DAL.LibraryDbContext.UserModel>
            {
                new library_prototype.DAL.LibraryDbContext.UserModel
                {
                    Email     = "*****@*****.**",
                    Password  = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt,
                    Role      = "administrator", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo",
                    CreatedAt = DateTime.UtcNow, Status = true,
                    Student   = new DAL.LibraryDbContext.StudentModel
                    {
                        FirstName      = "Rodner", MiddleInitial = "A", LastName = "Raymundo", Status = true, Birthday = DateTime.UtcNow.AddYears(-20),
                        ContactNumber  = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male",
                        StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 9012),
                        Section        = context.Sections.SingleOrDefault(s => s.Section == "Developer")
                    }
                },
                new library_prototype.DAL.LibraryDbContext.UserModel
                {
                    Email     = "*****@*****.**",
                    Password  = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt,
                    Role      = "staff", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo",
                    CreatedAt = DateTime.UtcNow, Status = true,
                    Student   = new DAL.LibraryDbContext.StudentModel
                    {
                        FirstName      = "Kevin", MiddleInitial = "G", LastName = "Tiu", Status = true, Birthday = DateTime.UtcNow.AddYears(-20),
                        ContactNumber  = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male",
                        StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 5678),
                        Section        = context.Sections.SingleOrDefault(s => s.Section == "Developer")
                    }
                },
                new library_prototype.DAL.LibraryDbContext.UserModel
                {
                    Email     = "*****@*****.**",
                    Password  = encrypPass, PasswordSalt = crypto.Salt, Pincode = encrypPin, PincodeSalt = cryptoPin.Salt,
                    Role      = "student", SecretQuestion = "Who are you?", SecretAnswer = "rodnerraymundo",
                    CreatedAt = DateTime.UtcNow, Status = true,
                    Student   = new DAL.LibraryDbContext.StudentModel
                    {
                        FirstName      = "Jake", MiddleInitial = "S", LastName = "Arroyo", Status = true, Birthday = DateTime.UtcNow.AddYears(-15),
                        ContactNumber  = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male",
                        StudentAddress = context.StudentAddresses.SingleOrDefault(a => a.ZipCode == 1234),
                        Section        = context.Sections.SingleOrDefault(s => s.Section == "Developer")
                    }
                },
            };

            accounts.ForEach(a => context.Users.AddOrUpdate(a));
            try
            {
                context.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                                                       validationErrors.Entry.Entity.ToString(),
                                                       validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }

            var publishers = new List <DAL.LibraryDbContext.PublisherModel>
            {
                new DAL.LibraryDbContext.PublisherModel
                {
                    PublisherName = "Kewl Publisher", CreatedAt = DateTime.UtcNow,
                }
            };

            publishers.ForEach(p => context.Publishers.AddOrUpdate(p));

            var subjects = SubjectSeeder.Subject();

            subjects.ForEach(s => context.Subjects.AddOrUpdate(s));

            context.SaveChanges();

            var books = new List <library_prototype.DAL.LibraryDbContext.BookModel>
            {
                new library_prototype.DAL.LibraryDbContext.BookModel
                {
                    Title     = "Discrete Mathematics for Kids", ISBN = "978-971-95546-0-8", Copyright = new DateTime(2012, 1, 1),
                    NoOfPages = 215, Price = 165.00, Quantity = 2, Synopsis = "This book is for students who failed Discrete Mathematics",
                    Borrow    = true, CreatedAt = DateTime.UtcNow, Volume = "1",
                    Subject   = context.Subjects.SingleOrDefault(s => s.CallNo == 001),
                    Publisher = context.Publishers.SingleOrDefault(p => p.PublisherName == "Kewl Publisher")
                }
            };

            books.ForEach(b => context.Books.AddOrUpdate(b));

            var authors = new List <library_prototype.DAL.LibraryDbContext.AuthorModel>
            {
                new library_prototype.DAL.LibraryDbContext.AuthorModel
                {
                    LastName = "Gonzales", FirstName = "George", MiddleInitial = "A",
                }
            };

            authors.ForEach(a => context.Authors.AddOrUpdate(a));

            var booksauthors = new List <library_prototype.DAL.LibraryDbContext.BookAuthorModel>
            {
                new library_prototype.DAL.LibraryDbContext.BookAuthorModel
                {
                    Book   = context.Books.SingleOrDefault(b => b.Title == "Discrete Mathematics for Kids"),
                    Author = context.Authors.SingleOrDefault(a => a.LastName == "Gonzales"),
                }
            };

            booksauthors.ForEach(b => context.BooksAuthors.AddOrUpdate(b));

            context.SaveChanges();

            var emailCredential = new List <DAL.LibraryDbContext.EmailCredentialModel>
            {
                new DAL.LibraryDbContext.EmailCredentialModel
                {
                    Host          = "smtp.sendgrid.net",
                    Username      = "******",
                    Password      = CustomEncrypt.Encrypt("bg5PSAAPof9L2TW"),
                    CreatedAt     = DateTime.UtcNow,
                    Deleted       = false,
                    EmailMessages = new List <DAL.LibraryDbContext.EmailMessageModel>
                    {
                        new DAL.LibraryDbContext.EmailMessageModel
                        {
                            Type      = "notification", From = "*****@*****.**", Subject = "Book Deadline",
                            Body      = "This is a reminder that your borrowed book's deadline is coming near. We urge you to return the book on or before it's deadline. Thank you",
                            CreatedAt = DateTime.UtcNow, Deleted = false,
                        },
                        new DAL.LibraryDbContext.EmailMessageModel
                        {
                            Type = "accountpincode", From = "*****@*****.**", Subject = "Account Activation",
                            Body = "You have received because you are registered at Santo Tomas de Villanueva Parochial School Web and Android Online Public Access Catalog System. Otherwise please disregard this email.", CreatedAt = DateTime.UtcNow, Deleted = false,
                        }
                    }
                }
            };

            emailCredential.ForEach(e => context.EmailCredentials.AddOrUpdate(e));

            context.SaveChanges();

            /*var information = new List<library_prototype.DAL.LibraryDbContext.StudentModel>
             * {
             *  new DAL.LibraryDbContext.StudentModel
             *  {
             *      FirstName = "Rodner", MiddleInitial = "Y", LastName = "Raymundo", Status = true,
             *      ContactNumber = "09176508082", CreatedAt = DateTime.UtcNow, Gender = "male",
             *  }
             * };
             * information.ForEach(i => context.Students.AddOrUpdate(i));
             */
            /*
             * var sections = new List<library_prototype.DAL.LibraryDbContext.SectionsModel>
             * {
             *  new DAL.LibraryDbContext.SectionsModel
             *  {
             *      Section = "Administrator", CreatedAt = DateTime.UtcNow,
             *  },
             *
             *  new DAL.LibraryDbContext.SectionsModel
             *  {
             *      Section = "Co-Administrator", CreatedAt = DateTime.UtcNow,
             *  }
             * };
             * var nonStudentGroup = context.Grades.FirstOrDefault(g => g.Grade == "Non-student");
             * sections.ForEach(s => nonStudentGroup.Sections.Add(s));
             * context.SaveChanges();
             */
            base.Seed(context);
        }