Exemple #1
0
        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <returns></returns>
        public static OracleConnection GetConnection(string key)
        {
            OracleConnection conn      = null;
            string           isEncrypt = Normal.ParseString(ConfigurationManager.AppSettings["Encrypt"]);

            isEncrypt = isEncrypt.ToLower();
            if (!isEncrypt.Equals("false"))
            {
                isEncrypt = "true";
            }
            string ConnectString = "";

            if (isEncrypt.Equals("true"))
            {
                ConnectString = PwdUtil.DesDecrypt(ConfigurationManager.ConnectionStrings[key].ConnectionString);
            }
            else
            {
                ConnectString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
            }
            try
            {
                conn = new OracleConnection(ConnectString);
            }
            catch (Exception e)
            {
                throw new DatabaseException(ConnectString + "\n" + e.Message);
            }
            return(conn);
        }
        public async Task <IActionResult> Reset(ResetViewModel model)
        {
            //token not useable, start over
            var result = await ValidateResetTokenAsync(model.Token);

            if (!result.success)
            {
                return(View("Forgot", new ForgotViewModel()));
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = result.user !;                        //result.user cannot be null when result.success == true
            var salt = PwdUtil.NewSalt();
            var hash = PwdUtil.Hash(model.Password !, salt); //model.Password cannot be null if ModelState.IsValid == true

            user.Hash = hash;
            user.Salt = salt;

            await DbContext.SaveChangesAsync();

            await SignInAsync(user);

            return(RedirectFromLogin());
        }
Exemple #3
0
        public ActionResult RegisterUser()
        {
            var flag = false;

            try
            {
                var model = new UserInfoModel()
                {
                    Account           = Normal.ListStr(Request["Account"]),
                    Password          = Normal.CheckPoint(PwdUtil.MD5Encrypt(Request["Password"])),
                    Email             = Normal.ListStr(Request["Email"]),
                    Name              = Normal.ListStr(Request["Name"]),
                    Sex               = Normal.ListStr(Request["Sex"]),
                    BirthDay          = Normal.ListStr(Request["BirthDay"]),
                    HomeTown          = Normal.ListStr(Request["HomeTown"]),
                    Marriage          = Normal.ListStr(Request["Marriage"]),
                    TheLatter         = Normal.ListStr(Request["TheLatter"]),
                    Position          = Normal.ListStr(Request["Position"]),
                    Company           = Normal.ListStr(Request["Company"]),
                    WorkingConditions = Normal.ParseInt(Request["WorkingConditions"]),
                    InterestIn        = Normal.ListStr(Request["InterestIn"]),
                    QQ = Normal.ListStr(Request["QQ"]),
                    IntroduceMyself = Normal.ListStr(Request["IntroduceMyself"])
                };
                var personService = new PersonService();
                flag = personService.AddUserInfo(model);
                return(flag ? Content("修改成功!") : Content("修改失败!"));
            }
            catch (Exception)
            {
                return(Content("修改失败!"));
            }
        }
        public async Task <IActionResult> Confirm(ConfirmEnrollViewModel model)
        {
            if (!EnableSelfEnrollment)
            {
                throw new NotSupportedException("Self-enrollment is disabled.");
            }

            //Model.Token is an encrypted token
            //valid token must:
            //1. decrypt successfully
            //2. has not expired
            //
            //then allow creating a new Data.Models.User entity.

            //token not useable, start over
            if (string.IsNullOrEmpty(model.Token) || !ValidateEnrollmentToken(model.Token, out string?email))
            {
                return(View("Enroll", new EnrollViewModel()));
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //test if requested username exists
            if (DbContext.Users.Where(x => x.Name == model.Username).Any())
            {
                ModelState.AddModelError("Username", $"\"{model.Username}\" is already in use.");
                ModelState.AddModelError("", $"\"{model.Username}\" is already in use. Please select something else. Your username does not have to match your email address.");
                return(View(model));
            }
            //create user and log in
            var salt = PwdUtil.NewSalt();
            var hash = PwdUtil.Hash(model.Password !, salt); //model.Password can't be null if ModelState.IsValid == true
            var user = new Data.Models.User()
            {
                Name  = model.Username !, //Username can't be null if ModelState.IsValid == true
                Email = email !,          //email cannot be null if ValidateEnrollmentToken returned true
                Hash  = hash,
                Salt  = salt
            };

            try
            {
                DbContext.Add(user);
                await DbContext.SaveChangesAsync();
                await SignInAsync(user);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failed to create user: {model.Username}.");
                ModelState.AddModelError("", $"Unable to create user: {model.Username}.");
                ModelState.AddModelError("", e.Message);
                return(View(model));
            }
            return(RedirectFromLogin(null));
        }
Exemple #5
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: dotnet run password");
                return;
            }

            string pwd  = args[0];
            var    salt = PwdUtil.NewSalt();
            var    hash = PwdUtil.Hash(pwd, salt);

            Console.WriteLine($"Hash: {Convert.ToBase64String(hash)}");
            Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");
        }
        public async Task <IActionResult> New(NewUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var salt = PwdUtil.NewSalt();
            var hash = PwdUtil.Hash(model.Password !, salt); //Password can't be null of ModelState.IsValid.

            var user = new Data.Models.User()
            {
                Name      = model.Username !, //Username can't be null if ModelState.IsValid == true.
                Email     = model.Email !,    //Email can't be null if ModelState.IsValid == true.
                GivenName = string.IsNullOrEmpty(model.GivenName) ? null : model.GivenName,
                Surname   = string.IsNullOrEmpty(model.Surname) ? null : model.Surname,
                Hash      = hash,
                Salt      = salt
            };

            var roles = model.Roles
                        .Where(x => x.Checked)
                        .Select(x => new Data.Models.UserRole()
            {
                RoleId = x.Id, UserId = user.UserId
            });

            try
            {
                DbContext.Add(user);
                foreach (var role in roles)
                {
                    DbContext.Add(role);
                }
                await DbContext.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Exception inserting new Data.Models.User.");
                ModelState.AddModelError("", e.Message);
                return(View(model));
            }

            return(RedirectToAction("Edit", new { id = user.UserId, created = true }));
        }
Exemple #7
0
        public ActionResult Login()
        {
            PersonService service  = new PersonService();
            var           account  = Normal.ListStr(Request["Account"]);
            var           password = Normal.CheckPoint(PwdUtil.MD5Encrypt(Request["Password"]));
            var           id       = service.Login(account, password);

            if (id > 0)
            {
                var cookie = new HttpCookie("PH_User");
                cookie.Expires = DateTime.Now.AddMonths(1);
                cookie.Values.Add("User_Account", account);
                cookie.Values.Add("User_Id", id.ToString());
                Response.AppendCookie(cookie);
                return(Content("True"));
            }
            return(Content("False"));
        }
        /// <summary>
        /// 取得数据库连接字符串
        /// </summary>
        /// <param name="connName">App.Config文件中connectionStrings节中 connectionString 对应的name</param>
        /// <returns>数据库连接字符串</returns>
        private static string GetConnStr(string connName)
        {
            string connectString = "";
            string isEncrypt     = "";

            //如果connName为空,默认取 "DefaultSqlConnStr" 对应的 connectionString
            if (string.IsNullOrEmpty(connName))
            {
                connName = "DefaultSqlConnStr";
            }

            connectString = ConfigurationManager.ConnectionStrings[connName].ConnectionString.ToString();

            if (isEncrypt.ToLower() == "true")
            {
                //解密
                connectString = PwdUtil.DesDecrypt(connectString);
            }

            return(connectString);
        }
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            ViewBag.EnableSelfEnrollment = EnableSelfEnrollment;

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await DbContext.Users.Where(x => x.Name == model.Username).FirstOrDefaultAsync();

            if (user == null)
            {
                ModelState.AddModelError("", "Please register before attempting to log in.");
                ModelState.AddModelError("Username", $"\"{model.Username}\" is not registered.");
                return(View(model));
            }

            if (!user.Active)
            {
                ModelState.AddModelError("", $"\"{model.Username}\" is disabled. Please contact the administrator.");
                ModelState.AddModelError("Username", $"\"{ model.Username}\" is disabled.");
                return(View(model));
            }

            DateTime lastLoginAttempt, currentLoginAttempt;

            currentLoginAttempt   = DateTime.UtcNow;
            lastLoginAttempt      = user.LastLoginAttempt ?? DateTime.UtcNow;
            user.LastLoginAttempt = currentLoginAttempt;

            var lockoutErrorMsg = $"Too many failed login attempts. \"{model.Username}\" is temporarily locked.";

            if (user.Locked && (currentLoginAttempt - lastLoginAttempt) < TimeSpan.FromSeconds(AccountLockoutSeconds))
            {
                ModelState.AddModelError("", lockoutErrorMsg);
                //don't save user last login attempt time update or it will extend the lockout
                return(View(model));
            }

            if (model.Password != null && !PwdUtil.Verify(pwd: model.Password, hash: user.Hash, salt: user.Salt))
            {
                ModelState.AddModelError("Password", "Incorrect password.");
                user.FailedLoginAttempts++;
                if (user.FailedLoginAttempts >= AccountLockoutMaxFailedAttempts)
                {
                    ModelState.AddModelError("", lockoutErrorMsg);
                    user.Locked = true;
                }

                await DbContext.SaveChangesAsync();

                return(View(model));
            }

            await SignInAsync(user);

            user.FailedLoginAttempts = 0;
            user.Locked = false;

            await DbContext.SaveChangesAsync();

            return(RedirectFromLogin(model.RedirectUrl));
        }
        public async Task <IActionResult> Edit(EditUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await DbContext.Users.Where(x => x.UserId == model.UserId).SingleOrDefaultAsync();

            if (user == null)
            {
                throw new ArgumentException($"The 'UserId' ({model.UserId}) does not match an existing User.");
            }


            user.Name      = model.Username !; //Username can't be null if ModelState.IsValid == true
            user.Email     = model.Email !;    //Email can't be null of ModelState.IsValid == true
            user.Active    = model.Active;
            user.GivenName = string.IsNullOrEmpty(model.GivenName) ? null : model.GivenName;
            user.Surname   = string.IsNullOrEmpty(model.Surname) ? null : model.Surname;

            if (!string.IsNullOrEmpty(model.Password))
            {
                var salt = PwdUtil.NewSalt();
                var hash = PwdUtil.Hash(model.Password, salt);
                user.Salt = salt;
                user.Hash = hash;
            }

            //force unlock from failed login attempts by resetting failed count and setting the lock bit
            if (!model.Locked && user.Locked)
            {
                user.Locked = false;
                user.FailedLoginAttempts = 0;
            }

            var currentRoles = await DbContext.UserRoles.Where(x => x.UserId == model.UserId).ToListAsync();

            var selected   = model.Roles.Where(x => x.Checked).Select(x => x.Id);
            var unselected = model.Roles.Where(x => x.Checked).Select(x => x.Id);
            var added      = selected.Where(x => !currentRoles.Select(x => x.RoleId).Contains(x)).Select(x => new Data.Models.UserRole()
            {
                RoleId = x, UserId = model.UserId
            });

            DbContext.RemoveRange(currentRoles.Where(x => unselected.Contains(x.RoleId)));
            await DbContext.AddRangeAsync(added);

            try
            {
                await DbContext.SaveChangesAsync();

                ViewBag.Message = "Changes saved. You may make edits or close this tab.";
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
                Logger.LogError(e, "Error saving user edit.");
            }

            return(View(model));
        }