Example #1
0
        public static async Task<AppUser> GetUserAsync(string tenant, HubCallerContext context)
        {
            var token = await GetTokenAsync(tenant, context).ConfigureAwait(false);

            if (token != null)
            {
                await AppUsers.SetCurrentLoginAsync(tenant, token.LoginId).ConfigureAwait(false);
                var loginView = await AppUsers.GetCurrentAsync(tenant, token.LoginId).ConfigureAwait(false);

                return new AppUser
                {
                    Tenant = tenant,
                    ClientToken = token.ClientToken,
                    LoginId = token.LoginId,
                    UserId = loginView.UserId,
                    OfficeId = loginView.OfficeId,
                    Email = loginView.Email,
                    IsAdministrator = loginView.IsAdministrator,
                    RoleId = loginView.RoleId,
                    Name = loginView.Name,
                    RoleName = loginView.RoleName,
                    OfficeName = loginView.OfficeName
                };
            }

            return null;
        }
 public Game GetGame(HubCallerContext context)
 {
     return games.Select(x => x.Value).FirstOrDefault(
         x => (x.FirstPlayer.ConnectionId == context.ConnectionId ||
               x.SecondPlayer == null ||
               x.SecondPlayer.ConnectionId == context.ConnectionId));
 }
Example #3
0
        public async Task FileSystemHubDisconnectTest()
        {
            // Setup
            var env = new Mock<IEnvironment>();
            var tracer = new Mock<ITracer>();
            var context = new HubCallerContext(Mock.Of<IRequest>(), Guid.NewGuid().ToString());
            var groups = new Mock<IGroupManager>();
            var clients = new Mock<HubConnectionContext>();

            using (
                var fileSystemHubTest = new FileSystemHubTest(env.Object, tracer.Object, context, groups.Object,
                    clients.Object))
            {
                // Test
                fileSystemHubTest.TestRegister(@"C:\");

                // Assert
                Assert.Equal(1, FileSystemHubTest.FileWatchersCount);

                // Test
                await fileSystemHubTest.TestDisconnect();
            }
            // Assert
            Assert.Equal(0, FileSystemHubTest.FileWatchersCount);
        }
 public object Resolve(HubCallerContext context)
 {
     return new
            {
                Name = context.ConnectionId,
                Id = context.ConnectionId
            };
 }
Example #5
0
        private static string GetIpAddress(HubCallerContext context)
        {
            object tempObject;

            context.Request.Environment.TryGetValue("server.RemoteIpAddress", out tempObject);

            return tempObject?.ToString() ?? string.Empty;
        }
Example #6
0
 public Player(HubCallerContext context, int position)
 {
     this.Context = context;
     this.StartingLocation = Constants.StartingLocations[position];
     this.EndingLocation = Constants.EndingLocations[position];
     this.CurrentLife = Constants.StartingLife;
     this.Resources = JsonConvert.DeserializeObject<Resources>(JsonConvert.SerializeObject(Constants.StartingResources));
 }
 internal static ChatUser Connection(HubCallerContext context, dynamic clients)
 {
     var token = context.QueryString["token"];
     var user = configuration.retrieveUser(token);
     user.connectionId = context.ConnectionId;
     users.TryAdd(token, user);
     return user;
 }
Example #8
0
 public void Subscribe(Persist type, object id, HubCallerContext connection)
 {
     if(!this.subscriptions.ContainsKey(this.GetKey(type, id)))
     {
         this.subscriptions.Add(this.GetKey(type, id), new List<HubCallerContext>());
     }
     this.subscriptions[this.GetKey(type, id)].Add(connection);
 }
Example #9
0
 public async Task<GameRoom> StartGameAsync(HubCallerContext context)
 {
     var gameRoom = new GameRoom(context);
     // gameRoom.Towers = gameRoom.Towers.Union(TestingConstants.Maze).ToList(); // TODO remove test code
     this.scaleoutService.Subscribe(Persist.GameRoom, gameRoom.Id, context);
     this.scaleoutService.Store(Persist.GameRoom, gameRoom.Id, gameRoom);
     return gameRoom;
 }
Example #10
0
        public static string GetUserName(HubCallerContext context)
        {
            var userName = context.Headers[ServiceConstants.Server.UsernameHeader];
            if (string.IsNullOrEmpty(userName))
            {
                return context.QueryString[ServiceConstants.Server.UsernameHeader];
            }

            return userName;
        }
 public void Subscribe(HubCallerContext context, string typeName, dynamic constraint)
 {
     var type = typeFinder.GetType(typeName);
     subscriptions[type].Add(new EventSubscription(context.ConnectionId, context.User.Identity.Name, constraint));
     if (!userSubscriptions.ContainsKey(context.ConnectionId))
     {
         userSubscriptions[context.ConnectionId] = new List<Type>();
     }
     userSubscriptions[context.ConnectionId].Add(type);
 }
		public SignalRConnectionContext(HubCallerContext context)
		{
			Contract.Requires(context != null);

			if (context == null) throw new ArgumentNullException("context");

			Contract.Ensures(QueryString != null);
			
			this.QueryString = context.QueryString.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
			this.CorrelationId = context.ConnectionId;
		}
Example #13
0
        public TestableHub(HubConnectionContext clients)
        {
            var mockCookies = new Mock<IRequestCookieCollection>();

            var mockRequest = new Mock<IRequest>();
            mockRequest.Setup(r => r.Cookies).Returns(mockCookies.Object);

            Context = new HubCallerContext(mockRequest.Object, ConnectionId);

            Clients = clients;
        }
Example #14
0
        public static async Task<long> GetLoginIdAsync(string tenant, HubCallerContext context)
        {
            var token = await GetTokenAsync(tenant, context).ConfigureAwait(false);

            if (token == null)
            {
                return 0;
            }

            return token.LoginId;
        }
 /// <summary>
 /// 通过请求上下文获取请求对应的Session
 /// </summary>
 /// <param name="context">请求上下文</param>
 /// <returns></returns>
 public static Session Session(HubCallerContext context)
 {
     if (!context.RequestCookies.ContainsKey("ASP.NET_SignalRExtendLib_SessionKey"))
     {
         throw new GetSessionFaildException("无法获取Session或该Hub未添加SessionEnableAttribute特性");
     }
     else
     {
         return SessionPool.Take(context.RequestCookies["ASP.NET_SignalRExtendLib_SessionKey"].Value);
     }
 }
Example #16
0
        public async Task ChatMessageReceived(HubCallerContext context, string roomId, string message)
        {
            var gameRoom = this.scaleoutService.Get(Persist.GameRoom, roomId) as GameRoom;
            var players = gameRoom.Players;

            var gameHubContext = GlobalHost.ConnectionManager.GetHubContext<GameHub>();
            foreach (Player player in players) 
            {
                gameHubContext.Clients.Client(player.Context.ConnectionId).chatMessageReceived(message);
            }
        }
Example #17
0
        private void InitializeHub(string name)
        {
            const string connectionId = "1234";
            var mockRequest = new Mock<IRequest>();

            if (name != null)
            {
                var mockUser = new GenericPrincipal(new UserViewModel { Name = name }, null);
                mockRequest.Setup(r => r.User).Returns(mockUser);
            }
            Context = new HubCallerContext(mockRequest.Object, connectionId);
        }
Example #18
0
 public GameRoom(HubCallerContext context)
 {
     this.Id = (new Random()).Next(1000); ;
     this.Players = new List<Player>()
     {
         new Player(context, 0)
     };
     this.CurrentRound = 0;
     this.Towers = new Dictionary<Point, Tower>();
     this.Map = Constants.Map;
     this.MapSize = Constants.MapSize;
 }
Example #19
0
        public async Task<GameRoom> JoinGameAsync(HubCallerContext context, string roomId)
        {
            var gameRoom = this.scaleoutService.Get(Persist.GameRoom, roomId) as GameRoom;

            if(gameRoom != null)
            {
                gameRoom.Players.Add(new Player(context, gameRoom.Players.Count));
                this.scaleoutService.Subscribe(Persist.GameRoom, gameRoom.Id, context);
                this.scaleoutService.Store(Persist.GameRoom, gameRoom.Id, gameRoom);
            }

            return gameRoom;
        }
Example #20
0
        /// <summary>
        /// Confirms that the user is part of the roomId provided.
        /// Throws 401 if the roomId is not found
        /// Throws 500 if the user is not part of the roomId
        /// </summary>
        /// <param name="context">The context to confirm is present in the room</param>
        /// <param name="roomId">The roomId to check against</param>
        /// <returns>True only if the context can be found in the gameRoom</returns>
        public async Task<bool> IsValidGameRoomUser(HubCallerContext context, string roomId)
        {
            var gameRoom = this.scaleoutService.Get(Persist.GameRoom, roomId) as GameRoom;

            if(gameRoom != null && !string.IsNullOrWhiteSpace(roomId))
            {
                foreach(Player player in gameRoom.Players)
                {
                    if(player.Context.ConnectionId == context.ConnectionId)
                    {
                        return true;
                    }
                }
                throw new HttpException(500, "User is not authorized for game room ");
            }
            throw new HttpException(401, "Game room not found");
        }
        public void Subscribe(HubCallerContext context, string typeName, IEnumerable<string> genericArguments, dynamic constraint, int? constraintId)
        {
            lock (this)
            {
                var type = typeFinder.GetEventType(typeName);
                var genericArgumentTypes = genericArguments.Select(typeFinder.GetType).ToList();
                var subscription = new Subscription(type, context.ConnectionId, context.User.Identity.Name, constraint,
                                                    constraintId, genericArgumentTypes);
                subscriptions[type.GUID] = new List<Subscription>(subscriptions[type.GUID]) { subscription };

                if (!userSubscriptions.ContainsKey(context.ConnectionId))
                {
                    userSubscriptions[context.ConnectionId] = new List<Subscription>();
                }
                userSubscriptions[context.ConnectionId] = new List<Subscription>(userSubscriptions[context.ConnectionId]) { subscription };
            }
        }
Example #22
0
        private string GetIpAddress(HubCallerContext context)
        {
            string ipAddress;
            object tempObject;

            context.Request.Environment.TryGetValue("server.RemoteIpAddress", out tempObject);

            if (tempObject != null)
            {
                ipAddress = (string)tempObject;
            }
            else
            {
                ipAddress = "";
            }

            return ipAddress;
        }
Example #23
0
        private static async Task<Token> GetTokenAsync(string tenant, HubCallerContext context)
        {
            string clientToken = context.Request.GetClientToken();
            var provider = new Provider();
            var token = provider.GetToken(clientToken);

            if (token != null)
            {
                bool isValid = await AccessTokens.IsValidAsync(tenant, token.ClientToken, context.Request.GetClientIpAddress(), context.Headers["User-Agent"]).ConfigureAwait(false);

                if (isValid)
                {
                    return token;
                }
            }

            return null;
        }
Example #24
0
        public TestableLoadHub()
        {
            const string connectionId = "1234";
            const string hubName = "LoadHub";
            var resolver = new DefaultDependencyResolver();
            Config = resolver.Resolve<IConfigurationManager>();

            var mockConnection = new Mock<IConnection>();
            var mockUser = new Mock<IPrincipal>();
            var mockHubPipelineInvoker = new Mock<IHubPipelineInvoker>();

            var mockRequest = new Mock<IRequest>();
            mockRequest.Setup(r => r.User).Returns(mockUser.Object);

            var tracker = new StateChangeTracker();

            Clients = new HubConnectionContext(mockHubPipelineInvoker.Object, mockConnection.Object, hubName, connectionId, tracker);
            Context = new HubCallerContext(mockRequest.Object, connectionId);
        }
Example #25
0
        private void InitializeHub(string name)
        {
            const string connectionId = "1234";
            //const string hubName = "Authenticating";
            //var mockConnection = new Mock<IConnection>();
            var mockRequest = new Mock<IRequest>();

            if (name != null)
            {
                var mockUser = new GenericPrincipal(new UserViewModel { Name = name }, null);
                mockRequest.Setup(r => r.User).Returns(mockUser);
            }

            mockRequest.Setup(r => r.Cookies).Returns(new Dictionary<string, Cookie>());

            //Clients = new ClientProxy(mockConnection.Object, hubName);
            Context = new HubCallerContext(mockRequest.Object, connectionId);

            //Caller = new StatefulSignalProxy(mockConnection.Object, connectionId, hubName, trackingDictionary);
        }
Example #26
0
        public async Task<GameRoom> IncrementRoundAsync(HubCallerContext context, string roomId)
        {

            var gameRoom = this.scaleoutService.Get(Persist.GameRoom, roomId) as GameRoom;

            foreach(var player in gameRoom.Players)
            {
                this.scaleoutService.Subscribe(Persist.GameRound, roomId, player.Context);
            }

            var success = await this.gameRoundService.ProcessRoundAsync(roomId);
            if(success)
            {
                lock(gameRoom)
                {
                    gameRoom.CurrentRound += 1;
                    gameRoom.CurrentRoundStartTime = DateTime.UtcNow;
                    this.scaleoutService.Notify(Persist.GameRoom, gameRoom.Id, gameRoom);
                    return gameRoom;
                }
            }

            return null;
        }
Example #27
0
 public string GetUsername(HubCallerContext context)
 {
     return context.QueryString[QueryStrings.Username];
 }
Example #28
0
 public User(HubCallerContext context)
 {
     IpAddress = GetIpAddress(context);
 }
Example #29
0
        internal static List<ChatUser> RetrieveFriends(HubCallerContext context)
        {
            var token = context.QueryString["token"];
            var friends = configuration.retrieveFriends(token);

            return friends.ToList();
        }
 /// <summary>
 /// 是否开启通信加密功能
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 protected virtual bool CanCrypto(HubCallerContext context)
 {
     return true;
 }