示例#1
0
        public async Task <IActionResult> WxLoginAsync(WxLoginParam loginParam)
        {
            // 使用IHttpClientFactory创建的HttpClient
            OpenIdParam openIdParam = await WxUtils.GetOpenIdAsync(loginParam, clientFactory.CreateClient());

            if (openIdParam == null || string.IsNullOrEmpty(openIdParam.session_key))
            {
                return(ValidationProblem("验证错误,Secret可能失效"));
            }
            WxPhoneModel wxPhoneModel = WxAppEncryptUtil.GetEncryptedDataStr(loginParam.EncryptedData, openIdParam.session_key, loginParam.Iv);

            if (wxPhoneModel == null)
            {
                return(ValidationProblem("用户信息解析错误"));
            }
            string phone = wxPhoneModel.PurePhoneNumber ?? wxPhoneModel.PhoneNumber;

            if (string.IsNullOrEmpty(phone))
            {
                return(ValidationProblem("可能未绑定手机号"));
            }
            TbUser user = await rep.GetEntityAsync(s => s.Phone.Equals(phone), s => new TbUser {
                State = s.State
            });

            if (user == null)
            {
                return(ValidationProblem("用户未注册"));
            }
            string token = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);

            return(Ok(new { access_token = token }));
        }
示例#2
0
        public async Task <IActionResult> LoginAsync(LoginModel model)
        {
            TbUser user = await rep.GetEntityAsync(s => s.Name.Equals(model.name));

            if (user == null)
            {
                return(NotFound($"用户名'{model.name}'不存在"));
            }
            if (!WxAppEncryptUtil.MD5(model.pwd).Equals(user.Pwd))
            {
                return(ValidationProblem(new ValidationProblemDetails()
                {
                    Detail = "密码错误"
                }));
            }

            string   token     = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);
            DateTime authTime  = DateTime.Now;
            DateTime expiresAt = authTime.AddMinutes(30);

            return(Ok(new
            {
                access_token = token,
                token_type = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme,
                profile = new
                {
                    sid = user.Id,
                    name = user.Name,
                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            }));
        }
示例#3
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (!(context.ActionDescriptor is ControllerActionDescriptor))
            {
                return;
            }

            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            #region 根据反射获取自定义验证特性,判断是否需要验证
            ControllerActionDescriptor cad = context.ActionDescriptor as ControllerActionDescriptor;
            bool r1 = cad.ControllerTypeInfo.CustomAttributes.Any(s => s.AttributeType.Name.Equals("AuthorizeAttribute"));
            bool r2 = cad.MethodInfo.CustomAttributes.Any(s => s.AttributeType.Name.Equals("AuthorizeAttribute"));
            if (!r1 && !r2)
            {
                return;
            }

            if (cad.MethodInfo.CustomAttributes.Any(s => s.AttributeType.Name.Equals("AllowAnonymousAttribute")))
            {
                return;
            }

            string actionName     = cad.ActionName;
            string controllerName = cad.ControllerName;
            #endregion

            bool rs      = context.HttpContext.Request.Headers.TryGetValue("token", out Microsoft.Extensions.Primitives.StringValues strValues);
            bool vaildRs = false;
            if (rs)
            {
                vaildRs = AuthorizationUtil.VerifyToken(strValues.ToString(), out TimeSpan validTime, out ClaimsIdentity claimsIdentity);
                if (vaildRs)
                {
                    List <Claim> list      = new List <Claim>(claimsIdentity.Claims);
                    Claim        roleClaim = list.Find(s => s.Type.Contains(JwtClaimTypes.Role));
                    if (roleClaim != null)
                    {
                        //Todo:根据 actionName,controllerName,roleClaim判断是否有权限
                        bool hadPower = true;
                        if (!hadPower)
                        {
                            context.Result = new ForbidResult();
                            return;
                        }
                    }
                }
            }

            if (!rs || !vaildRs)
            {
                context.Result = new UnauthorizedResult();
            }

            return;
        }
        public void SetUp()
        {
            var unitOfWorkFactory = Substitute.For <IUnitOfWorkFactory>();

            _unitOfWork = Substitute.For <IUnitOfWork>();
            unitOfWorkFactory.CreateUnitOfWork().Returns(_unitOfWork);
            _userRepository = Substitute.For <IUserRepository>();
            _unitOfWork.Users.Returns(_userRepository);
            _authorizationUtil = new AuthorizationUtil(unitOfWorkFactory);
        }
示例#5
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Model.Usuario user = null;

            if (AuthorizationUtil.IsValid(request.Headers.Authorization, out user))
            {
                var roles     = IdentityUtil.GetRoles(user);
                var principal = new GenericPrincipal(new GenericIdentity(user.Nome), roles);

                CurrentPrincipalUtil.SetPrincipal(principal);
            }

            return(base.SendAsync(request, cancellationToken));
        }
示例#6
0
        public void ProcessRequest(HttpContext context)
        {
            // Negotiate with the request limiter (if enabled)
            if (_requestLimiter != null)
            {
                if (!_requestLimiter.ClientLimitOK(context.Request))
                {
                    // Deny request
                    // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
                    context.Response.AppendHeader("Retry-After", _requestLimiter.LimiterTimeSpan.ToString());
                    throw new HttpException(429, "429 - Too many requests in too short timeframe. Please try again later.");
                }
            }

            // Enable CORS and preflight requests for saved queries
            // Preflight requests should also be allowed in the API (SSDHandler).

            if (Settings.Current.Features.SavedQuery.EnableCORS)
            {
                // Enable CORS (Cross-Origin-Resource-Sharing)
                context.Response.AppendHeader("Access-Control-Allow-Origin", "*");

                // Handle Preflight requests
                if (context.Request.HttpMethod == "OPTIONS")
                {
                    context.Response.AppendHeader("Access-Control-Allow-Methods", "GET");
                    return;
                }
            }

            string queryName;
            var    routeData = context.Items["RouteData"] as RouteData;

            if (routeData.Values["QueryName"] != null)
            {
                queryName = ValidationManager.GetValue(routeData.Values["QueryName"].ToString());
            }
            else
            {
                //No query supplied goto error page.
                //TODO just to shut the compiler up
                queryName = "";
                //TODO redirect
                throw new Exception("No query supplied");
            }

            // ----- Handle changed output format -----
            _format = GetChangedOutputFormat(routeData);

            // ----- Handle changed language -----
            HandleChangedLanguage();

            //Load saved query
            PCAxis.Query.SavedQuery sq = null;
            PXModel model = null;
            bool    safe  = true;

            try
            {
                if (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File)
                {
                    string path = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/queries/");

                    if (!queryName.ToLower().EndsWith(".pxsq"))
                    {
                        queryName = queryName + ".pxsq";
                    }

                    string[] allfiles = Directory.GetFiles(path, queryName, SearchOption.AllDirectories);

                    if (allfiles.Length == 0)
                    {
                        throw new HttpException(404, "HTTP/1.1 404 Not Found ");
                    }

                    queryName = allfiles[0];
                }

                //Check if the database is active.
                //It should not be possible to run a saved query if the database is not active
                sq = PCAxis.Query.SavedQueryManager.Current.Load(queryName);
                IEnumerable <string> db;
                TableSource          src = sq.Sources[0];

                if (src.Type.ToLower() == "cnmm")
                {
                    db = PXWeb.Settings.Current.General.Databases.CnmmDatabases;
                }
                else
                {
                    db = PXWeb.Settings.Current.General.Databases.PxDatabases;
                }
                bool activeDatabase = false;
                foreach (var item in db)
                {
                    if (item.ToLower() == src.DatabaseId.ToLower())
                    {
                        activeDatabase = true;
                        break;
                    }
                }
                if (!activeDatabase)
                {
                    throw new SystemException();
                }


                //Validate that the user has the rights to access the table
                string tableName = QueryHelper.GetTableName(src);
                //if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, src.Source))
                if (!AuthorizationUtil.IsAuthorized(src.DatabaseId, null, tableName)) //TODO: Should be dbid, menu and selection. Only works for SCB right now... (2018-11-14)
                {
                    List <LinkManager.LinkItem> linkItems = new List <LinkManager.LinkItem>();
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = PxUrl.LANGUAGE_KEY, Value = src.Language
                    });
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = PxUrl.DB_KEY, Value = src.DatabaseId
                    });
                    linkItems.Add(new LinkManager.LinkItem()
                    {
                        Key = "msg", Value = "UnauthorizedTable"
                    });

                    string url = LinkManager.CreateLink("~/Menu.aspx", linkItems.ToArray());
                    HttpContext.Current.Response.Redirect(url, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (string.IsNullOrWhiteSpace(_format))
                {
                    //Output format is not changed - use output format in the saved query
                    _format = sq.Output.Type;
                }

                // "Pre-flight" request from MS Office application
                var userAgent = context.Request.Headers["User-Agent"];
                //if (userAgent.ToLower().Contains("ms-office") && sq.Output.Type == PxUrl.VIEW_TABLE_IDENTIFIER)
                if (userAgent != null && userAgent.ToLower().Contains("ms-office"))
                {
                    context.Response.Write("<html><body>ms office return</body></html>");
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    //context.Response.End();
                    return;
                }

                //We need to store to be able to run workflow due to variables are referenced with name and not ids
                _originaleSavedQuerylanguage = sq.Sources[0].Language;

                // Check from saved query output type is on screen. If so createCopy shall be true, else false
                bool createCopy = CreateCopyOfCachedPaxiom(_format);

                // Create cache key
                string cacheKey = "";
                if (_language != null)
                {
                    cacheKey = string.Format("{0}_{1}", queryName, _language);
                }
                else
                {
                    cacheKey = string.Format("{0}_{1}", queryName, _originaleSavedQuerylanguage);
                }

                // Handle redirects to the selection page in a special way. The model object will only contain metadata and no data
                if (_format.Equals(PxUrl.PAGE_SELECT))
                {
                    cacheKey = string.Format("{0}_{1}", cacheKey, PxUrl.PAGE_SELECT);
                }

                // Try to get model from cache
                model = PXWeb.Management.SavedQueryPaxiomCache.Current.Fetch(cacheKey, createCopy);
                PaxiomManager.QueryModel = PXWeb.Management.SavedQueryPaxiomCache.Current.FetchQueryModel(cacheKey, createCopy);

                if (model == null || PaxiomManager.QueryModel == null)
                {
                    DateTime timeStamp = DateTime.Now;
                    // Model not found in cache - load it manually

                    model = LoadData(sq);

                    //Check if we need to change langauge to be able to run workflow due to variables are referenced with name and not ids
                    if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage)
                    {
                        model.Meta.SetLanguage(_originaleSavedQuerylanguage);
                    }

                    // No need to run workflow if we are redirecting to the selection page
                    if (!_format.Equals(PxUrl.PAGE_SELECT))
                    {
                        model = QueryHelper.RunWorkflow(sq, model);
                    }

                    //Set back to requested langauge after workflow operations
                    if (!string.IsNullOrEmpty(_language) && _language != _originaleSavedQuerylanguage)
                    {
                        if (model.Meta.HasLanguage(_language))
                        {
                            model.Meta.SetLanguage(_language);
                        }
                    }

                    // Store model in cache
                    PXWeb.Management.SavedQueryPaxiomCache.Current.Store(cacheKey, model, timeStamp);
                    PXWeb.Management.SavedQueryPaxiomCache.Current.StoreQueryModel(cacheKey, PaxiomManager.QueryModel, timeStamp);
                }

                if (!sq.Safe)
                {
                    safe = !CheckForUnsafeOperations(sq.Workflow);
                }
            }
            catch (Exception ex)
            {
                if ((PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.File && System.IO.File.Exists(queryName)) ||
                    (PCAxis.Query.SavedQueryManager.StorageType == PCAxis.Query.SavedQueryStorageType.Database))
                {
                    PCAxis.Query.SavedQueryManager.Current.MarkAsFailed(queryName);
                }

                throw new HttpException(404, "HTTP/1.1 404 Not Found");
                //throw ex;
            }

            sq.LoadedQueryName = queryName;
            PCAxis.Query.SavedQueryManager.Current.MarkAsRunned(queryName);

            // Tell the selection page that it sholud clear the PxModel
            if (_format.Equals(PxUrl.PAGE_SELECT))
            {
                HttpContext.Current.Session.Add("SelectionClearPxModel", true);
            }

            ViewSerializerCreator.GetSerializer(_format).Render(_format, sq, model, safe);
        }