示例#1
0
        public async Task <ActionResult> Register(User user)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            bool admincheck = false;


            using (App_Context db = new App_Context())
            {
                if (db.Users.ToList().Count == 0)
                {
                    admincheck = true;
                }

                var existUser = db.Users.Where(i => i.Username == user.Username).ToList();
                var count     = existUser.Count;
                if (count > 0)
                {
                    ViewData["UserExist"] = existUser;
                    return(View(user));
                }

                bool isValidPass = Regex.IsMatch(user.Password, passPattern);
                if (!isValidPass && user.Username != "god")
                {
                    ViewData["InvalidPass"] = existUser;
                    return(View(user));
                }

                if (count == 0)
                {
                    var  salt = Password.GetSalt();
                    var  hash = Password.Hash(user.Password, salt);
                    Role r    = new Role();
                    if (admincheck == true)
                    {
                        r = db.Roles.Find(1);
                    }
                    else
                    {
                        r = db.Roles.Find(2);
                    }

                    User u = new User
                    {
                        Username   = user.Username,
                        Password   = Convert.ToBase64String(hash),
                        Salt       = Convert.ToBase64String(salt),
                        Firstname  = user.Firstname,
                        Lastname   = user.Lastname,
                        Phone      = user.Phone,
                        Address    = user.Address,
                        City       = user.City,
                        Email      = user.Email,
                        PostalCode = user.PostalCode,
                        Role       = r
                    };
                    db.Users.Add(u);
                    db.Entry(r).State = System.Data.Entity.EntityState.Unchanged;
                    db.SaveChanges();
                    ViewData["Success"] = existUser;
                    await emailHandler.RegistrationEmail(user.Email, user.Firstname, user.Username, user.Password);
                }
            }
            return(View());
        }