/// <summary>
        /// 根据url上面的ticket获取token
        /// </summary>
        /// <param name="from"></param>
        /// <param name="ticket"></param>
        /// <param name="audience"></param>
        /// <returns></returns>
        public string GetTokenByTicket(string from, string ticket, string audience)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl.TrimEnd('/') + "/sso/gettoken?from=" + from + "&ticket=" + ticket + "&ip=" + audience);

            request.Method = "get";
            using (WebResponse response = request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string       resp   = reader.ReadToEnd();
                var          result = JsonSerializerHelper.Deserialize <ServiceModel <string> >(resp);
                if (result.code == 0)
                {
                    return(result.result);
                }
                return("");
            }
        }
Beispiel #2
0
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="from"></param>
        /// <param name="filter"></param>
        /// <param name="fileType"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="sorts"></param>
        /// <param name="delete"></param>
        /// <returns></returns>
        public ServiceModel <List <FileItem> > GetFileList(int pageIndex = 1, int pageSize = 10, string from = "", string filter = "", string fileType = "", DateTime?startTime = null, DateTime?endTime = null, Dictionary <string, string> sorts = null, bool delete = false)
        {
            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", Token);
            var url = RemoteUrl + "/data/GetFiles?pageIndex=" + pageIndex + "&pageSize=" + pageSize;

            if (!from.IsNullOrEmpty())
            {
                url += "&from=" + from;
            }
            if (!filter.IsNullOrEmpty())
            {
                url += "&filter=" + filter;
            }
            if (!fileType.IsNullOrEmpty())
            {
                url += "&fileType=" + fileType;
            }
            if (startTime != null)
            {
                url += "&startTime=" + startTime.Value.ToString(AppSettings.DateTimeFormat);
            }
            if (endTime != null)
            {
                url += "&endTime=" + endTime.Value.ToString(AppSettings.DateTimeFormat);
            }
            var index = 0;

            if (sorts != null)
            {
                foreach (var item in sorts)
                {
                    var key   = item.Key;
                    var value = item.Value;
                    url += "&sorts[" + index + "].key=" + key;
                    url += "&sorts[" + index + "].value=" + value;
                    index++;
                }
            }
            url += "&delete=" + delete;
            string list = requestHelper.Get(url, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <FileItem> > >(list));
        }
        /// <summary>
        /// 获取日志对象列表
        /// </summary>
        /// <param name="from"></param>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <param name="sorts"></param>
        /// <param name="exception"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ServiceModel <List <LogModel> > GetList(string from = null, string to = null, string controller = null, string action = null, DateTime?startTime = null, DateTime?endTime = null, string userId = null, string userName = null, Dictionary <string, string> sorts = null, bool?exception = null, int pageIndex = 1, int pageSize = 10)
        {
            LogListModel logModel = new LogListModel()
            {
                From           = from,
                To             = to,
                ControllerName = controller,
                ActionName     = action,
                StartTime      = startTime,
                EndTime        = endTime,
                UserId         = userId,
                UserName       = userName,
                Sorts          = sorts,
                Exception      = exception,
                PageIndex      = pageIndex,
                PageSize       = pageSize
            };
            var result = requestHelper.Post(baseUrl + "/log/getlist?", logModel, null);;

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <LogModel> > >(result));
        }
        private bool CheckPermission(string permission, string authorization)
        {
            if (permission.IsNullOrEmpty())
            {
                return(true);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl.TrimEnd('/') + "/permission/checkPermission?permissionName=" + permission);

            request.Method = "get";
            request.Headers.Add("Authorization", authorization);
            using (WebResponse response = request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string       resp   = reader.ReadToEnd();
                var          result = JsonSerializerHelper.Deserialize <ServiceModel <string> >(resp);
                if (result.code == 0)
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// 获取user详情
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ServiceModel <UserDetail> GetUserDetail(string userId)
        {
            string user = requestHelper.Get(RemoteUrl + "/user/getByUserId?userId=" + userId, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <UserDetail> >(user));
        }
        /// <summary>
        /// 通过id获取日志详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ServiceModel <LogModel> GetById(string id)
        {
            var result = requestHelper.Get(baseUrl + "/log/getbyid/" + id, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <LogModel> >(result));
        }
        /// <summary>
        /// 获取from中action列表
        /// </summary>
        /// <param name="to"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        public ServiceModel <List <ActionCountModel> > GetActionsByController(string to, string controllerName)
        {
            var result = requestHelper.Get(baseUrl + "/log/getactionsbycontroller?to=" + to + "&controllerName=" + controllerName, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <ActionCountModel> > >(result));
        }
        /// <summary>
        /// 统计昨天,上月,全部日志
        /// </summary>
        /// <returns></returns>
        public ServiceModel <OperationsCountModel> GetOperations()
        {
            var result = requestHelper.Get(baseUrl + "/log/getoperations", null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <OperationsCountModel> >(result));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            var actionDescriptor = (ControllerActionDescriptor)filterContext.ActionDescriptor;
            IEnumerable <CustomAttributeData> methodAttributes     = actionDescriptor.MethodInfo.CustomAttributes;
            IEnumerable <CustomAttributeData> controllerAttributes = actionDescriptor.ControllerTypeInfo.CustomAttributes;
            bool   isAuthorization = true;
            string permissionName  = "";

            foreach (CustomAttributeData item in controllerAttributes)
            {
                if (item.AttributeType.Name == "AllowAnonymousAttribute")
                {
                    isAuthorization = false;
                }
                if (item.AttributeType.Name == "SSOAuthorizeAttribute")
                {
                    isAuthorization = true;
                    if (item.ConstructorArguments.Count > 0)
                    {
                        permissionName = item.ConstructorArguments[0].Value.ToString();
                    }
                }
            }
            foreach (CustomAttributeData item in methodAttributes)
            {
                if (item.AttributeType.Name == "AllowAnonymousAttribute")
                {
                    isAuthorization = false;
                }
                if (item.AttributeType.Name == "SSOAuthorizeAttribute")
                {
                    isAuthorization = true;
                    if (item.ConstructorArguments.Count > 0)
                    {
                        permissionName = item.ConstructorArguments[0].Value.ToString();
                    }
                }
            }
            if (!isAuthorization)
            {
                return;
            }
            //验证配置文件
            if (!VerifyConfig(filterContext))
            {
                return;
            }
            HttpRequest request     = filterContext.HttpContext.Request;
            var         ssourl      = request.Query["ssourls"];
            var         absoluteUrl = AppSettings.GetAbsoluteUri(request);

            if (!string.IsNullOrEmpty(ssourl)) //sso 退出
            {
                var returnUrl = request.Query["returnUrl"];
                ////////清除本站cookie
                List <string> ssoUrls = JsonSerializerHelper.Deserialize <List <string> >(Encoding.UTF8.GetString(Convert.FromBase64String(Base64SecureURL.Decode(ssourl))));
                var           cookie  = request.Cookies[CookieKey];
                if (cookie != null)
                {
                    filterContext.HttpContext.Response.Cookies.Delete(CookieKey);
                }
                /////////////////////
                for (var i = 0; i < ssoUrls.Count; i++)
                {
                    if (absoluteUrl.Contains(ssoUrls[i]))
                    {
                        ssoUrls.RemoveAt(i);
                        break;
                    }
                }
                if (ssoUrls.Count > 0)
                {
                    string newSsoUrls = JsonSerializerHelper.Serialize(ssoUrls);
                    filterContext.Result = new RedirectResult(ssoUrls[0] + "?ssourls=" + newSsoUrls.StrToBase64() + "&returnUrl=" + returnUrl);
                }
                else //最后一个
                {
                    filterContext.Result = new RedirectResult(BaseUrl + "?returnUrl=" + returnUrl);
                }
                return;
            }
            string authorization = JwtManager.GetAuthorization(request, CookieKey);
            string ticket        = request.Query["ticket"];

            if (string.IsNullOrEmpty(authorization))
            {
                if (string.IsNullOrEmpty(ticket))
                {
                    filterContext.Result = GetActionResult(absoluteUrl);
                    return;
                }
                else
                {
                    string from = AppSettings.GetApplicationUrl(request).ReplaceHttpPrefix().TrimEnd('/');
                    authorization = GetTokenByTicket(from, ticket, request.HttpContext.Connection.RemoteIpAddress.ToString());
                    if (!string.IsNullOrEmpty(authorization))
                    {
                        if (CookieTime != "session")
                        {
                            filterContext.HttpContext.Response.Cookies.Append(CookieKey, authorization, new CookieOptions()
                            {
                                Expires = DateTime.Now.AddMinutes(Convert.ToInt32(CookieTime))
                            });
                        }
                        else
                        {
                            filterContext.HttpContext.Response.Cookies.Append(CookieKey, authorization);
                        }
                    }
                    else
                    {
                        filterContext.Result = GetActionResult(absoluteUrl);
                        return;
                    }
                }
            }
            try
            {
                var principal = JwtManager.ParseAuthorization(authorization, SecretKey, filterContext.HttpContext);
                filterContext.HttpContext.User = principal;
                if (!CheckPermission(permissionName, authorization))
                {
                    filterContext.Result = new ResponseModel <string>(ErrorCode.error_permission, "");
                }
            }
            catch (Exception ex) //token失效
            {
                Log4Net.ErrorLog(ex);
                var httpCookie = filterContext.HttpContext.Request.Cookies[CookieKey];
                if (httpCookie != null)
                {
                    filterContext.HttpContext.Response.Cookies.Delete(CookieKey);
                }
                filterContext.Result = GetActionResult(absoluteUrl);
            }
        }
        /// <summary>
        /// 获取to中Controller列表
        /// </summary>
        /// <param name="to"></param>
        /// <returns></returns>
        public ServiceModel <List <ControllerCountModel> > GetControllersByTo(string to)
        {
            var result = requestHelper.Get(baseUrl + "/log/getcontrollersbyto?to=" + to, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <ControllerCountModel> > >(result));
        }
        /// <summary>
        /// 添加调度任务
        /// </summary>
        /// <param name="machineName"></param>
        /// <param name="schedulingId"></param>
        /// <param name="triggerId"></param>
        /// <param name="schedulingState"></param>
        /// <returns></returns>
        public ServiceModel <string> InsertTaskScheduling(string machineName, int schedulingId, int triggerId, int schedulingState)
        {
            var result = requestHelper.Post(baseUrl.TrimEnd('/') + "/TaskScheduling/insert", new { machineName, schedulingId, triggerId, schedulingState }, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }
        /// <summary>
        /// 替换权限项
        /// </summary>
        /// <param name="origin">项目标记</param>
        /// <param name="names">权限列表</param>
        /// <returns></returns>
        public ServiceModel <string> ReplacePermissions(string origin, IEnumerable <string> names)
        {
            string result = requestHelper.Post(RemoteUrl + "/permission/add", new { Origin = origin, Names = names }, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }
        /// <summary>
        /// 获取最新的日志,按天统计
        /// </summary>
        /// <param name="last">最近多少天</param>
        /// <returns></returns>
        public ServiceModel <List <LogOpCountModel> > GetOpRecordByDay(int last = 30)
        {
            var result = requestHelper.Get(baseUrl + "/log/recordbyday?last=" + last, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <LogOpCountModel> > >(result));
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ServiceModel <List <RoleItem> > GetRoleList(string filter = "", int pageIndex = 1, int pageSize = 10)
        {
            string roles = requestHelper.Get(RemoteUrl + "/role/getlist?filter=" + filter + "&pageIndex=" + pageIndex + "&pageSize=" + pageSize, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <RoleItem> > >(roles));
        }
        /// <summary>
        /// 获取user列表
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="companyCode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ServiceModel <List <UserItem> > GetUserList(string companyCode = "", string filter = "", int pageIndex = 1, int pageSize = 10)
        {
            string users = requestHelper.Get(RemoteUrl + "/user/getBasic?companyCode=" + companyCode + "&filter=" + filter + "&orderField=UserName&orderType=asc&pageIndex=" + pageIndex + "&pageSize=" + pageSize, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <UserItem> > >(users));
        }
        /// <summary>
        /// 获取指定department列表
        /// </summary>
        /// <param name="companyCode"></param>
        /// <returns></returns>
        public ServiceModel <List <DepartmentItem> > GetAllDepartment(string companyCode)
        {
            string departments = requestHelper.Get(RemoteUrl + "/department/getDepartments?companyCode=" + companyCode, headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <DepartmentItem> > >(departments));
        }
        /// <summary>
        /// 获取所有company
        /// </summary>
        /// <returns></returns>
        public ServiceModel <List <CompanyItem> > GetAllCompany()
        {
            string companys = requestHelper.Get(RemoteUrl + "/company/getall", headers);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <CompanyItem> > >(companys));
        }
        /// <summary>
        /// 获取from列表
        /// </summary>
        /// <returns></returns>
        public ServiceModel <List <FromCountModel> > GetFromList()
        {
            var result = requestHelper.Get(baseUrl + "/log/getfromlist", null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <List <FromCountModel> > >(result));
        }
        /// <summary>
        /// 添加转换任务
        /// </summary>
        /// <param name="machineName">发往那个机器</param>
        /// <param name="collectionName"></param>
        /// <param name="collectionId"></param>
        /// <returns></returns>
        public ServiceModel <string> InsertConvertTask(string machineName, string collectionName, string collectionId)
        {
            var result = requestHelper.Post(baseUrl.TrimEnd('/') + "/filetask/insert", new { machineName, collectionName, collectionId }, null);

            return(JsonSerializerHelper.Deserialize <ServiceModel <string> >(result));
        }