コード例 #1
0
ファイル: AuthController.cs プロジェクト: ywscr/extensions
        public ActionResult <LoginResponse> ChangePassword([Required, FromBody] ChangePasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.oldPassword))
            {
                return(ModelError("oldPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            if (string.IsNullOrEmpty(request.newPassword))
            {
                return(ModelError("newPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            var user = UserEntity.Current;

            if (!user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword)))
            {
                return(ModelError("oldPassword", AuthMessage.InvalidPassword.NiceToString()));
            }

            user.PasswordHash = Security.EncodePassword(request.newPassword);
            using (AuthLogic.Disable())
                user.Execute(UserOperation.Save);

            return(new LoginResponse {
                userEntity = user, token = AuthTokenServer.CreateToken(UserEntity.Current)
            });
        }
コード例 #2
0
        public LoginResponse LoginFromApiKey(string apiKey)
        {
            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                userEntity = UserEntity.Current, token = token, authenticationType = "api-key"
            });
        }
コード例 #3
0
        public LoginResponse RefreshToken([FromBody] string oldToken)
        {
            var newToken = AuthTokenServer.RefreshToken(oldToken, out UserEntity user);

            return(new LoginResponse {
                message = null, userEntity = user, token = newToken
            });
        }
コード例 #4
0
        public LoginResponse LoginFromApiKey(string apiKey)
        {
            string message = AuthLogic.OnLoginMessage();

            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                message = message, userEntity = UserEntity.Current, token = token
            });
        }
コード例 #5
0
        public LoginResponse?LoginFromCookie()
        {
            if (!UserTicketServer.LoginFromCookie(ControllerContext))
            {
                return(null);
            }

            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                userEntity = UserEntity.Current, token = token, authenticationType = "cookie"
            });
        }
コード例 #6
0
ファイル: AuthController.cs プロジェクト: oltur/extensions
        public ActionResult <LoginResponse> ResetPassword([Required, FromBody] ResetPasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.newPassword))
            {
                return(ModelError("newPassword", AuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            var rpr = ResetPasswordRequestLogic.ResetPasswordRequestExecute(request.code, request.newPassword);

            return(new LoginResponse {
                userEntity = rpr.User, token = AuthTokenServer.CreateToken(rpr.User), authenticationType = "resetPassword"
            });
        }
コード例 #7
0
        public LoginResponse?LoginWithAzureAD([FromBody, Required] string jwt, [FromQuery] bool throwErrors = true)
        {
            if (!AzureADAuthenticationServer.LoginAzureADAuthentication(ControllerContext, jwt, throwErrors))
            {
                return(null);
            }

            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                userEntity = UserEntity.Current, token = token, authenticationType = "azureAD"
            });
        }
コード例 #8
0
        public LoginResponse?LoginWithAzureAD([FromBody, Required] string jwt)
        {
            if (!AzureADAuthenticationServer.LoginAzureADAuthentication(ControllerContext, jwt))
            {
                return(null);
            }

            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                message = null, userEntity = UserEntity.Current, token = token, authenticationType = "azureAD"
            });
        }
コード例 #9
0
ファイル: AuthController.cs プロジェクト: ywscr/extensions
        public LoginResponse?LoginWithAzureAD([FromBody, Required] string jwt)
        {
            using (ScopeSessionFactory.OverrideSession())
            {
                if (!AzureADAuthenticationServer.LoginAzureADAuthentication(ControllerContext, jwt))
                {
                    return(null);
                }

                var token = AuthTokenServer.CreateToken(UserEntity.Current);

                return(new LoginResponse {
                    message = null, userEntity = UserEntity.Current, token = token
                });
            }
        }
コード例 #10
0
ファイル: AuthController.cs プロジェクト: ywscr/extensions
        public LoginResponse?LoginWindowsAuthentication()
        {
            using (ScopeSessionFactory.OverrideSession())
            {
                if (!WindowsAuthenticationServer.LoginWindowsAuthentication(ControllerContext))
                {
                    return(null);
                }

                var token = AuthTokenServer.CreateToken(UserEntity.Current);

                return(new LoginResponse {
                    message = null, userEntity = UserEntity.Current, token = token
                });
            }
        }
コード例 #11
0
ファイル: AuthController.cs プロジェクト: oltur/extensions
        public LoginResponse?LoginFromCookie()
        {
            using (ScopeSessionFactory.OverrideSession())
            {
                if (!UserTicketServer.LoginFromCookie(ControllerContext))
                {
                    return(null);
                }

                string?message = AuthLogic.OnLoginMessage();

                var token = AuthTokenServer.CreateToken(UserEntity.Current);

                return(new LoginResponse {
                    message = message, userEntity = UserEntity.Current, token = token, authenticationType = "cookie"
                });
            }
        }
コード例 #12
0
        public LoginResponse LoginFromCookie()
        {
            using (ScopeSessionFactory.OverrideSession())
            {
                if (!UserTicketServer.LoginFromCookie())
                {
                    return(null);
                }

                string message = AuthLogic.OnLoginMessage();

                var token = AuthTokenServer.CreateToken(UserEntity.Current);

                return(new LoginResponse {
                    message = message, userEntity = UserEntity.Current, token = token
                });
            }
        }
コード例 #13
0
        public async Task <LoginResponse> MakeAssertion([FromBody][Required] MakeAssertionRequest request)
        {
            using (AuthLogic.Disable())
                using (Transaction tr = new Transaction())
                {
                    var assertionOptions = Database.Retrieve <WebAuthnAssertionOptionsEntity>(request.AssertionOptionsId);
                    var options          = AssertionOptions.FromJson(assertionOptions.Json);

                    var cred = Database.Query <WebAuthnCredentialEntity>().SingleEx(cred => cred.CredentialId == request.AssertionRawResponse.Id);

                    var res = await fido2.MakeAssertionAsync(request.AssertionRawResponse, options, cred.PublicKey, (uint)cred.Counter, (args) =>
                    {
                        if (!MemoryExtensions.SequenceEqual <byte>(cred.CredentialId, args.CredentialId))
                        {
                            return(Task.FromResult(false));
                        }

                        var userId = Encoding.UTF8.GetBytes(cred.User.Id.ToString());
                        if (!MemoryExtensions.SequenceEqual <byte>(userId, args.UserHandle))
                        {
                            return(Task.FromResult(false));
                        }

                        return(Task.FromResult(true));
                    });

                    cred.Counter++;
                    cred.Save();

                    var user = cred.User.RetrieveAndForget();

                    AuthServer.OnUserPreLogin(ControllerContext, user);

                    AuthServer.AddUserSession(ControllerContext, user);

                    var token = AuthTokenServer.CreateToken(user);

                    return(tr.Commit(new LoginResponse {
                        userEntity = user, token = token, authenticationType = "webauthn"
                    }));
                }
        }
コード例 #14
0
        public ActionResult <LoginResponse> ChangePassword([Required, FromBody] ChangePasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.newPassword))
            {
                return(ModelError("newPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            var error = UserEntity.OnValidatePassword(request.newPassword);

            if (error.HasText())
            {
                return(ModelError("newPassword", error));
            }

            var user = UserEntity.Current;

            if (string.IsNullOrEmpty(request.oldPassword))
            {
                if (user.PasswordHash != null)
                {
                    return(ModelError("oldPassword", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()));
                }
            }
            else
            {
                if (user.PasswordHash == null || !user.PasswordHash.SequenceEqual(Security.EncodePassword(request.oldPassword)))
                {
                    return(ModelError("oldPassword", LoginAuthMessage.InvalidPassword.NiceToString()));
                }
            }

            user.PasswordHash = Security.EncodePassword(request.newPassword);
            using (AuthLogic.Disable())
                using (OperationLogic.AllowSave <UserEntity>())
                {
                    user.Save();
                }

            return(new LoginResponse {
                userEntity = user, token = AuthTokenServer.CreateToken(UserEntity.Current), authenticationType = "changePassword"
            });
        }
コード例 #15
0
        public LoginResponse?LoginWindowsAuthentication(bool throwError)
        {
            string?error = WindowsAuthenticationServer.LoginWindowsAuthentication(ControllerContext);

            if (error != null)
            {
                if (throwError)
                {
                    throw new InvalidOperationException(error);
                }

                return(null);
            }

            var token = AuthTokenServer.CreateToken(UserEntity.Current);

            return(new LoginResponse {
                userEntity = UserEntity.Current, token = token, authenticationType = "windows"
            });
        }
コード例 #16
0
ファイル: AuthController.cs プロジェクト: zeevir/extensions
        public LoginResponse?LoginWindowsAuthentication(bool throwError)
        {
            using (ScopeSessionFactory.OverrideSession())
            {
                string?error = WindowsAuthenticationServer.LoginWindowsAuthentication(ControllerContext);
                if (error != null)
                {
                    if (throwError)
                    {
                        throw new InvalidOperationException(error);
                    }

                    return(null);
                }

                var token = AuthTokenServer.CreateToken(UserEntity.Current);

                return(new LoginResponse {
                    message = null, userEntity = UserEntity.Current, token = token
                });
            }
        }
コード例 #17
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;
        }
コード例 #18
0
        public LoginResponse Login([FromBody] LoginRequest data)
        {
            if (string.IsNullOrEmpty(data.userName))
            {
                throw ModelException("userName", AuthMessage.UserNameMustHaveAValue.NiceToString());
            }

            if (string.IsNullOrEmpty(data.password))
            {
                throw ModelException("password", AuthMessage.PasswordMustHaveAValue.NiceToString());
            }

            // Attempt to login
            UserEntity user = null;

            try
            {
                user = AuthLogic.Login(data.userName, Security.EncodePassword(data.password));
            }
            catch (Exception e) when(e is IncorrectUsernameException || e is IncorrectPasswordException)
            {
                if (AuthServer.MergeInvalidUsernameAndPasswordMessages)
                {
                    ModelState.AddModelError("userName", AuthMessage.InvalidUsernameOrPassword.NiceToString());
                    ModelState.AddModelError("password", AuthMessage.InvalidUsernameOrPassword.NiceToString());
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
                }
                else if (e is IncorrectUsernameException)
                {
                    throw ModelException("userName", AuthMessage.InvalidUsername.NiceToString());
                }
                else if (e is IncorrectPasswordException)
                {
                    throw ModelException("password", AuthMessage.InvalidPassword.NiceToString());
                }
            }
            catch (IncorrectPasswordException)
            {
                throw ModelException("password", AuthServer.MergeInvalidUsernameAndPasswordMessages ?
                                     AuthMessage.InvalidUsernameOrPassword.NiceToString() :
                                     AuthMessage.InvalidPassword.NiceToString());
            }

            using (UserHolder.UserSession(user))
            {
                if (data.rememberMe == true)
                {
                    UserTicketServer.SaveCookie();
                }

                AuthServer.AddUserSession(user);

                string message = AuthLogic.OnLoginMessage();

                var token = AuthTokenServer.CreateToken(user);

                return(new LoginResponse {
                    message = message, userEntity = user, token = token
                });
            }
        }
コード例 #19
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;
        }
コード例 #20
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);
                }
            });
コード例 #21
0
        public ActionResult <LoginResponse> Login([Required, FromBody] LoginRequest data)
        {
            if (string.IsNullOrEmpty(data.userName))
            {
                return(ModelError("userName", LoginAuthMessage.UserNameMustHaveAValue.NiceToString()));
            }

            if (string.IsNullOrEmpty(data.password))
            {
                return(ModelError("password", LoginAuthMessage.PasswordMustHaveAValue.NiceToString()));
            }

            string authenticationType;
            // Attempt to login
            UserEntity user;

            try
            {
                if (AuthLogic.Authorizer == null)
                {
                    user = AuthLogic.Login(data.userName, Security.EncodePassword(data.password), out authenticationType);
                }
                else
                {
                    user = AuthLogic.Authorizer.Login(data.userName, data.password, out authenticationType);
                }
            }
            catch (Exception e) when(e is IncorrectUsernameException || e is IncorrectPasswordException)
            {
                if (AuthServer.MergeInvalidUsernameAndPasswordMessages)
                {
                    return(ModelError("login", LoginAuthMessage.InvalidUsernameOrPassword.NiceToString()));
                }
                else if (e is IncorrectUsernameException)
                {
                    return(ModelError("userName", LoginAuthMessage.InvalidUsername.NiceToString()));
                }
                else if (e is IncorrectPasswordException)
                {
                    return(ModelError("password", LoginAuthMessage.InvalidPassword.NiceToString()));
                }
                throw;
            }
            catch (Exception e)
            {
                return(ModelError("login", e.Message));
            }

            AuthServer.OnUserPreLogin(ControllerContext, user);

            AuthServer.AddUserSession(ControllerContext, user);

            if (data.rememberMe == true)
            {
                UserTicketServer.SaveCookie(ControllerContext);
            }

            var token = AuthTokenServer.CreateToken(user);

            return(new LoginResponse {
                userEntity = user, token = token, authenticationType = authenticationType
            });
        }