Exemplo n.º 1
0
 public async Task TestSimple()
 {
     using (var rp = await RedisPublisher.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 6379)))
     {
         for (var x = 0; x < 10; x++)
         {
             await rp.Publish("test", Encoding.UTF8.GetBytes("test"));
         }
     }
 }
Exemplo n.º 2
0
        public ActionResult Index(long?ad, Guid?token)
        {
            if (!ad.HasValue)
            {
                return(this.NotFoundException());
            }

            RedisPublisher.Publish("token", "Listing page " + ad.Value + " token: " + token.HasValue.ToString());

            if (!User.Identity.IsAuthenticated && token.HasValue)
            {
                var user = authAdapter.ValidateAuthToken(token.Value);

                if (user.StatusCode == 200)
                {
                    CustomAuthentication.SetAuthCookie(user.Result.Username, user.Result.UserId, true);
                }

                return(Redirect("/ksl/listing/index?ad=" + ad.Value));
            }

            var status = this.listingAdapter.GetListing(ad.Value);

            // this is ok because the adapter will return 0 if count cannot
            // be retrieved
            var viewCount = this.listingAdapter.GetListingViews(ad.Value).Result;

            var userHasSaved = this.listingAdapter.ListingWasSavedBy(ad.Value, User.Identity.Name).Result;

            if (status.StatusCode != 200)
            {
                return(this.NotFoundException());
            }

            this.listingAdapter.IncrementListingViews(ad.Value);

            var model = new ListingIndexModel();

            model.Listing      = status.Result;
            model.ListingViews = viewCount;
            model.UserHasSaved = userHasSaved;

            //set the login url to Ksl
            model.LoginUrl = string.Format("{0}{1}?login_forward=",
                                           Rentler.Web.Config.KslDomain,
                                           Rentler.Web.Config.KslLoginPath);

            model.LoginUrl += Url.Encode(string.Format("{0}{1}{2}",
                                                       Rentler.Web.Config.KslDomain,
                                                       Rentler.Web.Config.KslListingPath,
                                                       status.Result.BuildingId));

            return(View(model));
        }
Exemplo n.º 3
0
        public async Task TestParallelCalls()
        {
            using (var rp = await RedisPublisher.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 6379)))
            {
                var tl = new List <Task <int> >();

                for (var x = 0; x < 10; x++)
                {
                    tl.Add(rp.Publish("test", Encoding.UTF8.GetBytes("test")));
                }

                await Task.WhenAll(tl);
            }
        }
Exemplo n.º 4
0
        public Status <User> ValidateAuthToken(Guid token)
        {
            RedisPublisher.Publish("token", "Validating token: " + token.ToString());

            //L1
            var cache  = HttpContext.Current.Cache;
            int?userId = cache[CacheKeys.AUTH_TOKENS + ":" + token.ToString()] as int?;

            if (!userId.HasValue || userId == 0)
            {
                //L2
                var redisConnection = ConnectionGateway.Current.GetReadConnection();

                var task   = redisConnection.Hashes.GetString(App.RedisDatabase, CacheKeys.AUTH_TOKENS, token.ToString());
                var result = redisConnection.Wait(task);

                int userIdTryParse = 0;
                if (int.TryParse(result, out userIdTryParse))
                {
                    userId = userIdTryParse;
                }
            }

            if (userId.HasValue && userId != 0)
            {
                using (var context = new RentlerContext())
                {
                    var user = (from u in context.Users
                                where u.UserId == userId.Value
                                select u).SingleOrDefault();

                    if (user == null)
                    {
                        return(Status.NotFound <User>());
                    }

                    //otherwise we're good, clear cache and return
                    //L2
                    var connection = ConnectionGateway.Current.GetWriteConnection();
                    var task       = connection.Hashes.Remove(App.RedisDatabase, CacheKeys.AUTH_TOKENS, token.ToString());

                    //L1
                    cache.Remove(CacheKeys.AUTH_TOKENS + ":" + token.ToString());

                    return(Status.OK(user));
                }
            }

            return(Status.NotFound <User>());
        }
Exemplo n.º 5
0
        public void Publish_SerializerCalled()
        {
            var connection = A.Fake <IConnectionMultiplexer>();
            var serializer = A.Fake <IItemSerializer>();

            A.CallTo(() => connection.ClientName).Returns("C");

            var publisher = new RedisPublisher(connection, serializer);

            publisher.NotifyUpdate("A", "B");

            A.CallTo(() => serializer.Serialize(
                         A <CacheUpdateNotificationArgs> .That.Matches(args => args.Key == "A" && args.Type == "B" && args.ClientName == "C")))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Exemplo n.º 6
0
        public void Publish_PublishCalled()
        {
            var connection = A.Fake <IConnectionMultiplexer>();
            var serializer = A.Fake <IItemSerializer>();
            var subscriber = A.Fake <ISubscriber>();

            A.CallTo(() => connection.GetSubscriber(null)).Returns(subscriber);
            A.CallTo(() => connection.ClientName).Returns("C");
            A.CallTo(() => serializer.Serialize(A <CacheUpdateNotificationArgs> .Ignored)).Returns(new byte[] { 1 });
            var publisher = new RedisPublisher(connection, serializer);

            publisher.NotifyUpdate("A", "B");

            A.CallTo(() => subscriber.Publish("cacheUpdate", A <RedisValue> .That.Matches(r => ((byte[])r)[0] == 1), CommandFlags.FireAndForget))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Exemplo n.º 7
0
        Guid CreateAuthToken(int userId)
        {
            var token = Guid.NewGuid();

            //store in L2
            RedisPublisher.Publish("token", "Creating token for userId: " + userId);

            var connection = ConnectionGateway.Current.GetWriteConnection();
            var task       = connection.Hashes.Set(App.RedisDatabase, CacheKeys.AUTH_TOKENS, token.ToString(), userId.ToString());

            connection.Wait(task);

            //store in L1
            var cache = HttpContext.Current.Cache;

            cache[CacheKeys.AUTH_TOKENS + ":" + token.ToString()] = userId;

            return(token);
        }
Exemplo n.º 8
0
        static async Task Main(string[] args)
        {
            string redisUrl         = ConfigurationManager.AppSettings["RedisUrl"];
            var    connectionString = ConfigurationManager.ConnectionStrings["FargoEntities"].ConnectionString;

            using var redisSubscriber = await CreateRedisSubscriber(redisUrl);

            var redisPublisher = new RedisPublisher(redisUrl);
            await redisPublisher.PublishAsync("messages", "hello");

            await redisPublisher.PublishAsync("messages", "hello2");

            await redisPublisher.SetStringAsync("statusVersion", DateTime.Now.ToString(CultureInfo.InvariantCulture));

            var statusVersion = await redisSubscriber.GetStringAsync("statusVersion");

            DateTime statusDateTimeVersion = DateTime.Parse(statusVersion);

            using var productsProvider = new ProductsSqlTableDependencyProvider(connectionString, ThreadPoolScheduler.Instance, new ConsoleLogger());

            using var productSqlTableDependencyRedisProvider = new ProductSqlTableDependencyRedisProvider(productsProvider, redisPublisher, ThreadPoolScheduler.Instance)
                                                               .StartPublishing();

            Console.WriteLine("Trying to connect...");

            productsProvider.SubscribeToEntityChanges();

            AddOrUpdateProduct(connectionString);

            Console.WriteLine("Press a key to stop.");
            Console.ReadKey();

            redisSubscriber.Unsubscribe(nameof(Product) + "-Changes");
            redisSubscriber.Unsubscribe(nameof(Product) + "-Status");

            redisSubscriber.Dispose();
            redisPublisher.Dispose();
        }
Exemplo n.º 9
0
        public Status <Guid> GetAuthToken(ApiKey apiKey, string affiliateUserKey,
                                          string email, string passwordHash,
                                          string firstName, string lastName, string username)
        {
            RedisPublisher.Publish("token", "Getting token for api key: " + apiKey.ToString());

            //check if user exists
            var userId = accountAdapter.GetAffiliateUserIdByUsernameOrEmailAndApiKey(email, apiKey.ApiKeyId);

            //did we not find anything?
            if (userId.StatusCode == 404)
            {
                //try again, looking for regular rentler users this time
                userId = accountAdapter.GetUserIdByUsernameOrEmail(email);

                //still didn't find anything?
                if (userId.StatusCode == 404)
                {
                    //we've got a new one, make 'em
                    var user = new User();
                    user.Email         = email;
                    user.FirstName     = firstName;
                    user.LastName      = lastName ?? string.Empty;
                    user.Username      = username;
                    user.PasswordHash  = string.Empty;
                    user.CreateDateUtc = DateTime.UtcNow;
                    user.UpdatedBy     = "ksl auth";
                    user.UpdateDateUtc = DateTime.UtcNow;

                    var status = Status.Validatate <User>(user);

                    if (status.StatusCode != 200)
                    {
                        var result = Status.NotFound <Guid>();
                        result.Errors = status.Errors;

                        return(result);
                    }


                    using (var context = new RentlerContext())
                    {
                        context.Users.Add(user);
                        context.SaveChanges();
                        userId = Status.OK(user.UserId);
                    }
                }

                //Okay, now they're either already a Rentler user but are coming in from an affiliate,
                //or they just became one from an affiliate, so create an affiliate user for them.
                using (var context = new RentlerContext())
                {
                    var affiliate = new AffiliateUser();
                    affiliate.UserId           = userId.Result;
                    affiliate.AffiliateUserKey = affiliateUserKey;
                    affiliate.ApiKey           = apiKey.ApiKeyId;
                    affiliate.PasswordHash     = passwordHash;
                    context.AffiliateUsers.Add(affiliate);
                    context.SaveChanges();
                }
            }

            //generate auth token
            var token = CreateAuthToken(userId.Result);

            RedisPublisher.Publish("token", "Returning token: " + token.ToString());

            //return token
            return(Status.OK(token));
        }
Exemplo n.º 10
0
 public HomeController(QuestionContext context, ILogger <HomeController> logger, RedisPublisher redis)
 {
     _context = context;
     _logger  = logger;
     _redis   = redis;
 }