Ejemplo n.º 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();
 }
Ejemplo n.º 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());
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 11
0
 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;
 }
        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");
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        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 }));
        }
Ejemplo n.º 15
0
        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();
                }
            }
        }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
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"));
        }
Ejemplo n.º 19
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);
            }
        }
 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;
                    }
                }
            }



        }
Ejemplo n.º 22
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);
                }
            }
        }
Ejemplo n.º 23
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));
        }
Ejemplo n.º 24
0
        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 });
        }
Ejemplo n.º 25
0
        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));
        }
Ejemplo n.º 26
0
        public ActionResult Login(FormCollection collection)
        {
            //SimpleCrypto used to create salts and hashes.
            ICryptoService cryptoService = new PBKDF2();
            Exception e = new Exception();

            var member = new MemberModel();

            try
            {

                member.Member.Add(new Member { UserName = "******" });

                string username = collection["username"];
                string password = collection["password"];
                string salt = cryptoService.GenerateSalt(); ;

                if (username == "" || password == "")
                {
                    e.Source = "Du har inte fyllt i fälten för lösenord eller användarnamn.";
                    throw e;
                }
                else
                {
                    string hashedPassword = cryptoService.Compute(password.ToString(), salt);
                    Session["hash"] = member.Member.Find(0).UserName;
                }

                if (password != "")
                {

                }
                else
                {
                    Session["hash"] = "";
                }

                if (username.Contains("kalle"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    e.Source = "rrr";
                    throw e;
                }
            }
            catch
            {

                TempData["errorData"] = e.Source;
                return RedirectToAction("Index", "Member");
            }
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
        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();
            }
        }
Ejemplo n.º 29
0
        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;
        }
Ejemplo n.º 30
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 bool IsValid(string password, string username)
        {
            ICryptoService cryptoService = new PBKDF2();
            bool isValid = false;

            var gebruiker = _gebruikerRepository.FindByUsername(username);
            if (gebruiker != null)
            {
                //var encryptedpassword = cryptoService.Compute(password, gebruiker.Salt);
                //if (cryptoService.Compare(gebruiker.Wachtwoord, encryptedpassword))
                //{
                //    isValid = true;
                //}
                if (BCrypt.Net.BCrypt.CheckPassword(password, gebruiker.Wachtwoord))
                {
                    isValid = true;
                }
            }

            return isValid;
        }
 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;
 }
Ejemplo n.º 33
0
        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);
        }
Ejemplo n.º 34
0
        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);
        }
Ejemplo n.º 35
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;
        }
Ejemplo n.º 36
0
        public ActionResult CreateUser(MultipleModel.UserIndexVM reg)
        {
            if (ModelState.IsValid)
            {
                if (db.Users.Where(u => u.Email == reg.Register.EmailAddress).Any())
                {
                    reg.Error = true;
                    var errorList = new List<string>();
                    string message = "Email " + reg.Register.EmailAddress + " is already existing";
                    errorList.Add(message);
                    reg.Message = errorList;

                    TempData["UserIndexTD"] = reg;
                    return RedirectToAction("UserIndex", new { id = reg.SectionID });
                }
                else
                {
                    using (var db = new LibraryDbContext())
                    {
                        var newUser = db.Users.Create();
                        string pin = RandomPassword.Generate(6, PasswordGroup.Lowercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
                        var crypto = new PBKDF2();
                        var encrypPin = crypto.Compute(pin);

                        newUser.Pincode = encrypPin;
                        newUser.PincodeSalt = crypto.Salt;

                        newUser.Email = reg.Register.EmailAddress;
                        newUser.Role = "student";
                        newUser.CreatedAt = DateTime.Now;
                        newUser.UpdatedAt = DateTime.Now;
                        db.Users.Add(newUser);
                        var newStudent = db.Students.Create();
                        var section = db.Sections.FirstOrDefault(s => s.Id == reg.SectionID);
                        newStudent.SectionId = section.Id;
                        newStudent.FirstName = reg.Register.FirstName;
                        newStudent.MiddleInitial = reg.Register.MiddleInitial;
                        newStudent.LastName = reg.Register.LastName;
                        newStudent.Gender = reg.Register.Gender;
                        newStudent.CreatedAt = DateTime.Now;
                        newStudent.UpdatedAt = DateTime.Now;

                        db.Students.Add(newStudent);
                        db.SaveChanges();

                        SMTP smtp = new SMTP();
                        smtp.SendEmal(newUser.Email, pin);

                        reg.Error = false;
                        var errorList = new List<string>();
                        string message = "You have successfully added a user(" + newUser.Email + ")";
                        errorList.Add(message);
                        reg.Message = errorList;
                        TempData["UserIndexTD"] = reg;

                        return RedirectToAction("UserIndex", new { id = reg.SectionID });
                    }
                }

            }
            else
            {
                reg.Error = true;
                reg.Message = CustomValidationMessage.GetErrorList(ViewData.ModelState);
            }
            TempData["UserIndexTD"] = reg;
            return RedirectToAction("UserIndex", new { id = reg.SectionID });
        }
Ejemplo n.º 37
0
        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");
        }
Ejemplo n.º 38
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");
        }
        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 PasswordBasedSecurityProvider()
 {
     crypto = new PBKDF2();
 }
Ejemplo n.º 41
0
        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");
        }
Ejemplo n.º 42
0
        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);
        }