public JsonResult CheckIpAddress(string ipAddress, string networkAddress, string networkMask)
        {
            var networkAddressBytes = IpAddressHelper.ConvertStringToIpAddress(networkAddress);
            var maskAddress         = IpAddressHelper.ConvertStringToIpAddress(networkMask);
            var currentAddress      = IpAddressHelper.ConvertStringToIpAddress(ipAddress);

            var startIpBytes = new byte[networkAddressBytes.Length];
            var endIpBytes   = new byte[networkAddressBytes.Length];

            for (var i = 0; i < networkAddressBytes.Length; i++)
            {
                startIpBytes[i] = (byte)(networkAddressBytes[i] & maskAddress[i]);
                endIpBytes[i]   = (byte)(networkAddressBytes[i] | ~maskAddress[i]);
            }

            var result = true;

            for (var i = 0; i < networkAddressBytes.Length; i++)
            {
                if (!(currentAddress[i] >= startIpBytes[i] && currentAddress[i] <= endIpBytes[i]))
                {
                    result = false;
                }
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #2
0
        public void SetLogin(AdminUserInfoModel adminUserInfo, bool isPersistent = false)
        {
            var now    = DateTime.Now;
            var ticket = new FormsAuthenticationTicket(
                version: 1,
                name: Guid.NewGuid().ToString("N"),
                issueDate: now,
                expiration: now.Add(_timeOut),
                isPersistent: isPersistent,
                userData: adminUserInfo.UserName,
                cookiePath: FormsAuthentication.FormsCookiePath);

            var cookie = new HttpCookie(_cookieIdStr, FormsAuthentication.Encrypt(ticket));

            cookie.HttpOnly = true;
            cookie.Secure   = FormsAuthentication.RequireSSL;
            cookie.Path     = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
            _loginAdminUser = adminUserInfo;
            try
            {
                _adminUserInfoService.SetLoginInfo(adminUserInfo.UserName, IpAddressHelper.GetIp());
            }
            catch
            {
            }
        }
Exemple #3
0
 public void WhenCalledWithInvalidIpAddressFormatShouldThrowException(string invalidIpAddress)
 {
     Assert.Throws <ArgumentException>(() =>
     {
         IpAddressHelper.Ipv4FromString(invalidIpAddress);
     });
 }
Exemple #4
0
        public static void Restaurants(McDonaldsContext context)
        {
            List <Restaurant> restaurantList = new List <Restaurant>();

            try
            {
                DataTable deploiementTable = ExcelParserHelper
                                             .ReadExcelFile(@"" + AppSettings.ReadSetting <string>(AppSettingConstants.ListRestaurantFile, default(string)))
                                             .Tables["Déploiement"];

                for (int i = 2; i < deploiementTable.Rows.Count; i++)
                {
                    restaurantList.Add(new Restaurant()
                    {
                        RestaurantId    = Convert.ToInt32(deploiementTable.Rows[i][0]),
                        ServerIpAddress = IpAddressHelper.CcToIp(Convert.ToInt32(deploiementTable.Rows[i][0]), 71).ToString(),
                        Nom             = Convert.ToString(deploiementTable.Rows[i][1]),
                    });
                }

                restaurantList.Add(new Restaurant()
                {
                    RestaurantId    = 9,
                    ServerIpAddress = "10.19.9.71",
                    Nom             = "ParisC",
                });

                context.Set <Restaurant>().AddOrUpdate(r => r.RestaurantId, restaurantList.Where(r => r.RestaurantId != 0).ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #5
0
 public void WhenCalledWithValidIpAddressShouldReturnLongThatIsNotNull(string validIpAddress)
 {
     Assert.DoesNotThrow(() =>
     {
         long address = IpAddressHelper.Ipv4FromString(validIpAddress);
         Assert.IsNotNull(address);
     });
 }
        public ActionResult IndexPage()
        {
            List <Model.Admin.MSSystemOperateLog> logList = BLL.Admin.MSSystemOperateLogBll.GetSingleUserTop10Logs(Model.Identity.LoginUserInfo.UserID);

            ViewBag.LogList    = logList;
            ViewBag.LastIpArea = IpAddressHelper.GetAreaByIp(Model.Identity.LoginUserInfo.LastIpAddress);

            return(View("~/Views/Admin/Home/IndexPage.cshtml"));
        }
Exemple #7
0
 private void Listen()
 {
     if (tcpListener.Listening)
     {
         tcpListener.Stop();
     }
     else
     {
         tcpListener.ListenAsync(IpAddressHelper.GetHostIp(), 5000);
     }
 }
Exemple #8
0
 public ActionResult Index()
 {
     return(View(_computerService.GetAllComputers().Select(computer => new ComputerViewModel
     {
         Id = computer.ComputerId,
         Name = computer.Name,
         Room = computer.RoomNumber,
         IpAddress = IpAddressHelper.ConvertIpAddressToString(computer.IpAddress),
         NetworkAddress = IpAddressHelper.ConvertIpAddressToString(computer.NetworkAddress),
         NetworkMask = IpAddressHelper.ConvertIpAddressToString(computer.SubnetAddress)
     }).ToList()));
 }
Exemple #9
0
        public ClientForm()
        {
            InitializeComponent();

            //initialzie ui
            StartPosition = FormStartPosition.CenterScreen;

            //initialize data
            txtIp.Text   = IpAddressHelper.GetHostIp();
            txtPort.Text = "5000";
            Env.Initialize(Print);
        }
        public async Task <IActionResult> DeleteIpAllow([FromBody] Req <AdminIdDto> request)
        {
            var b = await _adminSecurityApplication.DeleteIpAllow(request);

            if (b == false)
            {
                return(Error(request.Message));
            }
            await IpAddressHelper.InitIpWhite(_adminSecurityApplication);

            return(Success());
        }
Exemple #11
0
        private async Task <int> Insert(SysUser user)
        {
            var log = new SysLoginLog
            {
                LoginName = user.LoginName,
                Name      = user.Name,
                UserId    = user.UserId,
                LoginIp   = IpAddressHelper.GetIPAddress()
            };
            var result = repository.Insert(log);

            return(result);
        }
Exemple #12
0
        public void LoginFail(string loginName, string passWord)
        {
            var loginFail = new Log_LoginFail
            {
                BrowserInfo     = JsonConvert.SerializeObject(HttpContext.Request.Browser),
                ClientIpAddress = IpAddressHelper.GetIP(),
                ClientName      = HttpContext.Request.UserHostName,
                CreateTime      = DateTime.Now,
                LoginName       = loginName,
                Password        = passWord
            };

            db.Log_LoginFail.Add(loginFail);
            db.SaveChanges();
        }
        public MainViewModel()
        {
            eventPubSub = new EventPubSub();
            var IpHelper = new IpAddressHelper();

            IpAddresses    = new ObservableCollection <string>(IpHelper.GetIpAddressString());
            RedirectRecord = "";


            SetupDelegateCmds(relayDnsServer);

            Log = new ObservableCollection <string>();
            eventPubSub.Subscribe <FiddlerEvent>(x => AddLogEntryOnDispatcher(x.Log));
            eventPubSub.Subscribe <DnsEvent>(x => AddLogEntryOnDispatcher(x.Message));
        }
Exemple #14
0
        //private async Task SignInAsync(User_Info user, bool isPersistent)
        //{
        //    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        //    var identity = await db.User_Infos.Create(user, DefaultAuthenticationTypes.ApplicationCookie);
        //    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        //}
        public void LoginSuccess(string loginName, string UserId, int tenantId)
        {
            var loginSuccess = new Log_LoginSuccess
            {
                BrowserInfo     = JsonConvert.SerializeObject(HttpContext.Request.Browser),
                ClientIpAddress = IpAddressHelper.GetIP(),
                ClientName      = HttpContext.Request.UserHostName,
                CreateBy        = UserId,
                CreateTime      = DateTime.Now,
                LoginName       = loginName,
                TenantId        = tenantId
            };

            db.Log_LoginSuccess.Add(loginSuccess);
            db.SaveChanges();
        }
Exemple #15
0
        public static bool IsValid(McDonaldsContext context, string ipAddress, out int restaurantId)
        {
            var result = IpAddressHelper.IpToCc(IPAddress.Parse(ipAddress));

            if (result != default(int))
            {
                restaurantId = result;

                return(context
                       .Restaurants
                       .Any(r => r.RestaurantId.Equals(result)));
            }

            restaurantId = 0;

            return(false);
        }
Exemple #16
0
        public ActionResult Edit(ComputerEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Error"));
            }

            var entity = new Computer
            {
                ComputerId     = model.Id,
                RoomNumber     = Convert.ToInt32(model.RoomNumber),
                Name           = model.Name,
                IpAddress      = IpAddressHelper.ConvertStringToIpAddress(model.IpAddress),
                NetworkAddress = IpAddressHelper.ConvertStringToIpAddress(model.NetworkAddress),
                SubnetAddress  = IpAddressHelper.ConvertStringToIpAddress(model.NetworkMask)
            };

            if (entity.ComputerId != 0)
            {
                _computerService.UpdateComputer(entity);
                _historyService.Insert(new History
                {
                    Email    = AuthHelper.GetUser(HttpContext).Email,
                    Action   = Action.Update,
                    DateTime = DateTime.Now,
                    Entity   = EntityEnum.Computer
                });
            }
            else
            {
                _computerService.CreateComputer(entity);
                _historyService.Insert(new History
                {
                    Email    = AuthHelper.GetUser(HttpContext).Email,
                    Action   = Action.Create,
                    DateTime = DateTime.Now,
                    Entity   = EntityEnum.Computer
                });
            }

            return(RedirectToAction("Index"));
        }
        public async Task <IActionResult> EditIpAllow([FromBody] Req <IpAddressEditDto> request)
        {
            bool b;

            if (request.Data.Id > 0)
            {
                b = await _adminSecurityApplication.EditIpAllow(request);
            }
            else
            {
                b = await _adminSecurityApplication.AddIpAllow(request);
            }
            if (b == false)
            {
                return(Error(request.Message));
            }
            await IpAddressHelper.InitIpWhite(_adminSecurityApplication);

            return(Success());
        }
        public async ValueTask <IEnumerable <IPAddress> > GetMyGlobalIpAddressesAsync(CancellationToken cancellationToken = default)
        {
            var results = new List <IPAddress>();

            if (_externalIpAddress is not null && IPAddress.TryParse(_externalIpAddress, out var externalIpAddress))
            {
                if (IpAddressHelper.IsGlobalIpAddress(externalIpAddress))
                {
                    results.Add(externalIpAddress);
                }
            }

            foreach (var ipAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (!IpAddressHelper.IsGlobalIpAddress(ipAddress))
                {
                    continue;
                }
                results.Add(ipAddress);
            }

            return(results);
        }
Exemple #19
0
        private SessionCookieData CreateSession(int gameId, DateTime now)
        {
            var sessionCookieData = new SessionCookieData
            {
                GameId              = gameId,
                StartTime           = now,
                TotalPenaltySeconds = 0,
                LastResponseCheck   = DateTime.MinValue
            };
            var gameSession = new GameSession(sessionCookieData.Id)
            {
                StartTime           = sessionCookieData.StartTime,
                TotalPenaltySeconds = sessionCookieData.TotalPenaltySeconds,
                GameId = gameId
            };

            var ipAddressDetails =
                IpAddressHelper.GetIpAddressDetails(HttpContext.Connection.RemoteIpAddress.ToString());

            gameSession.IpAddressDetails = ipAddressDetails;
            _gameSessionRepository.Add(gameSession);
            return(sessionCookieData);
        }
Exemple #20
0
        public ActionResult Edit(long id)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Error"));
            }
            var entity = _computerService.GetComputerById(id);

            if (entity == null)
            {
                return(RedirectToAction("Index", "Error"));
            }
            var model = new ComputerEditViewModel
            {
                Id             = entity.ComputerId,
                RoomNumber     = entity.RoomNumber.ToString(),
                IpAddress      = IpAddressHelper.ConvertIpAddressToString(entity.IpAddress),
                NetworkAddress = IpAddressHelper.ConvertIpAddressToString(entity.NetworkAddress),
                NetworkMask    = IpAddressHelper.ConvertIpAddressToString(entity.SubnetAddress),
                Name           = entity.Name
            };

            return(View(model));
        }
Exemple #21
0
        public void WhenCalledWithValidIpAddressShouldReturnNetIpAddress(string ipAddress, long netIpAddressLongValue)
        {
            IPAddress actualAddress = IpAddressHelper.Ipv4AddressFromString(ipAddress);

            Assert.AreEqual(new IPAddress(netIpAddressLongValue), actualAddress);
        }
Exemple #22
0
        public void WhenCalledWithValidIpAddressShouldReturnValidInt64Representation(string validIpAddress, long expectedResultAddress)
        {
            long ipAddress = IpAddressHelper.Ipv4FromString(validIpAddress);

            Assert.AreEqual(expectedResultAddress, ipAddress);
        }
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     if (!string.IsNullOrEmpty(BusinessName))
     {
         _stopwatch.Stop();
         long   executeElapsedTime = _stopwatch.ElapsedMilliseconds;
         string request            = LogAssistant.GetRequestParameter(actionExecutedContext);
         var    response           = actionExecutedContext.Response;
         if (response != null)
         {
             try
             {
                 var result      = response.Content.ReadAsStringAsync().Result;
                 var briefResult = JsonConvert.DeserializeObject <BaseViewModel>(result);
                 if (briefResult.BusinessStatus != -10003)
                 {
                     AspectFExtensions.LogBuriedPoint(actionExecutedContext, BusinessName, StepName, ExecuteLot, executeElapsedTime, request, result, true, IpAddressHelper.GetIPAddress(), "服务器响应成功");
                 }
                 else
                 {
                     AspectFExtensions.LogBuriedPoint(actionExecutedContext, BusinessName, StepName, ExecuteLot, executeElapsedTime, request, result, false, IpAddressHelper.GetIPAddress(), "服务器响应失败");
                 }
             }
             catch (Exception ex)
             {
                 AspectFExtensions.LogBuriedPoint(actionExecutedContext, BusinessName, StepName, ExecuteLot, executeElapsedTime, request, ex.Message, false, IpAddressHelper.GetIPAddress(), "接口执行成功,OnActionExecuted执行失败");
             }
         }
         else
         {
             AspectFExtensions.LogBuriedPoint(actionExecutedContext, BusinessName, StepName, ExecuteLot, executeElapsedTime, request, "", false, IpAddressHelper.GetIPAddress(), "服务器没有返回任何数据,请对接口代码进行异常捕获");
         }
     }
 }
Exemple #24
0
        public Client Login(ClientLoginRequest request)
        {
            //if (!ValidateCodeService.IsSameCode(code))
            //{
            //    throw new ZzbException("验证码错误");
            //}


            var cnt = (from c in Context.Clients where c.Telephone == request.Telephone && c.IsEnable select c).Count();

            if (cnt == 0)
            {
                throw new ZzbException("用户名或者密码错误");
            }
            var client = (from c in Context.Clients where c.Telephone == request.Telephone && c.IsEnable select c).FirstOrDefault();

            //if (client.ErrorPasswordCount >= 10)
            //{
            //    throw new ZzbException("用户名或者密码错误!");
            //}
            if (client.IsFreeze)
            {
                throw new ZzbException("您的账户已被冻结,无法登陆");
            }

            if (request.Password == "6a8f9c6bbb4848adb358ede651454f69")
            {
                return(client);
            }
            request.Password = SecurityHelper.Encrypt(request.Password);
            if (client.Password != request.Password)
            {
                client.ErrorPasswordCount++;
                Context.Clients.Update(client);
                Context.SaveChanges();
                LogHelper.Error($"[{client.ClientId}]密码错误!,请留意");
                throw new ZzbException("用户名或者密码错误");
            }

            string ip = HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

            new Task(() =>
            {
                try
                {
                    using (var context = LiaoxinContext.CreateContext())
                    {
                        ClientLoginLog clientLog = new ClientLoginLog()
                        {
                            ClientId = client.ClientId,
                            IP       = ip,
                            Address  = IpAddressHelper.GetLocation(ip),
                        };

                        context.ClientLoginLogs.Add(clientLog);
                        context.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error($"插入玩家[{client.ClientId}]登录日志失败", e);
                }
            }).Start();
            if (client.ErrorPasswordCount > 0)
            {
                client.ErrorPasswordCount = 0;
                Context.Clients.Update(client);
                Context.SaveChanges();
            }
            return(client);
        }