コード例 #1
0
        /// <summary>
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public async Task <ServiceResult> AuthenticateUserAsync(string userName, string password, string ip)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                using (var context = new TreeMonDbContext(this._connectionKey))
                {
                    await context.InsertAsync <AuthenticationLog>(new AuthenticationLog()
                    {
                        Authenticated = false, AuthenticationDate = DateTime.UtcNow, IPAddress = ip, FailType = "Blank Username", UserName = userName, UUIDType = "AuthenticationLog", Vector = "UserManager.AuthenticateUser"
                    });
                }
                return(ServiceResponse.Error("Invalid username or password."));
            }

            User user = null;

            try
            {
                using (var context = new TreeMonDbContext(this._connectionKey))
                {
                    user = (await context.GetAllAsync <User>()).FirstOrDefault(uw => (uw.Name?.EqualsIgnoreCase(userName) ?? false));

                    if (user == null)
                    {
                        return(ServiceResponse.Error("Invalid username or password."));
                    }

                    user.LastActivityDate = DateTime.UtcNow;

                    if (!PasswordHash.ValidatePassword(password, user.PasswordHashIterations + ":" + user.PasswordSalt + ":" + user.Password))
                    {
                        context.Insert <AuthenticationLog>(new AuthenticationLog()
                        {
                            Authenticated = false, AuthenticationDate = DateTime.UtcNow, IPAddress = ip, FailType = "Invalid Password", UserName = userName, UUIDType = "AuthenticationLog", Vector = "UserManager.AuthenticateUser"
                        });
                        user.FailedPasswordAttemptCount++;
                        context.Update <User>(user);
                        return(ServiceResponse.Error("Invalid username or password."));
                    }

                    ServiceResult sr = IsUserAuthorized(user, ip);

                    if (sr.Status == "ERROR")
                    {
                        return(sr);
                    }

                    user.Online        = true;
                    user.LastLoginDate = DateTime.UtcNow;

                    await context.UpdateAsync <User>(user);
                }
            }
            catch (Exception ex)
            {
                _logger.InsertError(ex.Message, "UserManager", "AuthenticateUserAsync:" + userName + " IP:" + ip);

                return(ServiceResponse.Error(ex.Message));
            }

            return(ServiceResponse.OK());
        }