public ActionResult Login(string returnUrl) { var ip = IPClient.getIP();//lấy ip local AuthenticationManager.SignOut(); if (User.Identity.IsAuthenticated) { return(RedirectToAction("AccountDashboard", "Home")); } log.Info("tui là tui"); //_userManager.ChangePassword("c21a1169-1e5d-4aa7-9604-1595514608bc", "123456", "labixa@123"); ViewBag.ReturnUrl = returnUrl; //HttpCookie cookie1 = Request.Cookies["mimosa"]; Response.Cookies["mimosa"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["mamosi"].Expires = DateTime.Now.AddDays(-1); //if (cookie1 != null) //{ // cookie1.Value = null; //} //HttpCookie cookie2 = Request.Cookies["mamosi"]; //if(cookie2 != null) //{ // cookie2.Value = null; //} Request.Cookies.Remove("mimosa"); //QRIMage Request.Cookies.Remove("mamosi"); //QRText //Response.Cookies.Clear() return(View()); //return RedirectToAction("Index", "ErrorMessage"); }
async private void Client_OnDisconnected(string message) { client = null; Console.WriteLine("Disconnected!! " + message); LogFile.saveRegistro("Not Connected - " + message, levels.error); if (connectionAttemps == 0) { token = new CancellationToken(false); await TryReconnect(); } }
public override void Connect() { string hostname = ShiolConfiguration.Instance.Config.Communication.IP; int port = ShiolConfiguration.Instance.Config.Communication.IPPort; client = new IPClient(hostname, port); // client.taskUI = TaskScheduler.FromCurrentSynchronizationContext(); client.OnConnected += Client_OnConnected; client.OnDisconnected += Client_OnDisconnected; client.OnDataReceived += Client_OnDataReceived; Console.WriteLine("Connecting to " + ShiolConfiguration.Instance.Config.Communication.IP + ":" + ShiolConfiguration.Instance.Config.Communication.IPPort); client.BeginConnect(); }
public async System.Threading.Tasks.Task <JsonResult> GetIPClient(string username) { var ip = IPClient.getIP(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(DOMAIN_API_ADMIN); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); HttpResponseMessage response = await client.GetAsync(DOMAIN_API_ADMIN + "api/Account?UserIP=" + ip + "&username=" + username); if (response.IsSuccessStatusCode) { return(Json(response.Content.ReadAsStringAsync().Result)); } } return(Json(ip)); }
/// <summary> /// Чтение БД /// </summary> public static void ReadAll() { try { if (!File.Exists(Environment.CurrentDirectory + "\\BlackList.txt")) { return; } StreamReader wr = new StreamReader(Environment.CurrentDirectory + "\\BlackList.txt"); string[] param = wr.ReadToEnd().Split(new String[] { "<>" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < param.Length; i++) { string[] args = param[i].Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); if (args.Length >= 1) { try { IPAddress add = IPAddress.Parse(args[0]); IPClient ncl = new IPClient(add); bool block = Convert.ToBoolean(args[1]); DateTime.TryParse(args[2], out ncl.BlockTime); uint.TryParse(args[3], out ncl.BlockTimes); if (ncl.BlockTimes > 0) { } DateTime.TryParse(args[4], out ncl.FirstTime); DateTime.TryParse(args[5], out ncl.LastTime); lastconnects.Add(ncl); } catch (Exception ex) { Program.COut("Error!!!\r\n" + ex.ToString(), ConsoleColor.Red); } } } wr.Close(); } catch (Exception e) { Program.COut("Error2!!!\r\n" + e.ToString(), ConsoleColor.Red); } }
public ActionResult Submit2FA(string username, string pinCode) { var resultValidate = _twoAuthFact.ValidateTwoFactorPIN_2FA(username, pinCode); if (resultValidate == false) { ModelState.AddModelError("", "Validate invalid. Please confirm again"); return(RedirectToAction("Confirm2FA", "EmailFunc", new { username = username })); } else { var _user = _userManager.FindByName(username); //cập nhật ip vào db web _user.IP_login = IPClient.getIP(); _user.TwoFactorEnabled = true; _userManager.Update(_user); ModelState.AddModelError("", "Validate success. Please login"); return(RedirectToAction("LoginAferConfrim_2faAsync", "Account", new { username = _user.UserName })); } }
public static IPClient Add(IPAddress ip, DateTime date) { lock (lastconnects) { if (CheckNew(ip))//Есть ли ip в нашей базе { //Если нет, делай запрос к агрегатору базы данных ip адресов IPClient newip = new IPClient(ip); // lastconnects.Add(newip); //Добавляем его в нашу БД var outer = Task.Factory.StartNew(() => { double ot = AbuseIP.CheckIP(newip.ip.ToString());//Получаем коэффициент от агрегатора if (ot >= 0.5) { //Временная блокировка newip.Block = true; newip.BlockTime = DateTime.Now; newip.BlockTimes = Math.Max((uint)Math.Ceiling(Math.Max(ot, 19)), newip.BlockTimes);//max rat - 19 Program.COut(newip.ip.ToString() + " - added to Blacklist with IP rating - " + Math.Round(ot, 1), ConsoleColor.Red); } else { //Всё нормально Program.COut(newip.ip.ToString() + " IP rating - " + Math.Round(ot, 1), ConsoleColor.Green); } }); return(newip); } else { //Если ip есть в БД, выдаем информацию по нему var cl = GetByIP(ip); cl.LastTime = DateTime.Now; if (!Server.BlockWork) { cl.Block = false; } return(cl); } } }
public override void Disconnect() { client.Disconnect(); client = null; }
public async Task <ActionResult> Register(RegisterViewModel model) { CaptchaResponse response = _captcha.ValidateCaptcha(Request["g-recaptcha-response"]); try { if (ModelState.IsValid) { //kiểm tra user name khi được nhập vào var checkUser = _userManager.FindByName(model.UserName.ToLower()); //check mail var checkEmailAddress = _userManager.FindByEmail(model.Email); if (checkEmailAddress != null)// mail tồn tại không cho tạo tk { ModelState.AddModelError("", "Email existed"); //return RedirectToAction("Register", "Account"); } else { //kiểm tra username có tồn tại trong db hay chưa, null là username chưa có -> có thể đăng ký được if (checkUser == null) { //kiểm tra parent id if (!string.IsNullOrEmpty(model.Affilate_ID)) { var checkParentId = _userManager.FindByName(model.Affilate_ID); //chính là user name if (checkParentId != null && checkParentId.EmailConfirmed == true) // tồn tại affilliate cho tạo tk + trùng mail thì không cho tạo tk { //var checkParentId = _userManager.FindById(findUserParent.Id); //Neu parent exist thi them parent vao User userParent = new User() { UserName = model.UserName.ToLower().Replace(" ", string.Empty), Email = model.Email, ParentId = checkParentId.Id, PasswordNotHash = model.Password, Temp2 = model.Password, // để lưu khi đổi pass Activated = true //tạo mặc định để có thể lock hoặc unclock trong admin }; var ip = IPClient.getIP(); //chỉ dùng cho web golive if (ip.Equals("::1")) { log.Info("Ip localhost: " + ip + "_" + DateTime.Now); ip = SERVER_IP; } var CallApiFundist = await _sdkApiFundits.ApiCreateUser(model.UserName.ToLower().Replace(" ", string.Empty), model.Password, CommonCalculate.GetTimeStamp(), ip, model.UserName);//tạo account fundist if (CallApiFundist.Equals("1")) { var qrImage = _twoFact.GetQrCodeImage(model.UserName.ToLower().Replace(" ", string.Empty)); var qrText = _twoFact.GetQrCodeText(model.UserName.ToLower().Replace(" ", string.Empty)); userParent.Temp = qrImage; userParent.Temp1 = qrText; var resultParent = await _userManager.CreateAsync(userParent, model.Password); //tạo account trong db web var userId = _userManager.FindByName(model.UserName.ToLower().Replace(" ", string.Empty)); //tìm username trong db web để lấy ra id của user log.Info("Start mail register"); var resultSendMail = await _confirmEmail.CallMailRegister(CommonCalculate.GetTimeStamp(), model.UserName.ToLower().Replace(" ", string.Empty), 4); //gửi mail xác nhận đăng ký //gọi api admin để tạo ví var jsonObject = new { username = userId.UserName, password = userId.PasswordNotHash, usernameParent = model.Affilate_ID }; var CallApiAdmin = await _sdkApiAdmin.SDKApiAdminPostAsync(DOMAIN_API + "api/Account/", jsonObject);//gọi api tạo account admin JObject ApiAdminCall = JObject.Parse(CallApiAdmin); //tim username upate address, balance ETH, balance VIP var a = ApiAdminCall["UserName"].ToString(); var findUseName = _userManager.FindByName(a); if (findUseName != null) { findUseName.Address_Crypto = ApiAdminCall["AdressKey"].ToString(); findUseName.Balance_ETH = ApiAdminCall["Balance"].ToString(); findUseName.Balance_VIP = ApiAdminCall["BalanceVip"].ToString(); _userManager.Update(findUseName); } ///// if (resultParent.Succeeded) { // await SignInAsync(userParent, isPersistent: false);//tắt auto đăng nhập khi đăng ký thành công return(RedirectToAction("sendMailConfirm", "EmailFunc", new { message = resultSendMail })); } else { ModelState.AddModelError("", "Invalid: " + resultParent); } } else { log.Info("Error when call api fundist: " + CallApiFundist); ModelState.AddModelError("Invalid: ", CallApiFundist); } } else { log.Info("Error invalid Affilate"); //Thông báo lỗi parent ModelState.AddModelError("Parent invalid or email existed", "Affiliate ID does not exis !"); } } else { User userParent = new User() { UserName = model.UserName.ToLower().Replace(" ", string.Empty), Email = model.Email, PasswordNotHash = model.Password, ParentId = PARENT_ID, Temp2 = model.Password, // để lưu khi đổi pass Activated = true //tạo mặc định để có thể lock hoặc unclock trong admin }; var ip = IPClient.getIP(); //chỉ dùng cho web golive if (ip.Equals("::1")) { ip = SERVER_IP; } var CallApiFundist = await _sdkApiFundits.ApiCreateUser(model.UserName.ToLower().Replace(" ", string.Empty), model.Password, CommonCalculate.GetTimeStamp(), ip, model.UserName);//gọi api fundist //chưa check if (CallApiFundist.Equals("1")) { userParent.Temp = _twoFact.GetQrCodeImage(model.UserName.ToLower().Replace(" ", string.Empty)); userParent.Temp1 = _twoFact.GetQrCodeText(model.UserName.ToLower().Replace(" ", string.Empty)); var resultParent = await _userManager.CreateAsync(userParent, model.Password); //tạo account ở db web var userId = _userManager.FindByName(model.UserName.ToLower().Replace(" ", string.Empty)); //tìm username trong db web để lấy ra id của user log.Info("Send mail"); //Gửi mail xác nhận đăng ký var resultSendMail = await _confirmEmail.CallMailRegister(CommonCalculate.GetTimeStamp(), model.UserName.ToLower().Replace(" ", string.Empty), 4); //gửi mail xác nhận đăng ký var jsonObject = new { username = userId.UserName, password = userId.PasswordNotHash, usernameParent = "avataclub" }; var CallApiAdmin = await _sdkApiAdmin.SDKApiAdminPostAsync(DOMAIN_API + "api/Account/", jsonObject);//tạo account trên admin log.Info("Account create api admin: " + CallApiAdmin); if (!string.IsNullOrEmpty(CallApiAdmin)) { JObject ApiAdminCall = JObject.Parse(CallApiAdmin); //tim username upate address, balance ETH, balance VIP var a = ApiAdminCall["UserName"].ToString(); var findUseName = _userManager.FindByName(a); if (findUseName != null) { findUseName.Address_Crypto = ApiAdminCall["AdressKey"].ToString(); findUseName.Balance_ETH = ApiAdminCall["Balance"].ToString(); findUseName.Balance_VIP = ApiAdminCall["BalanceVip"].ToString(); _userManager.Update(findUseName); } if (resultParent.Succeeded) { //await SignInAsync(userParent, isPersistent: false); return(RedirectToAction("sendMailConfirm", "EmailFunc", new { message = resultSendMail })); } else { AddErrors(resultParent); } } else { log.Info("Can't create account from api admin - End"); ModelState.AddModelError("", CallApiAdmin); } } else { log.Info("Error when call api fundist: " + CallApiFundist); ModelState.AddModelError("Invalid: ", CallApiFundist); } //var resultParent = await _userManager.CreateAsync(userParent, model.Password); //if (resultParent.Succeeded) //{ // await SignInAsync(userParent, isPersistent: false); // return RedirectToAction("Index", "Home"); //} //else //{ // AddErrors(resultParent); //} } } else { ModelState.AddModelError("", "Same name existed"); } } } // If we got this far, something failed, redisplay form return(View(model)); } catch (Exception ex) { log.Info("Error exception function register accont_" + DateTime.Now + ": " + ex); ModelState.AddModelError("", "**Error register"); return(RedirectToAction("Index", "ErrorMessage")); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl, string message) { try { if (ModelState.IsValid) { var ip = IPClient.getIP();//lấy ip local //if (ip == "115.73.214.11") //{ //} //else //{ // return RedirectToAction("Index", "ErrorMessage"); //} ModelState.AddModelError("", message); var user = await _userManager.FindAsync(model.UserName.ToLower(), model.Password); if (user != null) { if (user.Activated == true) { //kiểm tra xác thực email if (user.EmailConfirmed == true) { //Nếu chứa xác thực thì login bình thường if (user.TwoFactorEnabled == false) { Session["User"] = user; Session["UserName"] = user.UserName.ToLower(); Session["QRImage"] = user.Temp; Session["QRText"] = user.Temp1; HttpCookie qrImage = Request.Cookies["mimosa"]; HttpCookie qrText = Request.Cookies["mamosi"]; if (qrImage != null && qrText != null) { //Request.Cookies.Remove("mimosa"); //Request.Cookies.Remove("mamosi"); qrImage.Value = null; qrText.Value = null; qrImage.Value = user.Temp; qrImage.Expires = DateTime.Now.AddDays(30); qrText.Value = user.Temp1; qrText.Expires = DateTime.Now.AddDays(30); Request.Cookies.Add(qrImage); Request.Cookies.Add(qrText); } else { qrImage = new HttpCookie("mimosa", user.Temp); qrImage.Expires = DateTime.Now.AddDays(1); Response.SetCookie(qrImage); qrText = new HttpCookie("mamosi", user.Temp1); qrText.Expires = DateTime.Now.AddDays(1); Response.SetCookie(qrText); } log.Info(Session["QRText"]); await SignInAsync(user, model.RememberMe); //lưu ip login vào db Website kiểm tra login user.IP_login = ip; _userManager.Update(user); return(RedirectToAction("AccountDashboard", "Home")); } else { return(RedirectToAction("Confirm2FA", "EmailFunc", new { username = user.UserName.ToLower() })); } } else { ModelState.AddModelError("", "Please confirm email before login"); } } else { ModelState.AddModelError("", "User name or Password incorrect"); } } else { ModelState.AddModelError("", "User name or Password incorrect"); } } return(View(model)); } catch (Exception) { return(RedirectToAction("Index", "ErrorMessage")); } }