示例#1
0
        /// <summary>
        /// Challenge the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param>
        /// <returns>A task.</returns>
        public virtual async Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultChallengeScheme = await Schemes.GetDefaultChallengeSchemeAsync();

                scheme = defaultChallengeScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultChallengeScheme found.");
                }
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme);

            if (handler == null)
            {
                throw await CreateMissingHandlerException(scheme);
            }

            await handler.ChallengeAsync(properties);
        }
示例#2
0
        /// <summary>
        /// Forbid the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param>
        /// <returns>A task.</returns>
        public virtual async Task ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultForbidScheme = await Schemes.GetDefaultForbidSchemeAsync();

                scheme = defaultForbidScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultForbidScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).");
                }
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme);

            if (handler == null)
            {
                throw await CreateMissingHandlerException(scheme);
            }

            await handler.ForbidAsync(properties);
        }
示例#3
0
        /// <summary>
        /// Sign out the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/>.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param>
        /// <returns>A task.</returns>
        public virtual async Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
        {
            if (scheme == null)
            {
                var defaultScheme = await Schemes.GetDefaultSignOutSchemeAsync();

                scheme = defaultScheme?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultSignOutScheme found.");
                }
            }

            var handler = await Handlers.GetHandlerAsync(context, scheme) as IAuthenticationSignOutHandler;

            if (handler == null)
            {
                throw new InvalidOperationException($"No IAuthenticationSignOutHandler is configured to handle sign out for the scheme: {scheme}");
            }

            await handler.SignOutAsync(properties);
        }
示例#4
0
        public void AddSchemes()
        {
            using (var toyapp = new ToyApplicationDbContext())
            {
                string schemeName, Description;
                Console.WriteLine("Enter schemeName");
                schemeName = Console.ReadLine();
                Console.WriteLine("Enter Description");
                Description = Console.ReadLine();

                var scheme = new Schemes
                {
                    SchemeName  = schemeName,
                    Description = Description
                };
                toyapp.Schemes.Add(scheme);

                toyapp.SaveChanges();

                Console.WriteLine(" Scheme Successfully Added");
            }
        }
示例#5
0
        public async Task <Schemes> UpdateAsync(Schemes model)
        {
            // model.IsUpdated = true;
            //   ObjectValidation(model);
            var dbobj = await GetByIdAsync(model.Id);

            if (dbobj == null)
            {
                throw new ProjectException("The Record does not exist in the system");
            }
            dbobj.Description = model.Description;
            dbobj.Fees        = model.Fees;
            dbobj.Name        = model.Name;
            if (model.Channel != null)
            {
                dbobj.Channel.Code        = model.Channel.Code;
                dbobj.Channel.Description = model.Channel.Description;
                dbobj.Channel.Name        = model.Channel.Name;
            }
            if (model.Route != null)
            {
                dbobj.Route.CardPAN     = model.Route.CardPAN;
                dbobj.Route.Description = model.Route.Description;
                dbobj.Route.Name        = model.Route.Name;
            }
            if (model.TransType != null)
            {
                dbobj.TransType.Code        = model.TransType.Code;
                dbobj.TransType.Description = model.TransType.Description;
                dbobj.TransType.Name        = model.TransType.Name;
            }

            _ModelRepository.Attach(dbobj, EntityStatus.Modified);
            await _UnitOfWork.SaveChangesAsync();

            return(dbobj);
        }
示例#6
0
        /// <summary>
        /// Sign a principal in for the specified authentication scheme.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Http.HttpContext" />.</param>
        /// <param name="scheme">The name of the authentication scheme.</param>
        /// <param name="principal">The <see cref="T:System.Security.Claims.ClaimsPrincipal" /> to sign in.</param>
        /// <param name="properties">The <see cref="T:Microsoft.AspNetCore.Authentication.AuthenticationProperties" />.</param>
        /// <returns>A task.</returns>
        public virtual async Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }
            if (scheme == null)
            {
                var signInSchemeAsync = await Schemes.GetDefaultSignInSchemeAsync();

                scheme = signInSchemeAsync?.Name;
                if (scheme == null)
                {
                    throw new InvalidOperationException("No authenticationScheme was specified, and there was no DefaultSignInScheme found.");
                }
            }
            if (!(await Handlers.GetHandlerAsync(context, scheme) is IAuthenticationSignInHandler handlerAsync))
            {
                throw new InvalidOperationException(string.Format("No IAuthenticationSignInHandler is configured to handle sign in for the scheme: {0}", scheme));
            }
            var user        = principal;
            var properties1 = properties;
            await handlerAsync.SignInAsync(user, properties1);
        }
示例#7
0
    protected override void OnPaint(PaintEventArgs e)
    {
        G = e.Graphics;

        base.OnPaint(e);

        G.Clear(Parent.BackColor);

        switch (Scheme)
        {

            case Schemes.Black:

                if (Enabled)
                {

                    if (State == Helpers.MouseState.None)
                    {
                        using (SolidBrush Background = new SolidBrush(Color.FromArgb(54, 54, 53)))
                        {
                            using (Pen Border = new Pen(Color.FromArgb(42, 42, 41)))
                            {
                                G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                                G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            }
                        }

                    }
                    else if (State == Helpers.MouseState.Over)
                    {
                        using (SolidBrush Background = new SolidBrush(Color.FromArgb(58, 58, 57)))
                        {
                            using (Pen Border = new Pen(Color.FromArgb(46, 46, 45)))
                            {
                                G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                                G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            }
                        }

                    }
                    else if (State == Helpers.MouseState.Down)
                    {
                        using (SolidBrush Background = new SolidBrush(Color.FromArgb(50, 50, 49)))
                        {
                            using (Pen Border = new Pen(Color.FromArgb(38, 38, 37)))
                            {
                                G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                                G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            }
                        }

                    }

                }
                else
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(40, 40, 39)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(38, 38, 37)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }

                break;
            case Schemes.Green:

                if (State == Helpers.MouseState.None)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(123, 164, 93)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(119, 160, 89)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Over)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(127, 168, 97)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(123, 164, 93)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Down)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(119, 160, 93)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(115, 156, 85)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }

                break;
            case Schemes.Red:

                if (State == Helpers.MouseState.None)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(164, 93, 93)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(160, 89, 89)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Over)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(168, 97, 97)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(164, 93, 93)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Down)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(160, 89, 89)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(156, 85, 85)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }

                break;
            case Schemes.Blue:

                if (State == Helpers.MouseState.None)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(93, 154, 164)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(89, 150, 160)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Over)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(97, 160, 168)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(93, 154, 164)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }
                else if (State == Helpers.MouseState.Down)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(89, 150, 160)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(85, 146, 156)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }

                }

                break;
        }

        if (Scheme == Schemes.Black)
        {
            if (Enabled)
            {
                using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(220, 220, 219)))
                {
                    using (Font TextFont = new Font("Segoe UI", 9))
                    {
                        using (StringFormat SF = new StringFormat { Alignment = StringAlignment.Center })
                        {
                            G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                        }
                    }
                }

            }
            else
            {
                using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(140, 140, 139)))
                {
                    using (Font TextFont = new Font("Segoe UI", 9))
                    {
                        using (StringFormat SF = new StringFormat { Alignment = StringAlignment.Center })
                        {
                            G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                        }
                    }
                }

            }

        }
        else
        {
            if (!Enabled)
            {
                Scheme = Schemes.Black;
            }

            using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(250, 250, 249)))
            {
                using (Font TextFont = new Font("Segoe UI", 9))
                {
                    using (StringFormat SF = new StringFormat { Alignment = StringAlignment.Center })
                    {
                        G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                    }
                }
            }

        }
    }
示例#8
0
        //public List<Security> security { get; set; }

        public void Serialize(JsonWriter writer)
        {
            writer.WritePropertyName(Id);

            writer.WriteStartObject();

            if (Tags != null && Tags.Any())
            {
                writer.WritePropertyName("tags");
                writer.WriteStartArray();
                foreach (string tag in Tags)
                {
                    writer.WriteValue(tag);
                }
                writer.WriteEndArray();
            }

            if (!string.IsNullOrWhiteSpace(Summary))
            {
                writer.WritePropertyName("summary");
                writer.WriteValue(Summary);
            }

            if (!string.IsNullOrWhiteSpace(Description))
            {
                writer.WritePropertyName("description");
                writer.WriteValue(Description);
            }

            if (ExternalDocs != null)
            {
                writer.WritePropertyName("externalDocs");
                ExternalDocs.Serialize(writer);
            }

            if (!string.IsNullOrWhiteSpace(OperationId))
            {
                writer.WritePropertyName("operationId");
                writer.WriteValue(OperationId);
            }

            if (Consumes != null && Consumes.Any())
            {
                writer.WritePropertyName("consumes");
                writer.WriteStartArray();
                foreach (string cons in Consumes)
                {
                    writer.WriteValue(cons);
                }
                writer.WriteEndArray();
            }

            if (Produces != null && Produces.Any())
            {
                writer.WritePropertyName("produces");
                writer.WriteStartArray();
                foreach (string prod in Produces)
                {
                    writer.WriteValue(prod);
                }
                writer.WriteEndArray();
            }

            if (Parameters != null && Parameters.Any())
            {
                writer.WritePropertyName("parameters");
                writer.WriteStartArray();
                foreach (ParameterBase p in Parameters)
                {
                    p.Serialize(writer);
                }
                writer.WriteEndArray();
            }

            if (Responses != null && Responses.Any())
            {
                writer.WritePropertyName("responses");
                writer.WriteStartObject();
                foreach (Response r in Responses)
                {
                    r.Serialize(writer);
                }
                writer.WriteEndObject();
            }

            if (Schemes != null && Schemes.Any())
            {
                writer.WritePropertyName("schemes");
                writer.WriteStartArray();
                foreach (string sch in Schemes)
                {
                    writer.WriteValue(sch);
                }
                writer.WriteEndArray();
            }
            if (Deprecated)
            {
                writer.WritePropertyName("deprecated");
                writer.WriteValue(Deprecated);
            }

            writer.WriteEndObject();
        }
示例#9
0
 public bool UpdateScheme(Schemes a)
 {
     return(admin.UpdateScheme(a));
 }
示例#10
0
        public void schemeBuilder()
        {
            int[][] scheme = new int[6][];
            scheme[0] = new int[]  { 1, 1, 1, 2, 2, 2, 2, 3, 3,
                                     1, 1, 4, 4, 4, 2, 2, 3, 3,
                                     1, 1, 4, 5, 5, 2, 3, 3, 3,
                                     1, 1, 4, 5, 2, 2, 6, 3, 3,
                                     4, 4, 4, 5, 5, 5, 6, 6, 6,
                                     7, 7, 4, 8, 8, 5, 6, 0, 0,
                                     7, 7, 7, 8, 5, 5, 6, 0, 0,
                                     7, 7, 8, 8, 6, 6, 6, 0, 0,
                                     7, 7, 8, 8, 8, 8, 0, 0, 0 };
            scheme[1] = new int[] { 1, 1, 2, 2, 2, 3, 3, 3, 4,
                                    1, 1, 2, 2, 2, 3, 3, 3, 4,
                                    1, 1, 2, 2, 2, 3, 3, 4, 4,
                                    5, 1, 1, 1, 6, 6, 3, 4, 4,
                                    5, 5, 6, 6, 6, 6, 6, 4, 4,
                                    5, 5, 7, 6, 6, 0, 0, 0, 4,
                                    5, 5, 7, 7, 8, 8, 8, 0, 0,
                                    5, 7, 7, 7, 8, 8, 8, 0, 0,
                                    5, 7, 7, 7, 8, 8, 8, 0, 0 };
            scheme[2] = new int[] { 1, 1, 1, 2, 2, 2, 3, 3, 3,
                                    1, 1, 1, 2, 2, 2, 4, 3, 3,
                                    1, 5, 5, 2, 6, 2, 4, 3, 3,
                                    1, 1, 5, 2, 6, 6, 4, 3, 3,
                                    5, 5, 5, 6, 6, 6, 4, 4, 4,
                                    7, 7, 5, 6, 6, 8, 4, 0, 0,
                                    7, 7, 5, 8, 6, 8, 4, 4, 0,
                                    7, 7, 5, 8, 8, 8, 0, 0, 0,
                                    7, 7, 7, 8, 8, 8, 0, 0, 0 };
            scheme[3] = new int[] { 1, 1, 1, 2, 2, 2, 2, 3, 3,
                                    1, 1, 4, 2, 2, 2, 2, 3, 3,
                                    5, 1, 4, 2, 4, 4, 4, 4, 3,
                                    5, 1, 4, 4, 4, 6, 6, 6, 3,
                                    5, 1, 1, 6, 6, 6, 8, 8, 3,
                                    5, 6, 6, 6, 7, 7, 7, 8, 3,
                                    5, 7, 7, 7, 7, 0, 7, 8, 3,
                                    5, 5, 0, 0, 0, 0, 7, 8, 8,
                                    5, 5, 0, 0, 0, 0, 8, 8, 8 };
            scheme[4] = new int[] { 1, 1, 2, 2, 2, 2, 2, 2, 2,
                                    1, 1, 1, 1, 3, 2, 2, 3, 4,
                                    1, 5, 5, 1, 3, 3, 3, 3, 4,
                                    1, 5, 6, 6, 3, 3, 3, 4, 4,
                                    5, 5, 6, 6, 6, 6, 6, 4, 4,
                                    5, 5, 7, 7, 7, 6, 6, 4, 8,
                                    5, 7, 7, 7, 7, 8, 4, 4, 8,
                                    5, 7, 0, 0, 7, 8, 8, 8, 8,
                                    0, 0, 0, 0, 0, 0, 0, 8, 8 };


            for (int s = 0; s < 5; s++)
            {
                int[,] Puzzle = new int[9, 9];

                for (int i = 0; i < 9; i++)
                {
                    for (int j = 0; j < 9; j++)
                    {
                        Puzzle[i, j] = scheme[s][i * 9 + j];
                    }
                }
                Schemes.Add(Puzzle);
            }
        }
        internal static void Load()
        {
            try
            {
                XmlDocument Doc = new XmlDocument();

                using (MemoryStream ms = new MemoryStream(Waher.Content.Resources.LoadResource(
                                                              typeof(PersonalNumberSchemes).Namespace + ".PersonalNumberSchemes.xml")))
                {
                    Doc.Load(ms);
                }

                foreach (XmlNode N in Doc.DocumentElement.ChildNodes)
                {
                    if (N is XmlElement E && E.LocalName == "Entry")
                    {
                        string     Country       = XML.Attribute(E, "country");
                        string     DisplayString = XML.Attribute(E, "displayString");
                        string     Variable      = null;
                        Expression Pattern       = null;
                        Expression Check         = null;
                        Expression Normalize     = null;

                        try
                        {
                            foreach (XmlNode N2 in E.ChildNodes)
                            {
                                if (N2 is XmlElement E2)
                                {
                                    switch (E2.LocalName)
                                    {
                                    case "Pattern":
                                        Pattern  = new Expression(E2.InnerText);
                                        Variable = XML.Attribute(E2, "variable");
                                        break;

                                    case "Check":
                                        Check = new Expression(E2.InnerText);
                                        break;

                                    case "Normalize":
                                        Normalize = new Expression(E2.InnerText);
                                        break;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                            continue;
                        }

                        if (Pattern is null || string.IsNullOrEmpty(Variable) || string.IsNullOrEmpty(DisplayString))
                        {
                            continue;
                        }

                        if (!schemesByCode.TryGetValue(Country, out LinkedList <PersonalNumberScheme> Schemes))
                        {
                            Schemes = new LinkedList <PersonalNumberScheme>();
                            schemesByCode[Country] = Schemes;
                        }

                        Schemes.AddLast(new PersonalNumberScheme(Variable, DisplayString, Pattern, Check, Normalize));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }
        }
示例#12
0
        /// <summary>
        /// 重载异步处理程序
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和接口列表更新,
            // 注意这里我用到了AOP缓存,只是减少与数据库的访问次数,而又保证是最新的数据

            var data = await _roleModulePermissionServices.GetRoleModule();

            var list = (from item in data
                        orderby item.Id
                        select new Permission
            {
                Id = item.Id,
                ApiUrl = item.ApiUrl,
                RequestMethod = item.RequestMethod,
                ActionName = item.ActionName
            }).ToList();

            requirement.Permissions = list;


            //从AuthorizationHandlerContext转成HttpContext,以便取出表头信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;



            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToLower();
            //判断请求是否停止
            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }
            //判断请求是否拥有凭据,即有没有登录
            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                //result?.Principal不为空即登录成功
                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    //权限中是否存在请求的url

                    // 获取当前用户的角色信息
                    var currentUserRoles = (from item in httpContext.User.Claims
                                            where item.Type == requirement.ClaimType
                                            select item.Value).FirstOrDefault();


                    //这里就是对权限的验证
                    //请求方式    httpContext.Request.Method
                    //请求连接    questUrl
                    //我们的权限  Permissions
                    if (requirement.Permissions.Where(g => g.Id == currentUserRoles && g.ApiUrl?.ToLower() == questUrl && g.RequestMethod == httpContext.Request.Method).Count() <= 0)
                    {
                        context.Fail();
                        return;
                    }

                    //判断过期时间
                    if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                    return;
                }
            }
            //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
            if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") ||
                                                                                                !httpContext.Request.HasFormContentType))
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);
        }
示例#13
0
 /// <summary>
 /// Creates a new key file with authentication information.
 /// </summary>
 /// <param name="sheme"></param>
 /// <param name="host"></param>
 /// <param name="path"></param>
 /// <param name="user"></param>
 /// <param name="pass"></param>
 /// <returns></returns>
 public static KeyFile BuildUri(Schemes sheme, string host, string path, string user, string pass)
 {
     return new KeyFile(string.Format("{0}://{1}:{2}@{3}/{4}",
         sheme, user, pass, host, path));
 }
示例#14
0
 /// <summary>
 /// Creates a new key file.
 /// </summary>
 /// <param name="sheme">The sheme of the source.</param>
 /// <param name="host">The hostname.</param>
 /// <param name="path">The path.</param>
 /// <returns></returns>
 public static KeyFile BuildUri(Schemes sheme, string host, string path)
 {
     return new KeyFile(string.Format("{0}://{1}/{2}",
         sheme, host, path));
 }
示例#15
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和接口列表更新
            var data = await RoleModulePermissionService.GetRoleModule().ConfigureAwait(false);

            var list = (from item in data
                        where item.IsDelete == false
                        orderby item.Id
                        select new PermissionItem
            {
                Url = item.Module?.LinkUrl,
                Role = item.Role?.RoleName,
            }).ToList();

            requirement.Permissions = list;

            // 从AuthorizationHandlerContext转成HttpContext,以便取出表头信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            // https://q.cnblogs.com/q/120091/
            if (httpContext == null)
            {
                httpContext = _accessor.HttpContext;
            }

            // 请求Url
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                // 判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync().ConfigureAwait(false))
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name).ConfigureAwait(false) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                // 判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync().ConfigureAwait(false);

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name).ConfigureAwait(false);

                    // result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        // 权限中是否存在请求的url
                        // if (requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key?.ToLower() == questUrl).Count() > 0)
                        // if (isMatchUrl)
                        if (true)
                        {
                            // 获取当前用户的角色信息
                            var currentUserRoles = (from item in httpContext.User.Claims
                                                    where item.Type == requirement.ClaimType
                                                    select item.Value).ToList();

                            var isMatchRole     = false;
                            var permissionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                            foreach (var item in permissionRoles)
                            {
                                try
                                {
                                    if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
                                    {
                                        isMatchRole = true;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }

                            // 验证权限
                            // if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                            if (currentUserRoles.Count <= 0 || !isMatchRole)
                            {
                                context.Fail();
                                return;
                            }
                        }

                        // 判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                            return;
                        }
                        return;
                    }
                }
                // 判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
                {
                    context.Fail();
                    return;
                }
            }

            context.Succeed(requirement);
        }
示例#16
0
        /// <summary>
        /// 判断是否授权
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MvcAuthorizeHandlerReq requirement)
        {
            #region 说明

            /*
             * .netcore3.0 启用EndpointRouting后,权限filter不再添加到ActionDescriptor ,而将权限直接作为中间件运行,
             * 同时所有filter都会添加到endpoint.Metadata。因此,文中的
             * context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext不再成立。
             *
             * 解决方案有两个:
             *
             * 首先必须在 controller 上进行配置 Authorize ,可以策略授权,也可以角色等基本授权
             *
             * 1、开启公约, startup 中的全局授权过滤公约:o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
             *
             * 2、不开启公约,使用 IHttpContextAccessor ,也能实现效果,但是不能自定义返回格式,详细看下边配置;
             */

            #endregion

            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息(netcore2.2之前有效,3.0需要开启全局过滤公约才有这个上下文)
            var filterContext = (context.Resource as AuthorizationFilterContext);
            var httpContext   = (context.Resource as AuthorizationFilterContext)?.HttpContext;
            if (httpContext == null)
            {
                httpContext = HttpContextAccessor.HttpContext;
            }

            //请求Url
            if (httpContext != null)
            {
                var user = httpContext.User;

                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        AuthDeal(context, requirement, httpContext, false);
                        return;
                    }
                }

                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        //判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            // todo:根据用户判断是否 有对应角色和路由的权限
                            //var questUrl = httpContext.Request.Path.Value.ToLower();
                            if (requirement.Roles != null && requirement.Roles.Length > 0)
                            {
                                var strReqRoles    = string.Join(",", requirement.Roles.Select(x => ((int)x).ToString()));
                                var isUserHadRoles = httpContext.User.IsInRole(strReqRoles);
                                if (!isUserHadRoles)
                                {
                                    AuthDeal(context, requirement, httpContext, false);
                                    return;
                                }
                            }

                            if (true)
                            {
                                AuthDeal(context, requirement, httpContext, true);
                                return;
                            }
                        }
                    }
                }
            }

            AuthDeal(context, requirement, httpContext, false);
            return;
        }
        public SchemeViewModel()
        {
            #region 初始化方案

            using (var db = new HomeAutomationEntities())
            {
                Schemes = db.t_Scheme.ToList();
            }
            if (Schemes.Count > 0)
            {
                Scheme     = Schemes[0];
                SchemeName = Schemes[0].SchemeName;
            }

            #endregion

            #region 初始化详细方案//test

            RefreshDetailScheme();

            #endregion

            #region 初始化电器

            using (var db = new HomeAutomationEntities())
            {
                HomeAppliances = db.t_HomeAppliances.ToList();
            }

            #endregion

            #region 新建方案

            CreateSchemeCommand = new RelayCommand(() =>
            {
                if (SchemeState)
                {
                    UMessageBox.Show($"请先停止方案!", false);
                    return;
                }
                if (SchemeNameEidtState)
                {
                    return;
                }
                using (var db = new HomeAutomationEntities())
                {
                    var count = db.t_Scheme.ToList().Count;
                    db.t_Scheme.Add(new t_Scheme()
                    {
                        SchemeName = $"方案{++count}"
                    });
                    db.SaveChanges();
                    Schemes       = db.t_Scheme.ToList();
                    Scheme        = Schemes.Find(x => x.SchemeName == $"方案{count}");
                    DetailSchemes = new ObservableCollection <DetailSchemeModel>();
                }
            });

            #endregion

            #region  除方案

            DeleteSchemeCommand = new RelayCommand(() =>
            {
                if (SchemeState)
                {
                    UMessageBox.Show($"请先停止方案!", false);
                    return;
                }
                if (SchemeNameEidtState)
                {
                    return;
                }
                var result = UMessageBox.Show("确定删除当前方案吗?");
                if (result == false)
                {
                    return;
                }
                using (var db = new HomeAutomationEntities())
                {
                    if (Scheme == null)
                    {
                        return;
                    }
                    var scheme = db.t_Scheme.FirstOrDefault(x => x.Id == Scheme.Id);
                    if (scheme != null)
                    {
                        db.t_Scheme.Remove(scheme);
                    }
                    var detailScheme = db.t_DetailScheme.Where(x => x.SchemeId == Scheme.Id);
                    db.t_DetailScheme.RemoveRange(detailScheme);
                    db.SaveChanges();
                    Schemes = db.t_Scheme.ToList();
                    if (Schemes.Count <= 0)
                    {
                        return;
                    }
                    Scheme     = Schemes[0];
                    SchemeName = Schemes[0].SchemeName;
                }
            });


            #endregion

            #region 刷新方案列表命令

            HomeApplianceScheme = new RelayCommand(() =>
            {
                if (SchemeNameEidtState)
                {
                    return;
                }
                RefreshDetailScheme();
            });

            #endregion

            #region 方案定时开关 (开关定时任务)

            StartSchemeCommand = new RelayCommand((() =>
            {
                if (!UMessageBox.Result)
                {
                    return;
                }
                //是否选择方案,执行方案是否为空
                if (Scheme == null)
                {
                    UMessageBox.Show($"当前没有选中方案!", false);
                    return;
                }
                //是否正在编辑方案
                if (SchemeNameEidtState)
                {
                    return;
                }
                //定时方案停止
                if (SchemeState)
                {
                    //
                    //等待提示框

                    //强制关闭所有电器
                    //var driver =new Rs485Driver();
                    //try
                    //{
                    //    driver.Connect(new NetArg("192.168.0.233", 10001));
                    //}
                    //catch (Exception e)
                    //{
                    //    MessageBox.Show($"连接不上设备", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    //    return;
                    //}
                    //var state=  driver.Read32RelayOutputState();
                    //foreach (var value in state)
                    //{
                    //    if (value.Value==true)
                    //    {
                    //        ControllerHomeAutomation(value.Key, false);
                    //    }
                    //}

                    foreach (var value in DetailSchemes)
                    {
                        value.RunSchemeState = false;
                        value.SchemevisibiState = "Hidden";
                        value.Cancel.Cancel();
                    }
                    SchemeState = false;
                    SchemeList = true;
                }
                //定时方案启动
                else
                {
                    SchemeState = true;
                    SchemeList = false;
                    foreach (var value in DetailSchemes)
                    {
                        value.Cancel = new CancellationTokenSource();
                        value.Task = new Task(() =>
                        {
                            //等待开始
                            var waitTime = 0;
                            while (waitTime < value.DtailScheme.WaitTime)
                            {
                                try
                                {
                                    value.Cancel.Token.ThrowIfCancellationRequested();
                                }
                                catch (Exception e)
                                {
                                    value.RunSchemeState = false;
                                    value.SchemevisibiState = "Hidden";
                                    return;
                                }
                                waitTime++;
                                Thread.Sleep(1000);
                            }

                            value.RunSchemeState = true;
                            value.SchemevisibiState = "Visible";
                            //启动电器
                            //try
                            //{
                            //
                            //    AsyncControllerHomeAutomation(value.DtailScheme.HomeAppliancesId, true);
                            //}
                            //catch (Exception e)
                            //{
                            //    MessageBox.Show($"连接不上设备", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            //    value.RunSchemeState = false;
                            //    value.SchemevisibiState = "Hidden";
                            //    return;
                            //}
                            //执行时长
                            var runTime = 0;

                            //等待结束
                            while (runTime < value.DtailScheme.RunTime)
                            {
                                var timeSpan = new TimeSpan(0, 0, value.DtailScheme.RunTime - runTime - 1);
                                value.SchemeTime = timeSpan.Hours.ToString() + " h " + timeSpan.Minutes + " m " +
                                                   timeSpan.Seconds + " s";
                                try
                                {
                                    value.Cancel.Token.ThrowIfCancellationRequested();
                                }
                                catch (Exception e)
                                {
                                    value.RunSchemeState = false;
                                    value.SchemevisibiState = "Hidden";
                                    return;
                                }
                                runTime++;
                                Thread.Sleep(1000);
                            }
                            //关闭电器
                            //try
                            //{

                            //    AsyncControllerHomeAutomation(value.DtailScheme.HomeAppliancesId, false);
                            //}
                            //catch (Exception e)
                            //{
                            //    MessageBox.Show($"连接不上设备", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            //}
                            value.RunSchemeState = false;
                        }, value.Cancel.Token);
                        value.Task.Start();
                    }
                }
            }));

            #endregion

            #region 添加 定时命令

            AddSchemeCommand = new RelayCommand(() =>
            {
                if (DetailSchemes.FirstOrDefault(x => x.DtailScheme.HomeAppliancesName == "选择电器") != null)
                {
                    //提示选择电器
                    UMessageBox.Show($"请选择电器!", false);
                    return;
                }
                using (var db = new HomeAutomationEntities())
                {
                    //遍历详细方案
                    for (var i = 0; i < DetailSchemes.Count; i++)
                    {
                        if (DetailSchemes[i].DtailScheme.WaitTime < 0 || DetailSchemes[i].DtailScheme.RunTime <= 0)
                        {
                            UMessageBox.Show($"{DetailSchemes[i].DtailScheme.HomeAppliancesName} 时间运行太短!", false);
                            return;
                        }
                        //id= 100表示没有选中
                        if (DetailSchemes[i] == null || DetailSchemes[i].DtailScheme.HomeAppliancesId == 100)
                        {
                            continue;
                        }
                        //判断时间重复
                        for (var j = 0; j < i; j++)
                        {
                            //根据电器名称相同,断定同一电器
                            if (DetailSchemes[i].DtailScheme.HomeAppliancesName !=
                                DetailSchemes[j].DtailScheme.HomeAppliancesName)
                            {
                            }
                            //判断同一电器启动,一分钟间隔以上
                            else if (DetailSchemes[i].DtailScheme.WaitTime >
                                     (DetailSchemes[j].DtailScheme.RunTime +
                                      DetailSchemes[j].DtailScheme.WaitTime) + 60 ||
                                     DetailSchemes[i].DtailScheme.RunTime + DetailSchemes[i].DtailScheme.WaitTime + 60 <
                                     DetailSchemes[j].DtailScheme.WaitTime)
                            {
                            }
                            else
                            {
                                UMessageBox.Show($"{DetailSchemes[i].DtailScheme.HomeAppliancesName} 运行时间冲突或者间隔太近!", false);
                                return;
                            }
                        }
                        var detail        = DetailSchemes[i];
                        var homeAppliance =
                            db.t_HomeAppliances.FirstOrDefault(
                                x => x.Name == detail.DtailScheme.HomeAppliancesName);
                        if (homeAppliance != null)
                        {
                            db.t_DetailScheme.AddOrUpdate(new t_DetailScheme()
                            {
                                Id = DetailSchemes[i].DtailScheme.DetailSchemeId,
                                HomeAppliancesId = homeAppliance.Id,
                                RunTime          = DetailSchemes[i].DtailScheme.RunTime,
                                WaitTime         = DetailSchemes[i].DtailScheme.WaitTime,
                                SchemeId         = DetailSchemes[i].DtailScheme.SchemeId
                            });
                        }
                    }
                    db.SaveChanges();
                    Schemes = db.t_Scheme.ToList();
                    Scheme  = Schemes.FirstOrDefault(x => x.Id == SchemmeId);
                }
                RefreshDetailScheme();
                DetailSchemes.Add(new DetailSchemeModel()
                {
                    DtailScheme = new v_DtailScheme()
                    {
                        RunTime            = 0,
                        WaitTime           = 0,
                        SchemeId           = Scheme.Id,
                        HomeAppliancesName = "选择电器"
                    }
                });
            });

            #endregion

            #region 更新选中定时

            UpdataSchemeCommand = new RelayCommand <long>((detailSchemeId) =>
            {
                var detailscheme = DetailSchemes.FirstOrDefault(x => x.DtailScheme.DetailSchemeId == detailSchemeId);
                //id 100表示没有选中
                if (detailscheme == null || detailSchemeId == 100)
                {
                    return;
                }
                //判断时间重复

                using (var db = new HomeAutomationEntities())
                {
                    var homeAppliance =
                        db.t_HomeAppliances.FirstOrDefault(x => x.Name == detailscheme.DtailScheme.HomeAppliancesName);
                    var detailScheme =
                        db.t_DetailScheme.FirstOrDefault(x => x.Id == detailscheme.DtailScheme.DetailSchemeId);
                    if (detailScheme == null || homeAppliance == null)
                    {
                        return;
                    }
                    detailScheme.HomeAppliancesId = homeAppliance.Id;
                    detailScheme.RunTime          = detailscheme.DtailScheme.RunTime;
                    detailScheme.WaitTime         = detailscheme.DtailScheme.WaitTime;

                    db.SaveChanges();
                }
                RefreshDetailScheme();
            });

            #endregion

            #region  除选中定时命令

            DeleletChooseDetailScheme = new RelayCommand <long>(((detailSchemeId) =>
            {
                using (var db = new HomeAutomationEntities())
                {
                    //删除定时
                    var descheme = db.t_DetailScheme.FirstOrDefault(x => x.Id == detailSchemeId);
                    if (descheme != null)
                    {
                        db.t_DetailScheme.Remove(descheme);
                    }
                    db.SaveChanges();
                }
                DetailSchemes.Remove(DetailSchemes.FirstOrDefault(x => x.DtailScheme.DetailSchemeId == detailSchemeId));
            }));

            #endregion

            #region 编辑选中方案

            UpdataChooseDatailScheme = new RelayCommand((() =>
            {
                if (SchemeState)
                {
                    UMessageBox.Show($"请先停止方案!", false);
                    return;
                }
                if (SchemeName == null)
                {
                    return;
                }

                if (SchemeEidtState)
                {
                    SchemmeId = Scheme.Id;
                    SchemeEidtState = false;
                    ButtonNameSave = "完成";
                    SchemeAddState = "Visible";
                    SchemeNameEidtState = true;
                }
                else
                {
                    for (var i = DetailSchemes.Count() - 1; i >= 0; i--)
                    {
                        if (DetailSchemes[i].DtailScheme.HomeAppliancesName == "选择电器")
                        {
                            DetailSchemes.Remove(DetailSchemes[i]);
                        }
                    }
                    using (var db = new HomeAutomationEntities())
                    {
                        //更新方案名称
                        var scheme = db.t_Scheme.FirstOrDefault(x => x.Id == SchemmeId);
                        if (scheme != null)
                        {
                            scheme.SchemeName = SchemeName;
                        }



                        //遍历详细方案
                        for (var i = 0; i < DetailSchemes.Count; i++)
                        {
                            if (DetailSchemes[i].DtailScheme.WaitTime <= 0 || DetailSchemes[i].DtailScheme.RunTime <= 0)
                            {
                                UMessageBox.Show($"{DetailSchemes[i].DtailScheme.HomeAppliancesName} 时间运行太短!", false);
                                return;
                            }
                            //id= 100表示没有选中
                            if (DetailSchemes[i] == null || DetailSchemes[i].DtailScheme.HomeAppliancesId == 100)
                            {
                                continue;
                            }
                            //判断时间重复
                            for (var j = 0; j < i; j++)
                            {
                                //根据电器名称相同,断定同一电器
                                if (DetailSchemes[i].DtailScheme.HomeAppliancesName !=
                                    DetailSchemes[j].DtailScheme.HomeAppliancesName)
                                {
                                }
                                //判断同一电器启动,一分钟间隔以上
                                else if (DetailSchemes[i].DtailScheme.WaitTime >
                                         (DetailSchemes[j].DtailScheme.RunTime +
                                          DetailSchemes[j].DtailScheme.WaitTime) + 60 ||
                                         DetailSchemes[i].DtailScheme.RunTime + DetailSchemes[i].DtailScheme.WaitTime +
                                         60 <
                                         DetailSchemes[j].DtailScheme.WaitTime)
                                {
                                }
                                else
                                {
                                    UMessageBox.Show($"{DetailSchemes[i].DtailScheme.HomeAppliancesName} 时间冲突!", false);
                                    return;
                                }
                            }
                            var detail = DetailSchemes[i];
                            var homeAppliance =
                                db.t_HomeAppliances.FirstOrDefault(
                                    x => x.Name == detail.DtailScheme.HomeAppliancesName);
                            if (homeAppliance != null)
                            {
                                db.t_DetailScheme.AddOrUpdate(new t_DetailScheme()
                                {
                                    Id = DetailSchemes[i].DtailScheme.DetailSchemeId,
                                    HomeAppliancesId = homeAppliance.Id,
                                    RunTime = DetailSchemes[i].DtailScheme.RunTime,
                                    WaitTime = DetailSchemes[i].DtailScheme.WaitTime,
                                    SchemeId = DetailSchemes[i].DtailScheme.SchemeId
                                });
                            }
                        }
                        db.SaveChanges();
                        Schemes = db.t_Scheme.ToList();
                        Scheme = Schemes.FirstOrDefault(x => x.Id == SchemmeId);
                    }

                    RefreshDetailScheme();
                    SchemeEidtState = true;
                    ButtonNameSave = "方案编辑";
                    SchemeAddState = "Hidden";
                    SchemeNameEidtState = false;
                }
            }));

            #endregion

            #region 编辑运行时间

            InstallRunTimeCommand = new RelayCommand <long>(detailSchemeId =>
            {
                if (SchemeEidtState)
                {
                    return;
                }
                var detailScheme =
                    DetailSchemes.FirstOrDefault(x => x.DtailScheme.DetailSchemeId == detailSchemeId);
                if (detailScheme == null)
                {
                    return;
                }
                var result      = UTimePiker.ChooseEquals(detailScheme.DtailScheme.RunTime);
                var dtailScheme = new v_DtailScheme()
                {
                    DetailSchemeId     = detailSchemeId,
                    HomeAppliancesId   = detailScheme.DtailScheme.HomeAppliancesId,
                    HomeAppliancesName = detailScheme.DtailScheme.HomeAppliancesName,
                    RunTime            = result,
                    SchemeId           = detailScheme.DtailScheme.SchemeId,
                    SchemeName         = detailScheme.DtailScheme.SchemeName,
                    WaitTime           = detailScheme.DtailScheme.WaitTime
                };
                detailScheme.DtailScheme = dtailScheme;
            });

            #endregion
            #region 编辑等待时间

            InstallWaitTimeCommand = new RelayCommand <long>(detailSchemeId =>
            {
                if (SchemeEidtState)
                {
                    return;
                }
                var detailScheme =
                    DetailSchemes.FirstOrDefault(x => x.DtailScheme.DetailSchemeId == detailSchemeId);
                if (detailScheme == null)
                {
                    return;
                }
                var result      = UTimePiker.ChooseEquals(detailScheme.DtailScheme.WaitTime);
                var dtailScheme = new v_DtailScheme()
                {
                    DetailSchemeId     = detailSchemeId,
                    HomeAppliancesId   = detailScheme.DtailScheme.HomeAppliancesId,
                    HomeAppliancesName = detailScheme.DtailScheme.HomeAppliancesName,
                    RunTime            = detailScheme.DtailScheme.RunTime,
                    SchemeId           = detailScheme.DtailScheme.SchemeId,
                    SchemeName         = detailScheme.DtailScheme.SchemeName,
                    WaitTime           = result
                };
                detailScheme.DtailScheme = dtailScheme;
            });

            #endregion
        }
示例#18
0
        // 重载异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和权限列表更新
            var data = await roleModulePermissionServices.GetPermission();

            var list = (from item in data
                        where item.S04_IsValid == 0
                        select new PermissionItem
            {
                Url = item.S03_BackRoute,
                RoleId = item.S02_RoleId,
            }).ToList();

            requirement.Permissions = list;

            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            //请求Url
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        if (true)
                        {
                            // 获取当前用户的角色信息
                            var currentUserRoles = (from item in httpContext.User.Claims
                                                    where item.Type == requirement.ClaimType
                                                    select item.Value).ToList();

                            var isMatchRole      = false;
                            var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.RoleId.ToString()));
                            foreach (var item in permisssionRoles)
                            {
                                try
                                {
                                    if (Regex.Match(questUrl, item.Url?.ToString().ToLower())?.Value == questUrl)
                                    {
                                        isMatchRole = true;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }

                            //验证权限
                            //if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                            if (currentUserRoles.Count <= 0 || !isMatchRole)
                            {
                                context.Fail();
                                // 可以在这里设置跳转页面,不过还是会访问当前接口地址的
                                httpContext.Response.Redirect(requirement.DeniedAction);
                            }
                        }
                        //else
                        //{
                        //    context.Fail();
                        //    return;

                        //}
                        //判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
                {
                    context.Fail();
                    return;
                }
            }

            context.Succeed(requirement);
        }
示例#19
0
        // 重载异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和接口列表更新
            var data = await _roleModulePermissionServices.GeRoleModule();

            var list = (from item in data
                        where item.IsDeleted == false
                        orderby item.Id
                        select new Permission
            {
                Url = item.Module?.LinkUrl,
                Role = item.Role?.Name,
            }).ToList();

            requirement.Permissions = list;


            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToLower();
            //判断请求是否停止
            var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
            {
                var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler != null && await handler.HandleRequestAsync())
                {
                    context.Fail();
                    return;
                }
            }
            //判断请求是否拥有凭据,即有没有登录
            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                //result?.Principal不为空即登录成功
                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    //权限中是否存在请求的url
                    if (requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key?.ToLower() == questUrl).Count() > 0)
                    {
                        // 获取当前用户的角色信息
                        var currentUserRoles = (from item in httpContext.User.Claims
                                                where item.Type == requirement.ClaimType
                                                select item.Value).ToList();


                        //验证权限
                        if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                        {
                            context.Fail();
                            return;

                            // 可以在这里设置跳转页面,不过还是会访问当前接口地址的
                            httpContext.Response.Redirect(requirement.DeniedAction);
                        }
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                    //判断过期时间
                    if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        context.Fail();
                        return;
                    }
                    return;
                }
            }
            //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
            if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") ||
                                                                                                !httpContext.Request.HasFormContentType))
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);
        }
示例#20
0
        protected override async void OnInitialize()
        {
            var schemes = await schemeStorage.GetSchemesAsync();

            Schemes.AddRange(schemes.Select(s => new SchemeViewModel(s)));
        }
示例#21
0
 public bool CanHandleUrl(string url)
 {
     return(Schemes.Any(p => Regex.IsMatch(url, p)));
 }
        // 重写异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            /*
             *
             * 首先必须在 controller 上进行配置 Authorize ,可以策略授权,也可以角色等基本授权
             *
             * 1、开启公约, startup 中的全局授权过滤公约:o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
             *
             * 2、不开启公约,使用 IHttpContextAccessor ,也能实现效果;
             */

            // 将最新的角色和接口列表更新
            var data = await _roleModuleService.GetRoleModule();

            var list = (from item in data

                        orderby item.Id
                        select new PermissionItem
            {
                Url = item.ModuleApi?.LinkUrl,
                Role = item.Role?.Name,
            }).ToList();

            requirement.Permissions = list;


            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            //var filterContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext);
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            if (httpContext == null)
            {
                httpContext = _accessor.HttpContext;
            }

            //请求Url
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        context.Fail();
                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        //权限中是否存在请求的url
                        //验证权限临时判断  需要加上按钮管理才能控制

                        if (true)
                        {
                            // 获取当前用户的角色信息
                            var currentUserRoles = (from item in httpContext.User.Claims
                                                    where item.Type == requirement.ClaimType
                                                    select item.Value).ToList();

                            var isMatchRole      = false;
                            var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                            foreach (var item in permisssionRoles)
                            {
                                try
                                {
                                    if (Regex.Match(questUrl, item.Url?.ToLower())?.Value == questUrl)
                                    {
                                        isMatchRole = true;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }
                            //验证权限
                            if (currentUserRoles.Count <= 0 || !isMatchRole)
                            {
                                context.Succeed(requirement); //测试验证权限临时通过 需要加上按钮管理才能控制
                                //context.Fail();
                                //return;
                            }
                        }

                        //判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
                {
                    context.Fail();
                    return;
                }
            }

            context.Succeed(requirement);
        }
示例#23
0
 /// <summary>
 /// Default-Constructor
 /// </summary>
 /// <param name="scheme"></param>
 public ColorScheme(Schemes scheme = Schemes.Normal, bool rightToLeft = true)
 {
     Scheme      = scheme;
     RightToLeft = rightToLeft;
 }
示例#24
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            ////赋值用户权限
            Requirement = requirement;
            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            AuthorizationFilterContext authorizationFilterContext = context.Resource as AuthorizationFilterContext;

            if (authorizationFilterContext != null)
            {
                var httpContext = authorizationFilterContext.HttpContext;
                //请求Url
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;

                    if (handler != null && await handler.HandleRequestAsync())
                    {
                        httpContext.Response.Redirect(requirement.DeniedAction);
                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;
                        var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Name).Value;
                        if (!Permissions.Any(g => g.UserName == name && g.Role?.Urls != null && g.Role.Urls.Any(w => w.Url.ToLower() == questUrl)))
                        {
                            //无权限跳转到拒绝页面
                            context.Fail();
                            return;
                        }

                        //判断过期时间
                        if (DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration).Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            context.Fail();
                        }
                        return;
                    }
                }

                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) &&
                    (!httpContext.Request.Method.Equals("POST") ||
                     !httpContext.Request.HasFormContentType))
                {
                    context.Fail();
                    return;
                }
            }
            context.Succeed(requirement);
        }
示例#25
0
 private async Task <string> GetAllSignOutSchemeNames()
 {
     return(string.Join(", ", (await Schemes.GetAllSchemesAsync())
                        .Where(sch => typeof(IAuthenticationSignOutHandler).IsAssignableFrom(sch.HandlerType))
                        .Select(sch => sch.Name)));
 }
示例#26
0
        public Bitmap drawSchemePreview(int w, int h, Schemes scheme)
        {
            Bitmap b = new Bitmap(w, h);

            int padding = 2;
            int margin  = 4;

            Size sqr_1 = new Size((w - ((margin * 2))), (((h - ((2 * margin) + (2 * padding))) / 4) * 2));
            Size sqr_2 = new Size((w - ((margin * 2) + padding)) / 2, (((h - ((2 * margin) + (2 * padding))) / 4)));
            Size sqr_3 = new Size((w - ((2 * padding) + (2 * margin))) / 3, (((h - ((2 * margin) + (2 * padding))) / 4)));
            Size sqr_4 = new Size((w - ((3 * padding) + (2 * margin))) / 4, (((h - ((2 * margin) + (2 * padding))) / 4)));
            int  hp3   = (((h - ((2 * margin) + (2 * padding))) / 3));

            using (Graphics g = Graphics.FromImage(b))
            {
                switch (scheme)
                {
                case Schemes.s133:

                    g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin, margin), sqr_1));

                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + padding + sqr_1.Height), sqr_3));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding * 2) + sqr_3.Height + sqr_1.Height), sqr_3));
                    }

                    break;

                case Schemes.s134:
                    g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin, margin), sqr_1));
                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + padding + sqr_1.Height), sqr_3));
                    }

                    for (int i = 0; i < 4; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + 1 + (i * (sqr_4.Width + padding)), margin + (padding * 2) + sqr_3.Height + sqr_1.Height), sqr_4));
                    }
                    break;

                case Schemes.s212:

                    for (int i = 0; i < 2; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_2.Width + padding)), margin), sqr_2));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_2.Width + padding)), margin + (padding * 2) + sqr_1.Height + sqr_2.Height), sqr_2));
                    }

                    g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin, margin + padding + sqr_2.Height), sqr_1));

                    break;

                case Schemes.s232:
                    for (int i = 0; i < 2; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_2.Width + padding)), margin), new Size(sqr_2.Width, hp3)));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_2.Width + padding)), margin + (padding * 2) + hp3 + hp3), new Size(sqr_2.Width, hp3)));
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + padding + hp3), new Size(sqr_3.Width, hp3)));
                    }

                    break;

                case Schemes.s313:
                    g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin, margin + padding + sqr_3.Height), sqr_1));

                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin), sqr_3));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding * 2) + sqr_3.Height + sqr_1.Height), sqr_3));
                    }
                    break;

                case Schemes.s323:
                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin), new Size(sqr_3.Width, hp3)));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding * 2) + hp3 + hp3), new Size(sqr_3.Width, hp3)));
                    }
                    for (int i = 0; i < 2; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_2.Width + padding)), margin + padding + hp3), new Size(sqr_2.Width, hp3)));
                    }
                    break;

                case Schemes.s333:
                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin), new Size(sqr_3.Width, hp3)));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding) + hp3), new Size(sqr_3.Width, hp3)));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding * 2) + hp3 + hp3), new Size(sqr_3.Width, hp3)));
                    }
                    break;

                case Schemes.s434:
                    for (int i = 0; i < 3; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin), new Size(sqr_3.Width, hp3)));
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + (i * (sqr_3.Width + padding)), margin + (padding * 2) + hp3 + hp3), new Size(sqr_3.Width, hp3)));
                    }
                    for (int i = 0; i < 4; i++)
                    {
                        g.DrawRectangle(Pens.Red, new Rectangle(new Point(margin + 1 + (i * (sqr_4.Width + padding)), margin + padding + hp3), new Size(sqr_4.Width, hp3)));
                    }
                    break;
                }
            }

            return(b);
        }
    protected override void OnPaint(PaintEventArgs e)
    {
        G = e.Graphics;

        base.OnPaint(e);

        G.Clear(Parent.BackColor);

        switch (Scheme)
        {
        case Schemes.Black:


            if (Enabled)
            {
                if (State == Helpers.MouseState.None)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(54, 54, 53)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(42, 42, 41)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }
                }
                else if (State == Helpers.MouseState.Over)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(58, 58, 57)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(46, 46, 45)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }
                }
                else if (State == Helpers.MouseState.Down)
                {
                    using (SolidBrush Background = new SolidBrush(Color.FromArgb(50, 50, 49)))
                    {
                        using (Pen Border = new Pen(Color.FromArgb(38, 38, 37)))
                        {
                            G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                            G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        }
                    }
                }
            }
            else
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(40, 40, 39)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(38, 38, 37)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }

            break;

        case Schemes.Green:


            if (State == Helpers.MouseState.None)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(123, 164, 93)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(119, 160, 89)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Over)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(127, 168, 97)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(123, 164, 93)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Down)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(119, 160, 93)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(115, 156, 85)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }

            break;

        case Schemes.Red:


            if (State == Helpers.MouseState.None)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(164, 93, 93)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(160, 89, 89)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Over)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(168, 97, 97)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(164, 93, 93)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Down)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(160, 89, 89)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(156, 85, 85)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }

            break;

        case Schemes.Blue:


            if (State == Helpers.MouseState.None)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(93, 154, 164)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(89, 150, 160)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Over)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(97, 160, 168)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(93, 154, 164)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }
            else if (State == Helpers.MouseState.Down)
            {
                using (SolidBrush Background = new SolidBrush(Color.FromArgb(89, 150, 160)))
                {
                    using (Pen Border = new Pen(Color.FromArgb(85, 146, 156)))
                    {
                        G.FillPath(Background, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                        G.DrawPath(Border, Helpers.RoundRect(new Rectangle(0, 0, Width - 1, Height - 1), 2));
                    }
                }
            }

            break;
        }


        if (Scheme == Schemes.Black)
        {
            if (Enabled)
            {
                using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(220, 220, 219)))
                {
                    using (Font TextFont = new Font("Segoe UI", 9))
                    {
                        using (StringFormat SF = new StringFormat {
                            Alignment = StringAlignment.Center
                        })
                        {
                            G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                        }
                    }
                }
            }
            else
            {
                using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(140, 140, 139)))
                {
                    using (Font TextFont = new Font("Segoe UI", 9))
                    {
                        using (StringFormat SF = new StringFormat {
                            Alignment = StringAlignment.Center
                        })
                        {
                            G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                        }
                    }
                }
            }
        }
        else
        {
            if (!Enabled)
            {
                Scheme = Schemes.Black;
            }

            using (SolidBrush TextBrush = new SolidBrush(Color.FromArgb(250, 250, 249)))
            {
                using (Font TextFont = new Font("Segoe UI", 9))
                {
                    using (StringFormat SF = new StringFormat {
                        Alignment = StringAlignment.Center
                    })
                    {
                        G.DrawString(Text, TextFont, TextBrush, new Rectangle(0, Height / 2 - 9, Width, Height), SF);
                    }
                }
            }
        }
    }
示例#28
0
        // 重写异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            /*
             * .netcore3.0 启用EndpointRouting后,权限filter不再添加到ActionDescriptor ,而将权限直接作为中间件运行,
             * 同时所有filter都会添加到endpoint.Metadata。因此,文中的
             * context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext不再成立。
             *
             * 解决方案有两个:
             *
             * 首先必须在 controller 上进行配置 Authorize ,可以策略授权,也可以角色等基本授权
             *
             * 1、开启公约, startup 中的全局授权过滤公约:o.Conventions.Insert(0, new GlobalRouteAuthorizeConvention());
             *
             * 2、不开启公约,使用 IHttpContextAccessor ,也能实现效果,但是不能自定义返回格式,详细看下边配置;
             */

            // 将最新的角色和接口列表更新
            var data = await RoleModulePermissionServices.GetRoleModule();

            var list = (from item in data
                        where item.IsDeleted == false
                        orderby item.Id
                        select new PermissionItem
            {
                Url = item.Module?.LinkUrl,
                Role = item.Role?.Name,
            }).ToList();

            requirement.Permissions = list;


            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var filterContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext);
            var httpContext   = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            if (httpContext == null)
            {
                httpContext = _accessor.HttpContext;
            }

            //请求Url
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        //context.Fail();
                        //return;

                        //自定义返回数据
                        var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口,请确保已经登录!" });
                        httpContext.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                        httpContext.Response.ContentType = "application/json";
                        await httpContext.Response.WriteAsync(payload);

                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        //权限中是否存在请求的url
                        //if (requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key?.ToLower() == questUrl).Count() > 0)
                        //if (isMatchUrl)
                        if (true)
                        {
                            // 获取当前用户的角色信息
                            var currentUserRoles = (from item in httpContext.User.Claims
                                                    where item.Type == requirement.ClaimType
                                                    select item.Value).ToList();

                            var isMatchRole      = false;
                            var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                            foreach (var item in permisssionRoles)
                            {
                                try
                                {
                                    if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
                                    {
                                        isMatchRole = true;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }

                            //验证权限
                            //if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                            if (currentUserRoles.Count <= 0 || !isMatchRole)
                            {
                                // 可以在这里设置跳转页面
                                //context.Fail();
                                //return;

                                var payload = JsonConvert.SerializeObject(new { Code = "403", Message = "很抱歉,您的访问权限等级不够,联系管理员!" });
                                httpContext.Response.StatusCode  = StatusCodes.Status403Forbidden;
                                httpContext.Response.ContentType = "application/json";
                                await httpContext.Response.WriteAsync(payload);

                                return;
                            }
                        }

                        //判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            //context.Fail();
                            //return;

                            //自定义返回数据
                            var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口,请确保已经登录!" });
                            httpContext.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                            httpContext.Response.ContentType = "application/json";
                            await httpContext.Response.WriteAsync(payload);

                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
                {
                    //context.Fail();
                    //return;

                    //自定义返回数据
                    var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口,请确保已经登录!" });
                    httpContext.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                    httpContext.Response.ContentType = "application/json";
                    await httpContext.Response.WriteAsync(payload);

                    return;
                }
            }

            context.Succeed(requirement);
        }
示例#29
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            ////赋值用户权限
            Requirement = requirement;
            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            //请求Url
            var questUrl = httpContext.Request.Path.Value.ToLower();
            //判断请求是否停止
            //var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
            //foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
            //{
            //	var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler;
            //	if (handler != null && await handler.HandleRequestAsync())
            //	{
            //		context.Fail();
            //		return;
            //	}
            //}
            //判断请求是否拥有凭据,即有没有登录
            var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                //result?.Principal不为空即登录成功
                if (result?.Principal != null)
                {
                    httpContext.User = result.Principal;
                    //权限中是否存在请求的url
                    if (Requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key.ToLower() == questUrl).Count() > 0)
                    {
                        var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value;
                        //验证权限
                        if (Requirement.Permissions.Where(w => w.Name == name && w.Url.ToLower() == questUrl).Count() <= 0)
                        {
                            //无权限跳转到拒绝页面
                            httpContext.Response.Redirect(requirement.DeniedAction);
                        }
                    }
                    //判断过期时间
                    if (DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == "exp").Value) >= DateTime.Now)
                    {
                        context.Succeed(requirement);
                    }
                    else
                    {
                        context.Fail();
                    }
                    return;
                }
            }
            //判断没有登录时,是否访问登录的url,并且是Post请求,并助是form表单提交类型,否则为失败

            if (!questUrl.Equals(Requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType))
            {
                context.Fail();
                return;
            }
            context.Succeed(requirement);
        }
示例#30
0
        /// <summary>
        /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes.
        /// </summary>
        /// <param name="context">The modified document context.</param>
        /// <param name="previous">The original document model.</param>
        /// <returns>A list of messages from the comparison.</returns>
        public override IEnumerable <ComparisonMessage> Compare(
            ComparisonContext <ServiceDefinition> context,
            ServiceDefinition previousDefinition
            )
        {
            if (context.CurrentRoot != this)
            {
                throw new ArgumentException("context.CurrentRoot != this");
            }
            if (context.PreviousRoot != previousDefinition)
            {
                throw new ArgumentException("context.PreviousRoot != previousDefinition");
            }

            if (previousDefinition == null)
            {
                throw new ArgumentException("Comparing a service definition with something else.");
            }

            base.Compare(context, previousDefinition);

            if (Info?.Version != null &&
                previousDefinition.Info?.Version != null)
            {
                context.PushProperty("info");
                context.PushProperty("version");

                CompareVersions(context, Info.Version, previousDefinition.Info.Version);

                context.Pop();
                context.Pop();
            }

            if (context.Strict)
            {
                // There was no version change between the documents. This is not an error, but noteworthy.
                context.LogInfo(ComparisonMessages.NoVersionChange);
            }

            // Check that all the protocols of the old version are supported by the new version.

            context.PushProperty("schemes");
            foreach (var scheme in previousDefinition.Schemes)
            {
                if (!Schemes.Contains(scheme))
                {
                    context.LogBreakingChange(ComparisonMessages.ProtocolNoLongerSupported, scheme);
                }
            }
            context.Pop();

            // Check that all the request body formats that were accepted still are.

            context.PushProperty("consumes");
            foreach (var format in previousDefinition.Consumes)
            {
                if (!Consumes.Contains(format))
                {
                    context.LogBreakingChange(ComparisonMessages.RequestBodyFormatNoLongerSupported, format);
                }
            }
            context.Pop();

            // Check that all the response body formats were also supported by the old version.

            context.PushProperty("produces");
            foreach (var format in Produces)
            {
                if (!previousDefinition.Produces.Contains(format))
                {
                    context.LogBreakingChange(ComparisonMessages.ResponseBodyFormatNowSupported, format);
                }
            }
            context.Pop();

            // Check that no paths were removed, and compare the paths that are still there.

            var newPaths = RemovePathVariables(Paths);

            context.PushProperty("paths");
            foreach (var path in previousDefinition.Paths.Keys)
            {
                var p = ObjectPath.OpenApiPathName(path);

                context.PushPathProperty(path);

                if (!newPaths.TryGetValue(p, out var operations))
                {
                    // Entrie path was removeed
                    context.LogBreakingChange(ComparisonMessages.RemovedPath, path);
                }
                else
                {
                    // 1. Remove this path from the current list to find the added paths
                    newPaths.Remove(p);
                    var copyOfOperations = operations.ToDictionary(e => e.Key, e => e.Value);

                    // 2. look for operation match inside this path
                    var previousOperations = previousDefinition.Paths[path];
                    foreach (var previousOperation in previousOperations)
                    {
                        if (!operations.TryGetValue(previousOperation.Key, out var newOperation))
                        {
                            // Operation was removed from the path
                            context.LogBreakingChange(ComparisonMessages.RemovedOperation, previousOperation.Value.OperationId);
                        }
                        else
                        {
                            copyOfOperations.Remove(previousOperation.Key);
                        }
                    }

                    // Look for added operations
                    foreach (var copyOfOperation in copyOfOperations)
                    {
                        context.PushProperty(copyOfOperation.Key);
                        context.LogInfo(ComparisonMessages.AddedOperation);
                        context.Pop();
                    }

                    // Compare operations
                    foreach (var operation in operations)
                    {
                        if (previousDefinition.Paths[path].TryGetValue(operation.Key, out var previousOperation))
                        {
                            context.PushProperty(operation.Key);
                            operation.Value.Compare(context, previousOperation);
                            context.Pop();
                        }
                    }
                }
                context.Pop();
            }

            // Check wether any new paths are being added
            foreach (var path in newPaths.Keys)
            {
                context.PushPathProperty(path);
                context.LogInfo(ComparisonMessages.AddedPath);
                context.Pop();
            }


            context.Pop();

            // Check for custom paths : x-ms-paths
            var newCustomPaths = RemovePathVariables(CustomPaths);

            context.PushProperty("x-ms-paths");
            foreach (var path in previousDefinition.CustomPaths.Keys)
            {
                var p = ObjectPath.OpenApiPathName(path);

                context.PushPathProperty(path);

                Dictionary <string, Operation> operations = null;
                if (!newCustomPaths.TryGetValue(p, out operations))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedPath, path);
                }
                else
                {
                    // 1. Remove this custom path from the current list to find the added paths
                    newCustomPaths.Remove(p);
                    Dictionary <string, Operation> copyOfOperations = operations.ToDictionary(e => e.Key, e => e.Value);

                    // 2. look for operation match inside this path
                    Dictionary <string, Operation> previousOperations = previousDefinition.CustomPaths[path];
                    foreach (var previousOperation in previousOperations)
                    {
                        Operation newOperation = null;
                        if (!operations.TryGetValue(previousOperation.Key, out newOperation))
                        {
                            context.LogBreakingChange(ComparisonMessages.RemovedOperation, previousOperation.Value.OperationId);
                        }
                    }

                    // Look for added operations
                    foreach (var copyOfOperation in copyOfOperations)
                    {
                        context.PushProperty(copyOfOperation.Key);
                        context.LogInfo(ComparisonMessages.AddedOperation);
                        context.Pop();
                    }

                    // Compare operations
                    foreach (var operation in operations)
                    {
                        Operation previousOperation = null;
                        if (previousDefinition.CustomPaths[path].TryGetValue(operation.Key, out previousOperation))
                        {
                            context.PushProperty(operation.Key);
                            operation.Value.Compare(context, previousOperation);
                            context.Pop();
                        }
                    }
                }
                context.Pop();
            }

            // Check wether any new paths are being added into x-ms-paths
            foreach (var path in newCustomPaths.Keys)
            {
                context.PushPathProperty(path);
                context.LogInfo(ComparisonMessages.AddedPath);
                context.Pop();
            }

            context.Pop();

            ReferenceTrackSchemas(this);
            ReferenceTrackSchemas(previousDefinition);

            context.PushProperty("parameters");
            foreach (var def in previousDefinition.Parameters.Keys)
            {
                SwaggerParameter parameter = null;
                if (!Parameters.TryGetValue(def, out parameter))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedClientParameter, def);
                }
                else
                {
                    context.PushProperty(def);
                    parameter.Compare(context, previousDefinition.Parameters[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.PushProperty("responses");
            foreach (var def in previousDefinition.Responses.Keys)
            {
                OperationResponse response = null;
                if (!Responses.TryGetValue(def, out response))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedDefinition, def);
                }
                else
                {
                    context.PushProperty(def);
                    response.Compare(context, previousDefinition.Responses[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.PushProperty("definitions");
            foreach (var def in previousDefinition.Definitions.Keys)
            {
                Schema schema    = null;
                Schema oldSchema = previousDefinition.Definitions[def];

                if (!Definitions.TryGetValue(def, out schema))
                {
                    if (oldSchema.IsReferenced)
                    {
                        // It's only an error if the definition is referenced in the old service.
                        context.LogBreakingChange(ComparisonMessages.RemovedDefinition, def);
                    }
                }
                else
                {
                    context.PushProperty(def);
                    schema.Compare(context, previousDefinition.Definitions[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.Pop();

            return(context.Messages);
        }
示例#31
0
 public bool AddScheme(Schemes a)
 {
     return(admin.AddScheme(a));
 }
        /// <summary>
        /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes.
        /// </summary>
        /// <param name="context">The modified document context.</param>
        /// <param name="previous">The original document model.</param>
        /// <returns>A list of messages from the comparison.</returns>
        public override IEnumerable <ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous)
        {
            if (previous == null)
            {
                throw new ArgumentNullException("previous");
            }

            context.CurrentRoot  = this;
            context.PreviousRoot = previous;

            base.Compare(context, previous);

            var previousDefinition = previous as ServiceDefinition;

            if (previousDefinition == null)
            {
                throw new ArgumentException("Comparing a service definition with something else.");
            }

            if (Info != null && previousDefinition.Info != null)
            {
                context.PushProperty("info");
                context.PushProperty("version");

                CompareVersions(context, Info.Version, previousDefinition.Info.Version);

                context.Pop();
                context.Pop();
            }

            if (context.Strict)
            {
                // There was no version change between the documents. This is not an error, but noteworthy.
                context.LogInfo(ComparisonMessages.NoVersionChange);
            }

            // Check that all the protocols of the old version are supported by the new version.

            context.PushProperty("schemes");
            foreach (var scheme in previousDefinition.Schemes)
            {
                if (!Schemes.Contains(scheme))
                {
                    context.LogBreakingChange(ComparisonMessages.ProtocolNoLongerSupported, scheme);
                }
            }
            context.Pop();

            // Check that all the request body formats that were accepted still are.

            context.PushProperty("consumes");
            foreach (var format in previousDefinition.Consumes)
            {
                if (!Consumes.Contains(format))
                {
                    context.LogBreakingChange(ComparisonMessages.RequestBodyFormatNoLongerSupported, format);
                }
            }
            context.Pop();

            // Check that all the response body formats were also supported by the old version.

            context.PushProperty("produces");
            foreach (var format in Produces)
            {
                if (!previousDefinition.Produces.Contains(format))
                {
                    context.LogBreakingChange(ComparisonMessages.ResponseBodyFormatNowSupported, format);
                }
            }
            context.Pop();

            // Check that no paths were removed, and compare the paths that are still there.

            var newPaths = RemovePathVariables(Paths);

            context.PushProperty("paths");
            foreach (var path in previousDefinition.Paths.Keys)
            {
                var p = Regex.Replace(path, @"\{\w*\}", @"{}");

                context.PushProperty(path);

                Dictionary <string, Operation> operations = null;
                if (!newPaths.TryGetValue(p, out operations))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedPath, path);
                }
                else
                {
                    Dictionary <string, Operation> previousOperations = previousDefinition.Paths[path];
                    foreach (var previousOperation in previousOperations)
                    {
                        Operation newOperation = null;
                        if (!operations.TryGetValue(previousOperation.Key, out newOperation))
                        {
                            context.LogBreakingChange(ComparisonMessages.RemovedOperation, previousOperation.Value.OperationId);
                        }
                    }

                    foreach (var operation in operations)
                    {
                        Operation previousOperation = null;
                        if (previousDefinition.Paths[path].TryGetValue(operation.Key, out previousOperation))
                        {
                            context.PushProperty(operation.Key);
                            operation.Value.Compare(context, previousOperation);
                            context.Pop();
                        }
                    }
                }
                context.Pop();
            }
            context.Pop();

            newPaths = RemovePathVariables(CustomPaths);

            context.PushProperty("x-ms-paths");
            foreach (var path in previousDefinition.CustomPaths.Keys)
            {
                var p = Regex.Replace(path, @"\{\w*\}", @"{}");

                context.PushProperty(path);

                Dictionary <string, Operation> operations = null;
                if (!newPaths.TryGetValue(p, out operations))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedPath, path);
                }
                else
                {
                    Dictionary <string, Operation> previousOperations = previousDefinition.CustomPaths[path];
                    foreach (var previousOperation in previousOperations)
                    {
                        Operation newOperation = null;
                        if (!operations.TryGetValue(previousOperation.Key, out newOperation))
                        {
                            context.LogBreakingChange(ComparisonMessages.RemovedOperation, previousOperation.Value.OperationId);
                        }
                    }

                    foreach (var operation in operations)
                    {
                        Operation previousOperation = null;
                        if (previousDefinition.CustomPaths[path].TryGetValue(operation.Key, out previousOperation))
                        {
                            context.PushProperty(operation.Key);
                            operation.Value.Compare(context, previousOperation);
                            context.Pop();
                        }
                    }
                }
                context.Pop();
            }
            context.Pop();

            ReferenceTrackSchemas(this);
            ReferenceTrackSchemas(previousDefinition);

            context.PushProperty("parameters");
            foreach (var def in previousDefinition.Parameters.Keys)
            {
                SwaggerParameter parameter = null;
                if (!Parameters.TryGetValue(def, out parameter))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedClientParameter, def);
                }
                else
                {
                    context.PushProperty(def);
                    parameter.Compare(context, previousDefinition.Parameters[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.PushProperty("responses");
            foreach (var def in previousDefinition.Responses.Keys)
            {
                OperationResponse response = null;
                if (!Responses.TryGetValue(def, out response))
                {
                    context.LogBreakingChange(ComparisonMessages.RemovedDefinition, def);
                }
                else
                {
                    context.PushProperty(def);
                    response.Compare(context, previousDefinition.Responses[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.PushProperty("definitions");
            foreach (var def in previousDefinition.Definitions.Keys)
            {
                Schema schema    = null;
                Schema oldSchema = previousDefinition.Definitions[def];

                if (!Definitions.TryGetValue(def, out schema))
                {
                    if (oldSchema.IsReferenced)
                    {
                        // It's only an error if the definition is referenced in the old service.
                        context.LogBreakingChange(ComparisonMessages.RemovedDefinition, def);
                    }
                }
                else if (schema.IsReferenced && oldSchema.IsReferenced)
                {
                    context.PushProperty(def);
                    schema.Compare(context, previousDefinition.Definitions[def]);
                    context.Pop();
                }
            }
            context.Pop();

            context.Pop();

            return(context.Messages);
        }
示例#33
0
        // 重载异步处理程序
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            // 将最新的角色和接口列表更新
            var data = await RoleModulePermissionServices.GetRoleModule();

            var list = (from item in data
                        where item.IsDeleted == false
                        orderby item.Id
                        select new PermissionItem
            {
                Url = item.Module?.LinkUrl,
                Role = item.Role?.Name,
            }).ToList();

            requirement.Permissions = list;


            //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息
            var filterContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext);
            var httpContext   = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)?.HttpContext;

            //请求Url
            if (httpContext != null)
            {
                var questUrl = httpContext.Request.Path.Value.ToLower();
                //判断请求是否停止
                var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
                {
                    if (await handlers.GetHandlerAsync(httpContext, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
                    {
                        //context.Fail();
                        //return;


                        //自定义返回数据
                        var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口!" });
                        httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        filterContext.Result            = new JsonResult(payload);
                        context.Succeed(requirement);
                        return;
                    }
                }
                //判断请求是否拥有凭据,即有没有登录
                var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);

                    //result?.Principal不为空即登录成功
                    if (result?.Principal != null)
                    {
                        httpContext.User = result.Principal;

                        // 取消对URL的判断,因为只需判断该角色下是否匹配当前URL即可,若不匹配都是无效请求
                        //var isMatchUrl = false;
                        //var permisssionGroup = requirement.Permissions.GroupBy(g => g.Url);
                        //foreach (var item in permisssionGroup)
                        //{
                        //    try
                        //    {
                        //        if (Regex.Match(questUrl, item.Key?.ObjToString().ToLower())?.Value == questUrl)
                        //        {
                        //            isMatchUrl = true;
                        //            break;
                        //        }
                        //    }
                        //    catch (Exception)
                        //    {
                        //    }
                        //}

                        //权限中是否存在请求的url
                        //if (requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key?.ToLower() == questUrl).Count() > 0)
                        //if (isMatchUrl)
                        if (true)
                        {
                            // 获取当前用户的角色信息
                            var currentUserRoles = (from item in httpContext.User.Claims
                                                    where item.Type == requirement.ClaimType
                                                    select item.Value).ToList();

                            var isMatchRole      = false;
                            var permisssionRoles = requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role));
                            foreach (var item in permisssionRoles)
                            {
                                try
                                {
                                    if (Regex.Match(questUrl, item.Url?.ObjToString().ToLower())?.Value == questUrl)
                                    {
                                        isMatchRole = true;
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }

                            //验证权限
                            //if (currentUserRoles.Count <= 0 || requirement.Permissions.Where(w => currentUserRoles.Contains(w.Role) && w.Url.ToLower() == questUrl).Count() <= 0)
                            if (currentUserRoles.Count <= 0 || !isMatchRole)
                            {
                                //context.Fail();
                                //return;


                                //自定义返回数据
                                var payload = JsonConvert.SerializeObject(new { Code = "403", Message = "很抱歉,您无权访问该接口!" });
                                httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
                                filterContext.Result            = new JsonResult(payload);
                                context.Succeed(requirement);
                                return;


                                // 可以在这里设置跳转页面,不过还是会访问当前接口地址的
                                //httpContext.Response.Redirect(requirement.DeniedAction);
                            }
                        }
                        //else
                        //{
                        //    context.Fail();
                        //    return;

                        //}
                        //判断过期时间(这里仅仅是最坏验证原则,你可以不要这个if else的判断,因为我们使用的官方验证,Token过期后上边的result?.Principal 就为 null 了,进不到这里了,因此这里其实可以不用验证过期时间,只是做最后严谨判断)
                        if ((httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) != null && DateTime.Parse(httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Expiration)?.Value) >= DateTime.Now)
                        {
                            context.Succeed(requirement);
                        }
                        else
                        {
                            //context.Fail();
                            //return;


                            //自定义返回数据
                            var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口!" });
                            httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            filterContext.Result            = new JsonResult(payload);
                            context.Succeed(requirement);
                            return;
                        }
                        return;
                    }
                }
                //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败
                if (!questUrl.Equals(requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") ||
                                                                                                    !httpContext.Request.HasFormContentType))
                {
                    //context.Fail();
                    //return;


                    //自定义返回数据
                    var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口!" });
                    httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    filterContext.Result            = new JsonResult(payload);
                }
            }

            context.Succeed(requirement);
        }
示例#34
0
        /// <summary>
        /// Add a transfer protocol
        /// </summary>
        /// <param name="scheme">
        /// The scheme.
        /// </param>
        /// <returns>
        /// The <see cref="OperationBuilder"/>.
        /// </returns>
        public OperationBuilder Scheme(Schemes scheme)
        {
            if (this.schemes == null)
            {
                this.schemes = new List<Schemes>();
            }

            this.schemes.Add(scheme);
            return this;
        }