예제 #1
0
        private async Task <string> GetApiPageAsync(byte type, string cursor)
        {
            string url = await GetApiUrl(Blog.Url, type, cursor, Blog.PageSize == 0? 50 : Blog.PageSize);

            if (ShellService.Settings.LimitConnectionsApi)
            {
                CrawlerService.TimeconstraintApi.Acquire();
            }

            var referer = Blog.Url;

            var headers = new Dictionary <string, string>();

            headers.Add("Origin", "https://twitter.com");
            if (type > 0)
            {
                var token = await GetGuestToken();

                headers.Add("x-guest-token", token);
                headers.Add("x-twitter-active-user", "yes");
                headers.Add("x-twitter-client-language", "en");
                var cookie = CookieService.GetAllCookies().FirstOrDefault(c => c.Name == "ct0");
                if (cookie != null)
                {
                    headers.Add("x-csrf-token", cookie.Value);
                }
            }

            return(await GetRequestAsync(url, referer, headers));
        }
예제 #2
0
        protected virtual async Task <string> RequestPostAsync(int pageNumber)
        {
            var requestRegistration = new CancellationTokenRegistration();

            try
            {
                string url     = "https://www.tumblr.com/search/" + Blog.Name + "/post_page/" + pageNumber;
                string referer = @"https://www.tumblr.com/search/" + Blog.Name;
                var    headers = new Dictionary <string, string> {
                    { "X-tumblr-form-key", tumblrKey }, { "DNT", "1" }
                };
                HttpWebRequest request = WebRequestFactory.CreatePostXhrReqeust(url, referer, headers);
                CookieService.GetUriCookie(request.CookieContainer, new Uri("https://www.tumblr.com/"));

                //Example request body, searching for cars:
                //q=cars&sort=top&post_view=masonry&blogs_before=8&num_blogs_shown=8&num_posts_shown=20&before=24&blog_page=2&safe_mode=true&post_page=2&filter_nsfw=true&filter_post_type=&next_ad_offset=0&ad_placement_id=0&more_posts=true

                string requestBody = "q=" + Blog.Name + "&sort=top&post_view=masonry&num_posts_shown=" +
                                     ((pageNumber - 1) * Blog.PageSize) + "&before=" + ((pageNumber - 1) * Blog.PageSize) +
                                     "&safe_mode=false&post_page=" + pageNumber +
                                     "&filter_nsfw=false&filter_post_type=&next_ad_offset=0&ad_placement_id=0&more_posts=true";
                await WebRequestFactory.PerformPostXHRReqeustAsync(request, requestBody);

                requestRegistration = Ct.Register(() => request.Abort());
                return(await WebRequestFactory.ReadReqestToEndAsync(request));
            }
            finally
            {
                requestRegistration.Dispose();
            }
        }
예제 #3
0
        public ActionResult Login()
        {
            AccountLoginVM model = new AccountLoginVM();

            TryUpdateModel(model);

            AuthenticationManager.AuthenticateUser(model.Username, model.Password);

            if (AuthenticationManager.LoggedUser == null)
            {
                ModelState.AddModelError(String.Empty, "Invalid username or password.");
                return(View(model));
            }

            if (model.IsRemembered)
            {
                CookieService.CreateCookie();
            }

            if (!String.IsNullOrEmpty(model.RedirectUrl))
            {
                return(Redirect(model.RedirectUrl));
            }

            return(this.RedirectToAction <ContactsController>(c => c.List()));
        }
예제 #4
0
        private async Task <string> GetGuestToken()
        {
            if (guestToken == null)
            {
                var requestRegistration = new CancellationTokenRegistration();
                try
                {
                    string url = await GetApiUrl(Blog.Url, 0, "", 0);

                    if (ShellService.Settings.LimitConnectionsApi)
                    {
                        CrawlerService.TimeconstraintApi.Acquire();
                    }
                    var headers = new Dictionary <string, string>();
                    headers.Add("Origin", "https://twitter.com");
                    headers.Add("Authorization", "Bearer " + BearerToken);
                    HttpWebRequest request = WebRequestFactory.CreatePostRequest(url, "https://twitter.com", headers);
                    CookieService.GetUriCookie(request.CookieContainer, new Uri("https://twitter.com"));
                    requestRegistration = Ct.Register(() => request.Abort());
                    var content = await WebRequestFactory.ReadRequestToEndAsync(request);

                    guestToken = ((JValue)((JObject)JsonConvert.DeserializeObject(content))["guest_token"]).Value <string>();
                }
                catch (Exception e)
                {
                    Logger.Error("GetGuestToken: {0}", e);
                }
                finally
                {
                    requestRegistration.Dispose();
                }
            }
            return(guestToken);
        }
예제 #5
0
 public ProfileModal(StorageService storage, CookieService cookie, ProfileService profile, EditService edit)
 {
     storageService = storage;
     cookieService  = cookie;
     profileService = profile;
     editService    = edit;
 }
예제 #6
0
        public async Task <IActionResult> OnPostLoginAsync()
        {
            if (!ModelState.IsValid)
            {
                Message = ModelState.Root.Errors[0].ErrorMessage;
            }
            else
            {
                var user = userService.Login(Login.UserName, Login.Password);
                if (user != null)
                {
                    VUserModel model = new VUserModel()
                    {
                        Id        = user.Id,
                        UserName  = user.Name,
                        LoginTime = DateTime.Now,
                        HeaderImg = user.HeaderImg
                    };
                    var identity = new ClaimsIdentity(CookieService.AuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Sid, CookieService.GetDesEncrypt(model)));

                    await HttpContext.SignInAsync(CookieService.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties()
                    {
                        //记住我
                        IsPersistent = true,
                        //过期时间
                        ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(30))
                    });

                    return(RedirectToPage("./Index"));
                }
                Message = "登录失败,用户名密码不正确。";
            }
            return(Page());
        }
예제 #7
0
        public ActionResult Login(UserViewModel uvm)
        {
            LoginUserValidator validator = new LoginUserValidator();
            ValidationResult   result    = validator.Validate(uvm.LoginUserDto);

            if (!result.IsValid)
            {
                result.Errors.ToList().ForEach(error =>
                {
                    ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
                });
            }
            else
            {
                UserBriefDto dto = uvm.FindUserByNameAndPwd(uvm.LoginUserDto.Username, uvm.LoginUserDto.Userpwd);
                if (dto == null)
                {
                    return(View());
                }

                Response.Cookies.Add(CookieService.SaveCookies(dto.Id.ToString()));
                return(Redirect("~/APManage/Default/Index"));
            }

            return(View());
        }
예제 #8
0
        public JsonResult CheckSmsCode(string mobile, string smsCode, string invitationCode)
        {
            var rm = new ReturnModel();

            if (!string.IsNullOrEmpty(mobile))
            {
                rm = SmsService.CreateInstance().CheckSmsVcode(10, mobile, smsCode);

                if (rm.code == "0" && rm.subCode == "32100")
                {
                    CookieService.SetOpenBetaCookie(invitationCode);
                }


                //if (mobile == "18800008888" && smsCode == "1234")
                //{
                //    CookieService.SetOpenBetaCookie(invitationCode);
                //    rm.code = "0";
                //    rm.message = "验证成功";
                //}
                //else
                //{
                //    rm.code = "0";
                //    rm.message = "验证失败";
                //}
            }
            return(Json(rm));
        }
예제 #9
0
        public ActionResult AddToCart(CartVM viewModel)
        {
            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                // TODO: Check if product is not null (it exists)
                HttpContext.Response.SetCookie(CookieService.AddProductToCart(Request.Cookies, viewModel.ProductId, viewModel.Size, viewModel.Quantity));

                return(RedirectToAction("Index", "ShoppingCart"));
            }

            // If we are a user on the site use he database for the shopping cart
            Product product = new ProductManager().GetProductById(viewModel.ProductId);

            if (!new ShoppingCartManager().AddProductToCart(User.Identity.GetUserId(),
                                                            product, viewModel.Size,
                                                            viewModel.Quantity))
            {
                ModelState.AddModelError("", "An error has occured.");
            }


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

            return(RedirectToAction("Index", "ShoppingCart"));
        }
예제 #10
0
 public IndexModel(StorageService storage, CookieService cookie, EncryptionService encryption, NotificationService notification)
 {
     storageService      = storage;
     cookieService       = cookie;
     encryptionService   = encryption;
     notificationService = notification;
 }
예제 #11
0
        // GET: ShoppingCart
        public ActionResult Index()
        {
            string currency = CookieService.GetCurrency(Request.Cookies);

            ShoppingCartVM viewModel = new ShoppingCartVM()
            {
                CurrencyCode = currency
            };

            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                // Get products using the CookieService
                viewModel.Products = CookieService.GetShoppingCartProducts(Request.Cookies);

                viewModel.Subtotal = ShoppingCartService.GetSubTotal(viewModel.Products, currency);
                // Reverse the list so the most recent products are first
                viewModel.Products.Reverse();
                return(View(viewModel));
            }

            ShoppingCart shoppingCart = new ShoppingCartManager().GetShoppingCartByUser(User.Identity.GetUserId());

            viewModel.Products = new ShoppingCartProductManager().GetShoppingCartProductByShoppingCartId(shoppingCart.ShoppingCartId);


            viewModel.Subtotal = ShoppingCartService.GetSubTotal(viewModel.Products, currency);
            // Reverse the list so the most recent products are first
            viewModel.Products.Reverse();
            return(View(viewModel));
        }
 public LanguageService(ICurrentMarket currentMarket, CookieService cookieService,
                        IUpdateCurrentLanguage defaultUpdateCurrentLanguage)
 {
     _currentMarket = currentMarket;
     _cookieService = cookieService;
     _defaultUpdateCurrentLanguage = defaultUpdateCurrentLanguage;
 }
예제 #13
0
        private void GetLoggedInCallback(IAsyncResult asyncResult)
        {
            HttpWebRequest   request  = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse  response = (HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream           stream   = stream = response.GetResponseStream();
            StreamReader     reader   = new StreamReader(stream);
            CookieCollection cookies  = request.CookieContainer.GetCookies(new Uri("https://cas.sfu.ca/cgi-bin/WebObjects/cas.woa/wa/login"));


            if (CookieService.CookieExists("CASTGC"))
            {
                CookieService.RemoveCookieWithName("CASTGC");
            }
            foreach (Cookie cookie in cookies)
            {
                if (cookie.Name == "CASTGC")
                {
                    CookieService.AddCookie(cookie);
                }
            }
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                OnPropertyChanged("LoginStatus");
            });
        }
예제 #14
0
 public ArchiveChat(StorageService storage, CookieService cookie, ChatService chat, EncryptionService encryption)
 {
     cookieService     = cookie;
     chatService       = chat;
     encryptionService = encryption;
     storageService    = storage;
 }
예제 #15
0
 public BrowseModel(CookieService cookie, StorageService storage, NotificationService notification, SearchService search)
 {
     cookieService       = cookie;
     storageService      = storage;
     notificationService = notification;
     searchService       = search;
 }
예제 #16
0
 public CheckoutControllerForTest(
     ICartService cartService,
     IContentRepository contentRepository,
     UrlResolver urlResolver,
     IMailService mailService,
     ICheckoutService checkoutService,
     IContentLoader contentLoader,
     IPaymentService paymentService,
     LocalizationService localizationService,
     Func <string, CartHelper> cartHelper,
     CurrencyService currencyService,
     AddressBookService addressBookService,
     ControllerExceptionHandler controllerExceptionHandler,
     CustomerContextFacade customerContextFacade,
     CookieService cookieService)
     : base(cartService,
            contentRepository,
            urlResolver,
            mailService,
            checkoutService,
            contentLoader,
            paymentService,
            localizationService,
            cartHelper,
            currencyService,
            addressBookService,
            controllerExceptionHandler,
            customerContextFacade,
            cookieService)
 {
 }
예제 #17
0
 public Live(StorageService storage, CookieService cookie, ChatService chat, EncryptionService encryption)
 {
     storageService    = storage;
     cookieService     = cookie;
     chatService       = chat;
     encryptionService = encryption;
 }
예제 #18
0
        public ActionResult IncrementProductQuantity(CartVM viewModel)
        {
            List <ShoppingCartProduct> scps = new List <ShoppingCartProduct>();
            int qty = viewModel.Quantity; // this is to pass by reference to have the variable at return time

            // If we are a guest on the site use cookies for the shopping cart
            if (!UserService.IsUserConnected(System.Web.HttpContext.Current.User))
            {
                HttpCookie cookie = CookieService.Increment(Request.Cookies, viewModel.ProductId,
                                                            viewModel.Size, ref qty);
                HttpContext.Response.SetCookie(cookie);

                scps = CookieService.GetShoppingCartProducts(cookie);
            }
            else // We are connected with a user account
            {
                ShoppingCartManager shoppingCartManager = new ShoppingCartManager();

                qty = shoppingCartManager.IncrementQuantity(User.Identity.GetUserId(), viewModel.ProductId, viewModel.Size);
                //TODO : Check error message and show it in view if error occured


                ShoppingCart shoppingCart = new ShoppingCartManager().GetShoppingCartByUser(User.Identity.GetUserId());

                scps = new ShoppingCartProductManager().GetShoppingCartProductByShoppingCartId(shoppingCart.ShoppingCartId);
            }

            return(Json(new { price = ShoppingCartService.GetSubTotal(scps, CookieService.GetCurrency(Request.Cookies)), qty }, JsonRequestBehavior.AllowGet));
        }
예제 #19
0
        public Cookies()
        {
            //instantiate services
            var optionsBuilder = new DbContextOptionsBuilder();

            var useCosmos = $"{ConfigurationManager.AppSettings["UseCosmos"]}".ToUpper() == "TRUE";

            if (useCosmos)
            {
                var accountEndpoint = ConfigurationManager.AppSettings["CosmosAccountEndpoint"];
                var databaseName    = ConfigurationManager.AppSettings["CosmosDatabaseName"];
                var authKeyName     = ConfigurationManager.AppSettings["CosmosAccountKeyName"];
                var accountKey      = Environment.GetEnvironmentVariable(authKeyName);

                optionsBuilder = optionsBuilder.UseCosmos(accountEndpoint, accountKey, databaseName);
            }
            else
            {
                optionsBuilder = optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["CookieDBConnection"].ConnectionString);
            }

            var context = new CookieContext(optionsBuilder.Options);

            context.EnsureCreatedAndSeedAsync().Wait();
            _cookieService = new CookieService(context);
            _orderService  = new OrderService(context);
        }
예제 #20
0
 public CheckoutController(
     ICartService cartService,
     IContentRepository contentRepository,
     UrlResolver urlResolver,
     IMailService mailService,
     ICheckoutService checkoutService,
     IContentLoader contentLoader,
     IPaymentService paymentService,
     LocalizationService localizationService,
     Func <string, CartHelper> cartHelper,
     CurrencyService currencyService,
     IAddressBookService addressBookService,
     ControllerExceptionHandler controllerExceptionHandler,
     CustomerContextFacade customerContextFacade,
     CookieService cookieService)
 {
     _cartService                = cartService;
     _contentRepository          = contentRepository;
     _urlResolver                = urlResolver;
     _mailService                = mailService;
     _checkoutService            = checkoutService;
     _paymentService             = paymentService;
     _contentLoader              = contentLoader;
     _localizationService        = localizationService;
     _cartHelper                 = cartHelper;
     _currencyService            = currencyService;
     _addressBookService         = addressBookService;
     _controllerExceptionHandler = controllerExceptionHandler;
     _customerContext            = customerContextFacade;
     _cookieService              = cookieService;
 }
예제 #21
0
        public void LoginTest()
        {
            CookieService s      = new CookieService(httpContextAccessorMock.Object);
            bool          result = s.IsLogin();

            Assert.IsTrue(result);
        }
예제 #22
0
        protected async Task <string> RequestApiDataAsync(string url, string bearerToken, Dictionary <string, string> headers = null,
                                                          IEnumerable <string> cookieHosts = null)
        {
            var requestRegistration = new CancellationTokenRegistration();

            try
            {
                HttpWebRequest request = WebRequestFactory.CreateGetRequest(url, string.Empty, headers);
                cookieHosts = cookieHosts ?? new List <string>();
                foreach (string cookieHost in cookieHosts)
                {
                    CookieService.GetUriCookie(request.CookieContainer, new Uri(cookieHost));
                }

                request.PreAuthenticate = true;
                request.Headers.Add("Authorization", "Bearer " + bearerToken);
                request.Accept = "application/json";

                requestRegistration = Ct.Register(() => request.Abort());
                return(await WebRequestFactory.ReadRequestToEndAsync(request));
            }
            finally
            {
                requestRegistration.Dispose();
            }
        }
        public IUserContext GetUserContext()
        {
            //var userContext = HttpContext.Current.Items[Constantes.UserContext];
            UserContext userContext = new UserContext(Int16.Parse(CookieService.GetCookieStringValue(Constantes.UserCookieName)),
                                                      Int16.Parse(CookieService.GetCookieStringValue(Constantes.UserTimeOffset)));

            return(userContext);
        }
예제 #24
0
 public CurrentMarket(IMarketService marketService,
                      CookieService cookieService,
                      ICustomerService customerService)
 {
     _marketService   = marketService;
     _cookieService   = cookieService;
     _customerService = customerService;
 }
예제 #25
0
 public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, CookieService cookieService,
                          ApplicationService applicationService)
 {
     this.userManager        = userManager;
     this.signInManager      = signInManager;
     this.cookieServie       = cookieService;
     this.applicationService = applicationService;
 }
예제 #26
0
 public Student(StorageService storage, CookieService cookie, ProfileService profile, NotificationService notification, EncryptionService encryption)
 {
     storageService      = storage;
     cookieService       = cookie;
     profileService      = profile;
     notificationService = notification;
     encryptionService   = encryption;
 }
예제 #27
0
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public FileContentResult GetValidateCode()
        {
            string checkCode = RandService.Number(4);

            CookieService.SetCookie("Code", checkCode);
            var bt = new ValidateCodeService().CreateImages(checkCode);

            return(File(bt, "image/JPEG"));
        }
예제 #28
0
 public StudentDashboard(StorageService storage, CookieService cookie, ProfileService profile, NotificationService notification, FollowService follow, ScheduleService schedule)
 {
     storageService      = storage;
     cookieService       = cookie;
     profileService      = profile;
     notificationService = notification;
     followService       = follow;
     scheduleService     = schedule;
 }
예제 #29
0
 public ActionResult SetInvitationCodeCookie(string code)
 {
     if (code == "BAILUN")
     {
         CookieService.SetOpenBetaCookie(code);
         return(Redirect("/"));
     }
     return(Redirect("/account/invitationcode"));
 }
예제 #30
0
        public ViewResult Index()
        {
            var cookieService = new CookieService();
            var model         = new Index();

            cookieService.GetCookie(model, this);
            ViewBag.space = " ";
            return(View(model));
        }
예제 #31
0
        // This is the SnackController unit test
        static void Main(string[] args)
        {
            // Create the proxy cookie service that wraps the real CookieService
            CookieService svc = new CookieService();
            ProxyFactory<ICookieService> pf = new ProxyFactory<ICookieService>(false);
            ICookieService proxy = pf.Create(svc);

            // Construct SnackController with the proxy cookie service
            SnackController ctrlr = new SnackController(proxy);
            ctrlr.PrepareSnacks(); // All calls are routed to the real CookieService

            // Now inject a fault in CookieService.DistributeAll
            ProxyFactory<ICookieService>.ChangeBehavior(proxy, "DistributeAll",
                new FaultyMethods(), "DistributeAllChanged");
            ctrlr.PrepareSnacks(); // Calls to CookieService.DistributeAll are routed to FaultyMethods.DistributeAllChanged
        }
예제 #32
0
        public ActionResult Thanks(QuestionModel model)
        {
            CookieService cookie=new CookieService();
            Alternative alternative = _db.Alternatives.Single(a => a.Id == model.AlternativeId);
            Question question = _db.Questions.Single(q => q.Id == model.QuestionId);

            if (cookie.VoteAllowed(question.Id))
            {
                alternative.Votes++;
                _db.SaveChanges();
                cookie.MakeVoteAuthenticate(question.Id);

                return View(question);
            }
            else return View("VoteDenied",question);
        }