Exemplo n.º 1
0
        public static UserEntity UpdateTicket(string device, ref string ticket)
        {
            using (AuthLogic.Disable())
                using (var tr = new Transaction())
                {
                    var pair = UserTicketEntity.ParseTicket(ticket);

                    UserEntity user = Database.Retrieve <UserEntity>(pair.userId);
                    CleanExpiredTickets(user);

                    UserTicketEntity?userTicket = user.UserTickets().SingleOrDefaultEx(t => t.Ticket == pair.ticket);
                    if (userTicket == null)
                    {
                        throw new UnauthorizedAccessException("User attempted to log-in with an invalid ticket");
                    }

                    UserTicketEntity result = new UserTicketEntity
                    {
                        User           = user.ToLite(),
                        Device         = device,
                        ConnectionDate = TimeZoneManager.Now,
                        Ticket         = Guid.NewGuid().ToString(),
                    }.Save();

                    ticket = result.StringTicket();

                    return(tr.Commit(user));
                }
        }
Exemplo n.º 2
0
        public static ResetPasswordRequestEntity SendResetPasswordRequestEmail(string email)
        {
            UserEntity?user;

            using (AuthLogic.Disable())
            {
                user = Database
                       .Query <UserEntity>()
                       .SingleOrDefault(u => u.Email == email && u.State != UserState.Disabled);

                if (user == null)
                {
                    throw new ApplicationException(AuthEmailMessage.EmailNotFound.NiceToString());
                }
            }

            try
            {
                var request = ResetPasswordRequest(user);

                string url = EmailLogic.Configuration.UrlLeft + @"/auth/ResetPassword?code={0}".FormatWith(request.Code);

                using (AuthLogic.Disable())
                    new ResetPasswordRequestEmail(request, url).SendMail();

                return(request);
            }
            catch (Exception ex)
            {
                ex.LogException();
                throw new ApplicationException(LoginAuthMessage.AnErrorOccurredRequestNotProcessed.NiceToString());
            }
        }
Exemplo n.º 3
0
        public static void ChangePassword(Lite <UserEntity> user, byte[] passwordHash, byte[] newPasswordHash)
        {
            var userEntity = user.RetrieveAndForget();

            userEntity.PasswordHash = newPasswordHash;
            using (AuthLogic.Disable())
                userEntity.Execute(UserOperation.Save);
        }
Exemplo n.º 4
0
 static void UserTicketLogic_Saving(UserEntity user)
 {
     if (!user.IsNew && user.IsGraphModified && !user.InDB(u => u.PasswordHash).SequenceEqual(user.PasswordHash))
     {
         using (AuthLogic.Disable())
             user.UserTickets().UnsafeDelete();
     }
 }
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <ResetPasswordRequestEntity>()
                .WithQuery(() => e => new
                {
                    Entity = e,
                    e.Id,
                    e.RequestDate,
                    e.Code,
                    e.User,
                    e.User.Email
                });

                EmailLogic.AssertStarted(sb);

                EmailModelLogic.RegisterEmailModel <ResetPasswordRequestEmail>(() => new EmailTemplateEntity
                {
                    DisableAuthorization = true,
                    Messages             = CultureInfoLogic.ForEachCulture(culture => new EmailTemplateMessageEmbedded(culture)
                    {
                        Text = "<p>{0}</p>".FormatWith(AuthEmailMessage.YouRecentlyRequestedANewPassword.NiceToString()) +
                               "<p>{0} @[User.UserName]</p>".FormatWith(AuthEmailMessage.YourUsernameIs.NiceToString()) +
                               "<p>{0}</p>".FormatWith(AuthEmailMessage.YouCanResetYourPasswordByFollowingTheLinkBelow.NiceToString()) +
                               "<p><a href=\"@[m:Url]\">@[m:Url]</a></p>",
                        Subject = AuthEmailMessage.ResetPasswordRequestSubject.NiceToString()
                    }).ToMList()
                });



                new Graph <ResetPasswordRequestEntity> .Execute(ResetPasswordRequestOperation.Execute)
                {
                    CanBeNew      = false,
                    CanBeModified = false,
                    CanExecute    = (e) => e.Lapsed == false ? null : AuthEmailMessage.YourResetPasswordRequestHasExpired.NiceToString(),
                    Execute       = (e, args) =>
                    {
                        string password = args.GetArg <string>();
                        e.Lapsed = true;
                        var user = e.User;

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

                        user.PasswordHash = Security.EncodePassword(password);
                        using (AuthLogic.Disable())
                            user.Execute(UserOperation.Save);
                    }
                }

                .Register();
            }
        }
Exemplo n.º 6
0
        public static UserEntity ChangePasswordLogin(string username, byte[] passwordHash, byte[] newPasswordHash)
        {
            var userEntity = RetrieveUser(username, passwordHash);

            userEntity.PasswordHash = newPasswordHash;
            using (AuthLogic.Disable())
                userEntity.Execute(UserOperation.Save);

            return(Login(username, newPasswordHash));
        }
Exemplo n.º 7
0
        public static UserEntity Login(string username, byte[] passwordHash)
        {
            using (AuthLogic.Disable())
            {
                UserEntity user = RetrieveUser(username, passwordHash);

                OnUserLogingIn(user);

                return(user);
            }
        }
Exemplo n.º 8
0
        public static UserEntity RetrieveUser(string username, byte[] passwordHash)
        {
            using (AuthLogic.Disable())
            {
                UserEntity?user = RetrieveUser(username);
                if (user == null)
                {
                    throw new IncorrectUsernameException(LoginAuthMessage.Username0IsNotValid.NiceToString().FormatWith(username));
                }


                if (user.PasswordHash == null || !user.PasswordHash.SequenceEqual(passwordHash))
                {
                    using (UserHolder.UserSession(SystemUser !))
                    {
                        user.LoginFailedCounter++;
                        user.Execute(UserOperation.Save);

                        if (MaxFailedLoginAttempts.HasValue &&
                            user.LoginFailedCounter == MaxFailedLoginAttempts &&
                            user.State == UserState.Active)
                        {
                            var config  = EmailLogic.Configuration;
                            var request = ResetPasswordRequestLogic.ResetPasswordRequest(user);
                            var url     = $"{config.UrlLeft}/auth/resetPassword?code={request.Code}";

                            var mail = new UserLockedMail(user, url);
                            mail.SendMailAsync();

                            user.Execute(UserOperation.Deactivate);

                            throw new UserLockedException(LoginAuthMessage.User0IsDisabled.NiceToString()
                                                          .FormatWith(user.UserName));
                        }

                        throw new IncorrectPasswordException(LoginAuthMessage.IncorrectPassword.NiceToString());
                    }
                }

                if (user.LoginFailedCounter > 0)
                {
                    using (UserHolder.UserSession(SystemUser !))
                    {
                        user.LoginFailedCounter = 0;
                        user.Execute(UserOperation.Save);
                    }
                }


                return(user);
            }
        }
Exemplo n.º 9
0
        public static UserEntity Login(string username, byte[] passwordHash, out string authenticationType)
        {
            using (AuthLogic.Disable())
            {
                UserEntity user = RetrieveUser(username, passwordHash);

                OnUserLogingIn(user);

                authenticationType = "database";

                return(user);
            }
        }
Exemplo n.º 10
0
        public static ResetPasswordRequestEntity ResetPasswordRequestExecute(string code, string password)
        {
            using (AuthLogic.Disable())
            {
                var rpr = Database.Query <ResetPasswordRequestEntity>()
                          .Where(r => r.Code == code && r.IsValid)
                          .SingleEx();

                using (UserHolder.UserSession(rpr.User))
                {
                    rpr.Execute(ResetPasswordRequestOperation.Execute, password);
                }
                return(rpr);
            }
        }
Exemplo n.º 11
0
        public static IDisposable UnsafeUserSession(string username)
        {
            UserEntity?user;

            using (AuthLogic.Disable())
            {
                user = RetrieveUser(username);
                if (user == null)
                {
                    throw new ApplicationException(AuthMessage.Username0IsNotValid.NiceToString().FormatWith(username));
                }
            }

            return(UserHolder.UserSession(user));
        }
Exemplo n.º 12
0
        public static ResetPasswordRequestEntity ResetPasswordRequestExecute(string code, string password)
        {
            using (AuthLogic.Disable())
            {
                //Remove old previous requests
                var rpr = Database.Query <ResetPasswordRequestEntity>()
                          .Where(r => r.Code == code && !r.Lapsed)
                          .SingleOrDefault();

                using (UserHolder.UserSession(rpr.User))
                {
                    rpr.Execute(ResetPasswordRequestOperation.Execute, password);
                }
                return(rpr);
            }
        }
Exemplo n.º 13
0
 public static void SessionStart(string userHostAddress, string userAgent)
 {
     var user = UserEntity.Current;
     if (SessionLogLogic.RoleTracked(user.Role))
     {
         using (AuthLogic.Disable())
         {
             new SessionLogEntity
             {
                 User = user.ToLite(),
                 SessionStart = TimeZoneManager.Now.TrimToSeconds(),
                 UserHostAddress = userHostAddress,
                 UserAgent = userAgent
             }.Save();
         }
     }
 }
Exemplo n.º 14
0
        public static UserEntity?TryRetrieveUser(string username, byte[] passwordHash)
        {
            using (AuthLogic.Disable())
            {
                UserEntity?user = RetrieveUser(username);
                if (user == null)
                {
                    return(null);
                }

                if (!user.PasswordHash.SequenceEqual(passwordHash))
                {
                    return(null);
                }

                return(user);
            }
        }
Exemplo n.º 15
0
        public static UserEntity RetrieveUser(string username, byte[] passwordHash)
        {
            using (AuthLogic.Disable())
            {
                UserEntity?user = RetrieveUser(username);
                if (user == null)
                {
                    throw new IncorrectUsernameException(AuthMessage.Username0IsNotValid.NiceToString().FormatWith(username));
                }

                if (!user.PasswordHash.SequenceEqual(passwordHash))
                {
                    throw new IncorrectPasswordException(AuthMessage.IncorrectPassword.NiceToString());
                }

                return(user);
            }
        }
Exemplo n.º 16
0
        public static ResetPasswordRequestEntity ResetPasswordRequest(UserEntity user)
        {
            using (AuthLogic.Disable())
            {
                //Remove old previous requests
                Database.Query <ResetPasswordRequestEntity>()
                .Where(r => r.User.Is(user) && r.RequestDate < TimeZoneManager.Now.AddMonths(1))
                .UnsafeUpdate()
                .Set(e => e.Lapsed, e => true)
                .Execute();

                return(new ResetPasswordRequestEntity()
                {
                    Code = MyRandom.Current.NextString(5),
                    User = user,
                    RequestDate = TimeZoneManager.Now,
                }.Save());
            }
        }
Exemplo n.º 17
0
        public static UserEntity CreateUserFromAD(ActiveDirectoryUser adUser)
        {
            ClientCredentialProvider authProvider = GetClientCredentialProvider();
            GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);
            var msGraphUser = graphClient.Users[adUser.ObjectID.ToString()].Request().GetAsync().Result;

            using (ExecutionMode.Global())
            {
                var user = Database.Query <UserEntity>().SingleOrDefaultEx(a => a.Mixin <UserOIDMixin>().OID == Guid.Parse(msGraphUser.Id));
                if (user != null)
                {
                    return(user);
                }

                var config = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer !).GetConfig();

                user = Database.Query <UserEntity>().SingleOrDefault(a => a.UserName == msGraphUser.UserPrincipalName) ??
                       (msGraphUser.UserPrincipalName.Contains("@") && config.AllowMatchUsersBySimpleUserName ? Database.Query <UserEntity>().SingleOrDefault(a => a.Email == msGraphUser.UserPrincipalName || a.UserName == msGraphUser.UserPrincipalName.Before("@")) : null);

                if (user != null)
                {
                    using (AuthLogic.Disable())
                        using (OperationLogic.AllowSave <UserEntity>())
                        {
                            user.Mixin <UserOIDMixin>().OID = Guid.Parse(msGraphUser.Id);
                            user.UserName = msGraphUser.UserPrincipalName;
                            user.Email    = msGraphUser.UserPrincipalName;
                            if (!UserOIDMixin.AllowUsersWithPassswordAndOID)
                            {
                                user.PasswordHash = null;
                            }
                            user.Save();
                        }

                    return(user);
                }
            }

            var result = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer !).OnAutoCreateUser(new MicrosoftGraphCreateUserContext(msGraphUser));

            return(result ?? throw new InvalidOperationException(ReflectionTools.GetPropertyInfo((ActiveDirectoryConfigurationEmbedded e) => e.AutoCreateUsers).NiceName() + " is not activated"));
        }
Exemplo n.º 18
0
        public static string NewTicket(string device)
        {
            using (AuthLogic.Disable())
                using (var tr = new Transaction())
                {
                    CleanExpiredTickets(UserEntity.Current);

                    UserTicketEntity result = new UserTicketEntity
                    {
                        User           = UserEntity.Current.ToLite(),
                        Device         = device,
                        ConnectionDate = TimeZoneManager.Now,
                        Ticket         = Guid.NewGuid().ToString(),
                    };

                    result.Save();

                    return(tr.Commit(result.StringTicket()));
                }
        }
Exemplo n.º 19
0
        public static void SessionEnd(UserEntity user, TimeSpan? timeOut)
        {
            if (user == null || !RoleTracked(user.Role))
                return;

            using (AuthLogic.Disable())
            {
                var sessionEnd = timeOut.HasValue ? TimeZoneManager.Now.Subtract(timeOut.Value).TrimToSeconds() : TimeZoneManager.Now.TrimToSeconds();

                var rows = Database.Query<SessionLogEntity>()
                    .Where(sl => sl.User.RefersTo(user))
                    .OrderByDescending(sl => sl.SessionStart)
                    .Take(1)
                    .Where(sl => sl.SessionEnd == null)
                    .UnsafeUpdate()
                    .Set(a => a.SessionEnd, a => sessionEnd)
                    .Set(a => a.SessionTimeOut, a => timeOut.HasValue)
                    .Execute();
            }
        }
Exemplo n.º 20
0
        public static ResetPasswordRequestEntity ResetPasswordRequest(UserEntity user)
        {
            using (OperationLogic.AllowSave <UserEntity>())
                using (AuthLogic.Disable())
                {
                    //Remove old previous requests
                    Database.Query <ResetPasswordRequestEntity>()
                    .Where(r => r.User.Is(user) && r.IsValid)
                    .UnsafeUpdate()
                    .Set(e => e.Used, e => true)
                    .Execute();

                    return(new ResetPasswordRequestEntity
                    {
                        Code = MyRandom.Current.NextString(32),
                        User = user,
                        RequestDate = TimeZoneManager.Now,
                    }.Save());
                }
        }
Exemplo n.º 21
0
        static DirectedGraph <Lite <RoleEntity> > CacheRoles()
        {
            using (AuthLogic.Disable())
            {
                DirectedGraph <Lite <RoleEntity> > newRoles = new DirectedGraph <Lite <RoleEntity> >();

                using (new EntityCache(EntityCacheType.ForceNewSealed))
                    foreach (var role in Database.RetrieveAll <RoleEntity>())
                    {
                        newRoles.Expand(role.ToLite(), r => r.RetrieveAndRemember().Roles);
                    }

                var problems = newRoles.FeedbackEdgeSet().Edges.ToList();

                if (problems.Count > 0)
                {
                    throw new ApplicationException(
                              AuthMessage._0CyclesHaveBeenFoundInTheGraphOfRolesDueToTheRelationships.NiceToString().FormatWith(problems.Count) +
                              problems.ToString("\r\n"));
                }

                return(newRoles);
            }
        }
Exemplo n.º 22
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                sb.Include <PasswordExpiresIntervalEntity>()
                .WithSave(PasswordExpiresIntervalOperation.Save)
                .WithQuery(dqm, () => e => new
                {
                    Entity = e,
                    e.Id,
                    e.Enabled,
                    e.Days,
                    e.DaysWarning
                });

                AuthLogic.UserLogingIn += (u =>
                {
                    if (u.PasswordNeverExpires)
                    {
                        return;
                    }

                    var ivp = Database.Query <PasswordExpiresIntervalEntity>().Where(p => p.Enabled).FirstOrDefault();
                    if (ivp == null)
                    {
                        return;
                    }

                    if (TimeZoneManager.Now > u.PasswordSetDate.AddDays((double)ivp.Days))
                    {
                        throw new PasswordExpiredException(AuthMessage.ExpiredPassword.NiceToString());
                    }
                });

                AuthLogic.LoginMessage += (() =>
                {
                    UserEntity u = UserEntity.Current;

                    if (u.PasswordNeverExpires)
                    {
                        return(null);
                    }

                    PasswordExpiresIntervalEntity ivp = null;
                    using (AuthLogic.Disable())
                        ivp = Database.Query <PasswordExpiresIntervalEntity>().Where(p => p.Enabled).FirstOrDefault();

                    if (ivp == null)
                    {
                        return(null);
                    }

                    if (TimeZoneManager.Now > u.PasswordSetDate.AddDays((double)ivp.Days).AddDays((double)-ivp.DaysWarning))
                    {
                        return(AuthMessage.YourPasswordIsNearExpiration.NiceToString());
                    }

                    return(null);
                });
            }
        }