Example #1
0
 private void AuthHandler(object sender, WsRequest <AuthRequestContent> args)
 {
     if (CheckToken(args.content.token))
     {//认证通过
         this._isAuth = true;
         if (CheckSession(args.content.sessionId))
         {//session存在
             this._sessionId = args.content.sessionId;
             var res = new WsResponse <object> {
                 resID = args.reqID, resType = ResponseType.subscribe.ToString(), content = new { result = 1 }
             };
             this.SendMsg <WsResponse <object> >(res);//订阅成功消息
             //立即推送位号数据
             PushData(null);
         }
         else
         {//session不存在
             this._sessionId = Guid.NewGuid().ToString();
             var res = new WsResponse <AuthResponseContent> {
                 resID = args.reqID, resType = ResponseType.request.ToString(), content = new AuthResponseContent {
                     auth = "1", sessionId = this._sessionId
                 }
             };
             this.SendMsg <WsResponse <AuthResponseContent> >(res);//返回session
         }
         //心跳检测,30秒检测一次
         this._lastHearBeat    = DateTime.Now;
         this._hearBeatMonitor = new Timer(this.HearBeatCheck, null, 2000, 30000);
     }
     else
     {
         this._webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "authentication failed", CancellationToken.None);
     }
 }
Example #2
0
        private void ProcessMessage(byte[] receivedData)
        {
            // parsing response
            using (MemoryStream responseStream = new MemoryStream(receivedData))
            {
                WsResponse response = ProtoBuf.Serializer.Deserialize <WsResponse>(responseStream);

                _newMessage.Enqueue(response);
            }
        }
        /// <summary>
        /// Check permission according to the functions
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var bizContext           = context.HttpContext.RequestServices.GetService(typeof(BizContext)) as BizContext;
            var authorizationHandler = context.HttpContext.RequestServices.GetService(typeof(IAuthorizationHandler)) as IAuthorizationHandler;

            // if no login, pass 401 error
            if (bizContext.LoginUser == null)
            {
                var response = new WsResponse();
                response.Trans.ErrorCode = "401";
                response.Trans.ErrorMsg  = "Not login";
                var result = new JsonResult(response);
                result.StatusCode = 401;
                context.Result    = result;
            }
            else
            {
                // Check does the user can access these funcs
                var funcCount = this.functions.Length;
                int passedCount = 0, failedCount = 0;
                foreach (var funcCode in this.functions)
                {
                    var hasPermission = authorizationHandler.CheckFunction(bizContext.LoginUser.UserId.ToString(), funcCode);
                    if (hasPermission)
                    {
                        passedCount++;
                    }
                    else
                    {
                        failedCount++;
                    }
                }

                // If there are no func need check
                // or all successful, then passed
                // or one of them passed and passedByOneOf is true, then passed
                if (funcCount == 0 ||
                    failedCount == 0 ||
                    (this.passedByOneOf && passedCount > 0))
                {
                    base.OnActionExecuting(context);
                }
                else
                {
                    var response = new WsResponse();
                    response.Trans.ErrorCode = "403";
                    response.Trans.ErrorMsg  = "Authorization Failed";
                    var result = new JsonResult(response);
                    result.StatusCode = 403;
                    context.Result    = result;
                }
            }
        }
        /// <summary>
        /// On authorization
        /// </summary>
        /// <param name="context"></param>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var tokenHandler = context.HttpContext.RequestServices.GetService(typeof(ITokenHandler)) as ITokenHandler;
            var bizContext   = context.HttpContext.RequestServices.GetService(typeof(BizContext)) as BizContext;

            bizContext.TokenHandler = tokenHandler;

            var token = context.HttpContext.Request.Headers["token"];

            bizContext.Token = token;
            if (!string.IsNullOrEmpty(token))
            {
                bizContext.LoginUser = tokenHandler.GetAssociateObjectByToken <LoginUser>(token);
            }

            if (bizContext.Configuration.NeedCheckPermissionFromUrl)
            {
                var url = context.HttpContext.Request.Path.Value;
                var authorizationHandler = context.HttpContext.RequestServices.GetService(typeof(IAuthorizationHandler)) as IAuthorizationHandler;
                var isPassed             = authorizationHandler.CheckUrl(bizContext.LoginUser != null ? bizContext.LoginUser.UserId.ToString() : null,
                                                                         url,
                                                                         bizContext.Configuration.IgnoreCheckPermissionUrls,
                                                                         bizContext.Configuration.IgnoreCheckPermissionUrlsWhenLogined);
                if (isPassed)
                {
                    return;           // passed check permission
                }
                // failed to check url according permission
                if (bizContext.LoginUser == null)
                {
                    var response = new WsResponse();
                    response.Trans.ErrorCode = "401";
                    response.Trans.ErrorMsg  = "Not login";
                    var result = new JsonResult(response);
                    result.StatusCode = 401;
                    context.Result    = result;
                }
                else
                {
                    var response = new WsResponse();
                    response.Trans.ErrorCode = "403";
                    response.Trans.ErrorMsg  = "Authorization Failed";
                    var result = new JsonResult(response);
                    result.StatusCode = 403;
                    context.Result    = result;
                }
            }
        }
Example #5
0
        private static void Conn_NewMessage(WsResponse data)
        {
            if (!string.IsNullOrEmpty(data.I))
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"{DateTime.Now} ");
                Console.ResetColor();
                Console.Write("- ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write($"Invocation Succeeded For Id: {data.I} \r\n");
                Console.ResetColor();
                return;
            }
            foreach (var msg in data.M)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write($"{DateTime.Now} ");
                Console.ResetColor();
                Console.Write("- ");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write($"Hub: {msg.H} ");
                Console.ResetColor();
                Console.Write("- ");
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write($"Method: {msg.M} \r\n");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("Data: ");
                Console.ResetColor();
                foreach (var a in msg.A)
                {
	                using (var inputStream = new MemoryStream(Convert.FromBase64String((string)a)))
	                using (var gZipStream = new DeflateStream(inputStream, CompressionMode.Decompress))
	                using (var streamReader = new StreamReader(gZipStream))
	                {
		                var decompressed = streamReader.ReadToEnd();

		                Console.Write($"{decompressed} \r\n");
	                }
                }
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("---------------- End Of Message ----------------");
                Console.ResetColor();
            }
        }
Example #6
0
        public Task <WsResponse> HandleRequest(WsRequest request)
        {
            var response = new WsResponse();

            var     data    = request.GetJson();
            var     message = data.message;
            dynamic value   = null;

            switch ((string)message.InterfaceName)
            {
            case "setAttributeInfo":
                value = "hello world";
                break;

            default:
                Log.W($"Unknwon interface name: {message.InterfaceName}");
                break;
            }

            var result = new
            {
                protocolType = "general",
                message      = new
                {
                    message.InterfaceName,
                    message.MessageUID,
                    message.SessionID,
                    InterfaceErrorCode    = 0,
                    InterfaceErrorMessage = "",
                    ReturnValue           = value,
                    ReturnType            = value is int? "number" : "string",
                },
            };

            response.SetJson(result);

            return(Task.FromResult(response));
        }
Example #7
0
        private void SubscribeHandler(object sender, WsRequest <SubscribeRequestContent> args)
        {
            if (!this._isAuth)
            {
                this._webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "authentication failed", CancellationToken.None);
                return;
            }

            //订阅数据
            this.Subscribe(args.content.body);

            //响应客户端订阅
            var res = new WsResponse <object> {
                resID = args.reqID, resType = RequestType.subscribe.ToString(), content = new { result = "1" }
            };

            this.SendMsg <WsResponse <object> >(res);

            if (this._dataPushTimer == null)
            {
                this._dataPushTimer = new Timer(this.PushData, null, 0, 2000);
            }
        }
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);
            var response  = new WsResponse();
            var exception = context.Exception;

            if (exception is SpException)
            {
                // It is business error. Just log it.
                var spException = exception as SpException;
                response.Trans.ErrorCode = spException.ErrorCode;
                Logger.Error(exception);
            }
            else
            {
                // It is unknown exception, It must resolve by developer is these kind of error occur
                response.Trans.ErrorCode = "9999";
                Logger.Fatal(exception);

                // Log as detail as possible
                var request = context.HttpContext.Request;
                Logger.Fatal("Request url: " + request.Path);
                Logger.Fatal("Request Query String: " + request.QueryString.ToString());
                request.Body.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(request.Body))
                {
                    var bodyContent = reader.ReadToEnd();
                    Logger.Fatal("Request body: " + bodyContent);
                }
            }

            response.Trans.ErrorMsg = exception.Message;
            var result = new JsonResult(response);

            result.StatusCode = 404;
            context.Result    = result;
        }
Example #9
0
 private static void Conn_NewMessage(WsResponse data)
 {
     if (!string.IsNullOrEmpty(data.I))
     {
         Console.ForegroundColor = ConsoleColor.Yellow;
         Console.Write($"{DateTime.Now} ");
         Console.ResetColor();
         Console.Write("- ");
         Console.ForegroundColor = ConsoleColor.Green;
         Console.Write($"Invocation Sucedded For Id: {data.I} \r\n");
         Console.ResetColor();
         return;
     }
     foreach (var msg in data.M)
     {
         Console.ForegroundColor = ConsoleColor.Yellow;
         Console.Write($"{DateTime.Now} ");
         Console.ResetColor();
         Console.Write("- ");
         Console.ForegroundColor = ConsoleColor.Red;
         Console.Write($"Hub: {msg.H} ");
         Console.ResetColor();
         Console.Write("- ");
         Console.ForegroundColor = ConsoleColor.Blue;
         Console.Write($"Method: {msg.M} \r\n");
         Console.ForegroundColor = ConsoleColor.Green;
         Console.Write("Data: ");
         Console.ResetColor();
         foreach (var a in msg.A)
         {
             Console.Write($"{a} \r\n");
         }
         Console.ForegroundColor = ConsoleColor.Cyan;
         Console.WriteLine("---------------- End Of Message ----------------");
         Console.ResetColor();
     }
 }
Example #10
0
        public Task <WsResponse> HandleRequest(WsRequest request)
        {
            var response = new WsResponse();

            var data = request.GetJson();

            if (data == null)
            {
                return(Task.FromResult(response));
            }

            dynamic result        = null;
            dynamic callbackReply = null;

            if (data.init != null)
            {
                switch ((string)data.init)
                {
                case "get_versions":
                    result = new
                    {
                        tabid  = data.tabid,
                        daemon = "9.9.9.9",
                        ex     = "9.9.9.9",
                        m      = new[] { new { name = data.m, version = "9.9.9.9" } }
                    };
                    break;

                default:
                    Log.W($"Unknwon init command: {data.init}");
                    break;
                }
            }
            else if (data.cmd != null)
            {
                var     callback = data.callback;
                dynamic reply    = null;
                switch ((string)data.cmd)
                {
                case "setcallback":
                    reply = "";
                    break;

                case "native":
                    var args = data.exfunc.args;
                    switch ((string)data.exfunc.fname)
                    {
                    case "Request":
                        dynamic requestParams = JsonConvert.DeserializeObject((string)args[0]);
                        switch ((string)requestParams.key)
                        {
                        case "Clear":
                            callbackReply = new { InputClear = requestParams.elename };
                            break;

                        case "InvalidateSession":
                            break;

                        default:
                            Log.W($"Unknown request type: {requestParams.key}");
                            break;
                        }
                        reply = "";
                        break;

                    case "Key_Init":
                        reply = new
                        {
                            result = "true",
                            isvm   = "false",
                        };
                        callbackReply = new
                        {
                            SeedKey = "SeedKey",
                            value   = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
                        };
                        break;

                    case "Key_Start":
                        reply = "StartReadyComplete";
                        // callbackReply = new { addChar = $"a_#_{args[1]}" };
                        break;

                    case "Key_Keydown":
                        reply = "";
                        break;

                    case "Key_Stop":
                        reply         = "";
                        callbackReply = new { GetActiveElement = args[2] };
                        break;

                    case "Key_RealStop":
                        reply = "";
                        break;

                    default:
                        Log.W($"Unknown native call: {data.exfunc.fname}");
                        break;
                    }
                    break;

                default:
                    Log.W($"Unknwon command: {data.cmd}");
                    break;
                }

                result = new
                {
                    response = new
                    {
                        id       = data.id,
                        tabid    = data.tabid,
                        status   = "TRUE",
                        reply    = new { reply = new { status = "0", reply = reply } },
                        callback = callback ?? "",
                    }
                };
            }

            response.SetJson(result);

            if (callbackReply != null)
            {
                var callbackResult = new
                {
                    response = new
                    {
                        id       = "setcallback",
                        callback = "update_callback",
                        reply    = callbackReply,
                    }
                };

                var callbackResponse = new WsResponse();
                callbackResponse.SetJson(callbackResult);
                response.Additional = callbackResponse;
            }

            return(Task.FromResult(response));
        }
Example #11
0
        public async Task WsHandler(WebSocket socket)
        {
            //认证消息验证
            if (socket.State == WebSocketState.Open)
            {
                var buffer = new byte[1024 * 4];
                var result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                var  reqAuth = GetReceiveObj <WsRequest <AuthRequestContent> >(buffer);
                bool isAuth  = true;
                if (isAuth)
                {//验证成功
                    string sessionId = HttpContext.Session.Id;
                    var    resAuth   = new WsResponse <AuthResponseContent> {
                        resID = reqAuth.reqID, resType = RequestType.request.ToString(), content = new AuthResponseContent {
                            auth = Convert.ToInt32(true).ToString(), sessionId = sessionId
                        }
                    };
                    var sendBuffer = GetSendBuffer <WsResponse <AuthResponseContent> >(resAuth);
                    await socket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);

                    //session相关操作,如缓存一些连接信息
                }
                else
                {//验证失败
                    var resAuth = new WsResponse <object> {
                        resID = reqAuth.reqID, resType = RequestType.request.ToString(), content = new { auth = Convert.ToInt32(false).ToString() }
                    };
                    var sendBuffer = GetSendBuffer <WsResponse <object> >(resAuth);
                    await socket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);

                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "认证失败,断开socket通道", CancellationToken.None);
                }
            }

            //等待接收订阅消息
            if (socket.State == WebSocketState.Open)
            {//1.接收心跳包,2.接收订阅消息,3.响应订阅请求
                var buffer = new byte[1024 * 4];
                var result = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                var req = GetReceiveObj <WsRequest <object> >(buffer);
                if (req.reqType == RequestType.heartbreak.ToString())
                {//接收订阅消息
                    await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                    var reqSub = GetReceiveObj <WsRequest <SubscribeRequestContent> >(buffer);
                    //去订阅位号数据
                    this.Subscribe(reqSub.content.body);


                    //响应订阅请求
                    bool subFlag = true;
                    var  resSub  = new WsResponse <object> {
                        resID = reqSub.reqID, resType = ResponseType.subscribe.ToString(), content = new { result = Convert.ToInt32(subFlag).ToString() }
                    };
                    var sendBuffer = GetSendBuffer <WsResponse <object> >(resSub);
                    await socket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {//继续接收心跳包
                }
            }

            //推送实时数据()
            while (socket.State == WebSocketState.Open)
            {//1.推送实时数据,2.
                var resData = new DataPushResponse {
                    resType = ResponseType.push.ToString(), content = new DataPushContent {
                        subType = "device_prop", body = new Dictionary <string, IEnumerable <TagDataPush> >()
                    }
                };
                resData.content.body.Add("device - 1:prop1", new List <TagDataPush> {
                    new TagDataPush {
                        value = "0.85262805", status = TagDataStatus.normal, timestamp = 1524185355322
                    }
                });
                resData.content.body.Add("device - 1:prop2", new List <TagDataPush> {
                    new TagDataPush {
                        value = "0.6905742", status = TagDataStatus.normal, timestamp = 1524185355322
                    }
                });
                var sendBuffer = GetSendBuffer <DataPushResponse>(resData);
                await socket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
        public ActionResult <WsResponse <int> > GetUserCount([FromBody] WsListRequest <string> req)
        {
            WsResponse <int> result = this.userManager.GetUserCount(req.Condition);

            return(result);
        }