コード例 #1
0
ファイル: AuthServer.cs プロジェクト: zeevir/extensions
        public static void Start(IApplicationBuilder app, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());

            AuthTokenServer.Start(tokenConfig, hashableEncryptionKey);

            ReflectionServer.GetContext = () => new
            {
                Culture = ReflectionServer.GetCurrentValidCulture(),
                Role    = UserEntity.Current == null ? null : RoleEntity.Current,
            };

            AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear();

            if (TypeAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (typeof(Entity).IsAssignableFrom(t))
                    {
                        var ta = UserEntity.Current != null?TypeAuthLogic.GetAllowed(t) : null;

                        ti.Extension.Add("maxTypeAllowed", ta == null ? TypeAllowedBasic.None : ta.MaxUI());
                        ti.Extension.Add("minTypeAllowed", ta == null ? TypeAllowedBasic.None : ta.MinUI());
                        ti.RequiresEntityPack |= ta != null && ta.Conditions.Any();
                    }
                };


                EntityPackTS.AddExtension += ep =>
                {
                    var typeAllowed =
                        UserEntity.Current == null ? TypeAllowedBasic.None :
                        ep.entity.IsNew ? TypeAuthLogic.GetAllowed(ep.entity.GetType()).MaxUI() :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Write, true) ? TypeAllowedBasic.Write :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Read, true) ? TypeAllowedBasic.Read :
                        TypeAllowedBasic.None;

                    ep.extension.Add("typeAllowed", typeAllowed);
                };

                OperationController.AnyReadonly += (Lite <Entity>[] lites) =>
                {
                    return(lites.GroupBy(ap => ap.EntityType).Any(gr =>
                    {
                        var ta = TypeAuthLogic.GetAllowed(gr.Key);

                        if (ta.Min(inUserInterface: true) == TypeAllowedBasic.Write)
                        {
                            return false;
                        }

                        if (ta.Max(inUserInterface: true) <= TypeAllowedBasic.Read)
                        {
                            return true;
                        }

                        return giCountReadonly.GetInvoker(gr.Key)() > 0;
                    }));
                };
            }

            if (QueryAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (ti.QueryDefined)
                    {
                        ti.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t));
                    }
                };

                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType !.Name.EndsWith("Query"))
                    {
                        mi.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null) !));
                    }
                };
            }

            if (PropertyAuthLogic.IsStarted)
            {
                ReflectionServer.AddPropertyRouteExtension += (mi, pr) =>
                {
                    mi.Extension.Add("propertyAllowed", UserEntity.Current == null ? PropertyAllowed.None : pr.GetPropertyAllowed());
                };
            }

            if (OperationAuthLogic.IsStarted)
            {
                ReflectionServer.AddOperationExtension += (oits, oi, type) =>
                {
                    oits.Extension.Add("operationAllowed",
                                       UserEntity.Current == null ? false :
                                       OperationAuthLogic.GetOperationAllowed(oi.OperationSymbol, type, inUserInterface: true));
                };
            }

            if (PermissionAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.FieldType == typeof(PermissionSymbol))
                    {
                        mi.Extension.Add("permissionAllowed",
                                         UserEntity.Current == null ? false :
                                         PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null) !));
                    }
                };
            }


            var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash);
            var pcs            = PropertyConverter.GetPropertyConverters(typeof(UserEntity));

            pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { };
            pcs.Add("newPassword", new PropertyConverter
            {
                AvoidValidate           = true,
                CustomWriteJsonProperty = ctx => { },
                CustomReadJsonProperty  = ctx =>
                {
                    EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash));

                    var password = (string)ctx.JsonReader.Value !;

                    var error = UserEntity.OnValidatePassword(password);
                    if (error != null)
                    {
                        throw new ApplicationException(error);
                    }

                    ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password);
                }
            });
コード例 #2
0
        public static void Start(IApplicationBuilder app, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());

            AuthTokenServer.Start(tokenConfig, hashableEncryptionKey);

            ReflectionServer.GetContext = () => new
            {
                Culture = ReflectionServer.GetCurrentValidCulture(),
                Role    = UserEntity.Current == null ? null : RoleEntity.Current,
            };

            AuthLogic.OnRulesChanged += ReflectionServer.InvalidateCache;

            if (TypeAuthLogic.IsStarted)
            {
                ReflectionServer.TypeExtension += (ti, t) =>
                {
                    if (typeof(Entity).IsAssignableFrom(t))
                    {
                        if (UserEntity.Current == null)
                        {
                            return(null);
                        }

                        var ta = TypeAuthLogic.GetAllowed(t);

                        if (ta.MaxUI() == TypeAllowedBasic.None)
                        {
                            return(null);
                        }

                        ti.Extension.Add("maxTypeAllowed", ta.MaxUI());
                        ti.Extension.Add("minTypeAllowed", ta.MinUI());
                        ti.RequiresEntityPack |= ta.Conditions.Any();

                        return(ti);
                    }
                    else
                    {
                        if (t.HasAttribute <AllowUnathenticatedAttribute>())
                        {
                            return(ti);
                        }

                        if (UserEntity.Current == null)
                        {
                            return(null);
                        }

                        if (!AuthServer.IsNamespaceAllowed(t))
                        {
                            return(null);
                        }

                        return(ti);
                    }
                };


                EntityPackTS.AddExtension += ep =>
                {
                    var typeAllowed =
                        UserEntity.Current == null ? TypeAllowedBasic.None :
                        ep.entity.IsNew ? TypeAuthLogic.GetAllowed(ep.entity.GetType()).MaxUI() :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Write, true) ? TypeAllowedBasic.Write :
                        TypeAuthLogic.IsAllowedFor(ep.entity, TypeAllowedBasic.Read, true) ? TypeAllowedBasic.Read :
                        TypeAllowedBasic.None;

                    ep.extension.Add("typeAllowed", typeAllowed);
                };

                OperationController.AnyReadonly += (Lite <Entity>[] lites) =>
                {
                    return(lites.GroupBy(ap => ap.EntityType).Any(gr =>
                    {
                        var ta = TypeAuthLogic.GetAllowed(gr.Key);

                        if (ta.Min(inUserInterface: true) == TypeAllowedBasic.Write)
                        {
                            return false;
                        }

                        if (ta.Max(inUserInterface: true) <= TypeAllowedBasic.Read)
                        {
                            return true;
                        }

                        return giCountReadonly.GetInvoker(gr.Key)() > 0;
                    }));
                };
            }

            if (QueryAuthLogic.IsStarted)
            {
                ReflectionServer.TypeExtension += (ti, t) =>
                {
                    if (ti.QueryDefined)
                    {
                        var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t);
                        if (allowed == QueryAllowed.None)
                        {
                            ti.QueryDefined = false;
                        }

                        ti.Extension.Add("queryAllowed", allowed);
                    }

                    return(ti);
                };

                ReflectionServer.FieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType !.Name.EndsWith("Query"))
                    {
                        var allowed = UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null) !);

                        if (allowed == QueryAllowed.None)
                        {
                            return(null);
                        }

                        mi.Extension.Add("queryAllowed", allowed);
                    }
                    return(mi);
                };
            }

            if (PropertyAuthLogic.IsStarted)
            {
                ReflectionServer.PropertyRouteExtension += (mi, pr) =>
                {
                    var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed();

                    if (allowed == PropertyAllowed.None)
                    {
                        return(null);
                    }

                    mi.Extension.Add("propertyAllowed", allowed);
                    return(mi);
                };

                SignumServer.WebEntityJsonConverterFactory.CanReadPropertyRoute += (pr, mod) =>
                {
                    var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed();

                    return(allowed == PropertyAllowed.None ? "Not allowed" : null);
                };

                SignumServer.WebEntityJsonConverterFactory.CanWritePropertyRoute += (pr, mod) =>
                {
                    var allowed = UserEntity.Current == null?pr.GetAllowUnathenticated() : pr.GetPropertyAllowed();

                    return(allowed == PropertyAllowed.Write ? null : "Not allowed to write property: " + pr.ToString());
                };
            }

            if (OperationAuthLogic.IsStarted)
            {
                ReflectionServer.OperationExtension += (oits, oi, type) =>
                {
                    var allowed = UserEntity.Current == null ? false :
                                  OperationAuthLogic.GetOperationAllowed(oi.OperationSymbol, type, inUserInterface: true);

                    if (!allowed)
                    {
                        return(null);
                    }

                    return(oits);
                };
            }

            if (PermissionAuthLogic.IsStarted)
            {
                ReflectionServer.FieldInfoExtension += (mi, fi) =>
                {
                    if (fi.FieldType == typeof(PermissionSymbol))
                    {
                        var allowed = UserEntity.Current == null ? false :
                                      PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null) !);

                        if (allowed == false)
                        {
                            return(null);
                        }
                    }

                    return(mi);
                };
            }

            var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash);
            var pcs            = SignumServer.WebEntityJsonConverterFactory.GetPropertyConverters(typeof(UserEntity));

            pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = (writer, ctx) => { };
            pcs.Add("newPassword", new PropertyConverter
            {
                AvoidValidate           = true,
                CustomWriteJsonProperty = (Utf8JsonWriter writer, WriteJsonPropertyContext ctx) => { },
                CustomReadJsonProperty  = (ref Utf8JsonReader reader, ReadJsonPropertyContext ctx) =>
                {
                    SignumServer.WebEntityJsonConverterFactory.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash), ctx.Entity);

                    var password = reader.GetString();

                    if (password == null)
                    {
                        ((UserEntity)ctx.Entity).PasswordHash = null;
                    }
                    else
                    {
                        var error = UserEntity.OnValidatePassword(password);
                        if (error != null)
                        {
                            throw new ApplicationException(error);
                        }

                        ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password);
                    }
                }
            });

            if (TypeAuthLogic.IsStarted)
            {
                Omnibox.OmniboxServer.IsNavigable += type => TypeAuthLogic.GetAllowed(type).MaxUI() >= TypeAllowedBasic.Read;
            }

            if (SessionLogLogic.IsStarted)
            {
                AuthServer.UserLogged += (ActionContext ac, UserEntity user) =>
                {
                    Microsoft.AspNetCore.Http.HttpRequest re = ac.HttpContext.Request;
                    SessionLogLogic.SessionStart(
                        re.Host.ToString(),
                        re.Headers["User-Agent"].FirstOrDefault());
                }
            }
            ;

            SchemaMap.GetColorProviders += GetMapColors;
        }
コード例 #3
0
ファイル: AuthServer.cs プロジェクト: crazyants/extensions
        public static void Start(HttpConfiguration config, Func <AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());

            AuthTokenServer.Start(tokenConfig, hashableEncryptionKey);

            ReflectionServer.GetContext = () => new
            {
                Culture = ReflectionServer.GetCurrentValidCulture(),
                Role    = UserEntity.Current == null ? null : RoleEntity.Current,
            };

            AuthLogic.OnRulesChanged += () => ReflectionServer.cache.Clear();

            if (TypeAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (typeof(Entity).IsAssignableFrom(t))
                    {
                        ti.Extension.Add("typeAllowed", UserEntity.Current == null ? TypeAllowedBasic.None : TypeAuthLogic.GetAllowed(t).MaxUI());
                    }
                };
            }

            if (QueryAuthLogic.IsStarted)
            {
                ReflectionServer.AddTypeExtension += (ti, t) =>
                {
                    if (ti.QueryDefined)
                    {
                        ti.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(t));
                    }
                };

                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType.Name.EndsWith("Query"))
                    {
                        mi.Extension.Add("queryAllowed", UserEntity.Current == null ? QueryAllowed.None : QueryAuthLogic.GetQueryAllowed(fi.GetValue(null)));
                    }
                };
            }

            if (PropertyAuthLogic.IsStarted)
            {
                ReflectionServer.AddPropertyRouteExtension += (mi, pr) =>
                {
                    mi.Extension.Add("propertyAllowed", UserEntity.Current == null ? PropertyAllowed.None : pr.GetPropertyAllowed());
                };
            }

            if (OperationAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.DeclaringType.Name.EndsWith("Operation"))
                    {
                        if (fi.GetValue(null) is IOperationSymbolContainer container)
                        {
                            mi.Extension.Add("operationAllowed",
                                             UserEntity.Current == null ? false
                                    : OperationAuthLogic.GetOperationAllowed(container.Symbol, inUserInterface: true));
                        }
                    }
                };
            }

            if (PermissionAuthLogic.IsStarted)
            {
                ReflectionServer.AddFieldInfoExtension += (mi, fi) =>
                {
                    if (fi.FieldType == typeof(PermissionSymbol))
                    {
                        mi.Extension.Add("permissionAllowed",
                                         UserEntity.Current == null
                                ? false
                                : PermissionAuthLogic.IsAuthorized((PermissionSymbol)fi.GetValue(null)));
                    }
                };
            }


            var piPasswordHash = ReflectionTools.GetPropertyInfo((UserEntity e) => e.PasswordHash);
            var pcs            = PropertyConverter.GetPropertyConverters(typeof(UserEntity));

            pcs.GetOrThrow("passwordHash").CustomWriteJsonProperty = ctx => { };
            pcs.Add("newPassword", new PropertyConverter
            {
                AvoidValidate           = true,
                CustomWriteJsonProperty = ctx => { },
                CustomReadJsonProperty  = ctx =>
                {
                    EntityJsonConverter.AssertCanWrite(ctx.ParentPropertyRoute.Add(piPasswordHash));

                    var password = (string)ctx.JsonReader.Value;

                    var error = UserEntity.OnValidatePassword(password);
                    if (error != null)
                    {
                        throw new ApplicationException(error);
                    }

                    ((UserEntity)ctx.Entity).PasswordHash = Security.EncodePassword(password);
                }
            });

            if (TypeAuthLogic.IsStarted)
            {
                Omnibox.OmniboxServer.IsNavigable += type => TypeAuthLogic.GetAllowed(type).MaxUI() >= TypeAllowedBasic.Read;
            }

            SchemaMap.GetColorProviders += GetMapColors;
        }
コード例 #4
0
        public static void Start(bool types, bool property, bool queries, bool resetPassword, bool passwordExpiration, bool singleSignOnMessage)
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                ResetPasswordStarted = resetPassword;
                SingleSignOnMessage  = singleSignOnMessage;

                Navigator.RegisterArea(typeof(AuthClient));

                if (!Navigator.Manager.EntitySettings.ContainsKey(typeof(UserEntity)))
                {
                    Navigator.AddSetting(new EntitySettings <UserEntity>());
                }

                if (!Navigator.Manager.EntitySettings.ContainsKey(typeof(RoleEntity)))
                {
                    Navigator.AddSetting(new EntitySettings <RoleEntity>());
                }

                if (resetPassword)
                {
                    Navigator.AddSetting(new EntitySettings <ResetPasswordRequestEntity>());
                }

                if (passwordExpiration)
                {
                    Navigator.AddSetting(new EntitySettings <PasswordExpiresIntervalEntity> {
                        PartialViewName = _ => ViewPrefix.FormatWith("PasswordValidInterval")
                    });
                }

                Navigator.AddSetting(new ModelEntitySettings <SetPasswordModel>
                {
                    PartialViewName = _ => ViewPrefix.FormatWith("SetPassword"),
                    MappingDefault  = new EntityMapping <SetPasswordModel>(false)
                                      .SetProperty(a => a.PasswordHash, ctx => UserMapping.GetNewPassword(ctx, UserMapping.NewPasswordKey, UserMapping.NewPasswordBisKey))
                });

                if (property)
                {
                    Common.CommonTask += TaskAuthorizeProperties;
                    Mapping.CanChange += Mapping_CanChange;
                }


                var manager = Navigator.Manager;
                if (types)
                {
                    manager.IsCreable  += manager_IsCreable;
                    manager.IsReadOnly += manager_IsReadOnly;
                    manager.IsViewable += manager_IsViewable;
                }

                if (queries)
                {
                    Finder.Manager.IsFindable += q => QueryAuthLogic.GetQueryAllowed(q) != QueryAllowed.None;
                }

                AuthenticationRequiredAttribute.Authenticate = context =>
                {
                    if (UserEntity.Current == null)
                    {
                        string returnUrl = context.HttpContext.Request.SuggestedReturnUrl().PathAndQuery;

                        //send them off to the login page
                        string loginUrl = PublicLoginUrl(returnUrl);
                        context.Result = context.Controller.RedirectHttpOrAjax(loginUrl);
                    }
                };

                Schema.Current.EntityEvents <UserEntity>().Saving += AuthClient_Saving;

                var defaultException = SignumExceptionHandlerAttribute.OnControllerException;
                SignumExceptionHandlerAttribute.OnControllerException = ctx =>
                {
                    if (ctx.Exception is UnauthorizedAccessException && (UserEntity.Current == null || UserEntity.Current.Is(AuthLogic.AnonymousUser)))
                    {
                        string returnUrl = ctx.HttpContext.Request.SuggestedReturnUrl().PathAndQuery;
                        string loginUrl  = PublicLoginUrl(returnUrl);

                        DefaultOnControllerUnauthorizedAccessException(ctx, loginUrl);
                    }
                    else
                    {
                        defaultException(ctx);
                    }
                };

                OperationClient.AddSettings(new List <OperationSettings>
                {
                    new EntityOperationSettings <UserEntity>(UserOperation.SetPassword)
                    {
                        Click = ctx => Module["setPassword"](ctx.Options(),
                                                             ctx.Url.Action((AuthController c) => c.SetPasswordModel()),
                                                             ctx.Url.Action((AuthController c) => c.SetPasswordOnOk()))
                    },

                    new EntityOperationSettings <UserEntity>(UserOperation.SaveNew)
                    {
                        Click = ctx => Module["saveNew"](ctx.Options(),
                                                         ctx.Url.Action((AuthController c) => c.SaveNewUser()))
                    }
                });
            }
        }