Пример #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 public void Execute(IJobExecutionContext context)
 {
     try {
         _task = (ScheduledTask)context.MergedJobDataMap["ScheduledTask"];
         DateTime planingTime = context.ScheduledFireTimeUtc.HasValue ? context.ScheduledFireTimeUtc.Value.LocalDateTime : DateTime.Now;
         planingTime = new DateTime(planingTime.Ticks - (planingTime.Ticks % TimeSpan.TicksPerMinute), planingTime.Kind);
         if (_task.OnlyWorkingDays)
         {
             if (HolidayCalculator.Instance.IsHoliday(planingTime, _task.RunAtHalfPublicHoliday))
             {
                 return;
             }
         }
         _action = Toolkit.Instance.CreateInstance <IPxTaskAction>(_task.Action);
         using (PeakDbContext dbContext = new PeakDbContext()) {
             if (dbContext.ScheduledTaskLogs.FirstOrDefault(x => x.ScheduledTaskId == _task.Id && x.ScheduledTime == planingTime) != null)
             {
                 return;
             }
             ScheduledTaskLog taskLog = new ScheduledTaskLog()
             {
                 ScheduledTaskId = _task.Id,
                 State           = Dal.Enums.ScheduleState.Running,
                 ScheduledTime   = planingTime,
                 StartTime       = DateTime.Now
             };
             dbContext.ScheduledTaskLogs.Add(taskLog);
             dbContext.SaveChanges();
             bool succeed = executeAction(planingTime, 0);
             taskLog.EndTime = DateTime.Now;
             if (succeed)
             {
                 taskLog.State = Dal.Enums.ScheduleState.Succeed;
             }
             else
             {
                 taskLog.State = Dal.Enums.ScheduleState.Failed;
                 if (_lastError != null)
                 {
                     taskLog.ErrorMessage = _lastError.Message;
                     taskLog.ErrorDetail  = _lastError.ToString();
                     _lastError           = null;
                 }
             }
             dbContext.SaveChanges();
         }
     }
     catch (Exception ex) {
         PxErrorLogger.Log(ex);
     }
 }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="principleInfo"></param>
        /// <param name="verificationCode"></param>
        public void CheckMFACode(PxPrincipalInfo principleInfo, string verificationCode)
        {
            using (PeakDbContext dbContext = new PeakDbContext()) {
                MFAMessage mfa = dbContext.MFAMessages.FirstOrDefault(x => x.RereferenceCode == principleInfo.Authentication.MFAReferenceCode && x.UserId == principleInfo.UserId && !x.IsUsed);
                if (mfa == null)
                {
                    throw AuthExceptions.InvalidMFAReferenceNo();
                }
                User usr = dbContext.Users.FirstOrDefault(x => x.Id == principleInfo.UserId);
                if (usr.PasswordState == PasswordState.Blocked)
                {
                    throw AuthExceptions.MFAUserBlocked();
                }

                if (DateTime.Now > mfa.Date.AddMinutes(PxConfigurationManager.PxConfig.Authentication.MultiFA.CodeValidDuration))
                {
                    throw AuthExceptions.MFACodeExpired();
                }

                string encryptedVerificationCode = encryptVerificationCode(verificationCode, principleInfo.PhoneNumber);
                if (!string.Equals(encryptedVerificationCode, mfa.VerificationCode))
                {
                    usr.MFATryCount++;
                    if (usr.MFATryCount >= PxConfigurationManager.PxConfig.Authentication.Policy.MaxFailedMFAAttemptCount)
                    {
                        usr.MFATryCount   = 0;
                        usr.PasswordState = PasswordState.Blocked;
                        dbContext.SaveChanges();
                        throw AuthExceptions.MFAUserBlocked();
                    }
                    dbContext.SaveChanges();
                    throw AuthExceptions.MFAAuthenticationFailed();
                }
                usr.MFATryCount = 0;
                dbContext.SaveChanges();
            }
            principleInfo.Authentication.IsMFAAuthenticationCompleted = true;
            PxSession session = PxSession.Get();

            session.Principal = principleInfo;
            PxSession.Save(session);
        }
Пример #3
0
        /// <summary>
        /// Çoklu doğrulama için gönderilecek mesajdır. Msg'da string format için {0} ifadesi yer almalıdır.
        /// </summary>
        /// <param name="principleInfo"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public void SendMFACode(PxPrincipalInfo principleInfo, string msg)
        {
            FesMultiFAParameter parameter = JsonConvert.DeserializeObject <FesMultiFAParameter>(PxConfigurationManager.PxConfig.Authentication.MultiFA.Parameter);

            if (parameter == null)
            {
                throw AuthExceptions.MFAParameterNotFound();
            }
            if (principleInfo == null)
            {
                throw AuthExceptions.PrincipleInfoNotFound();
            }
            if (string.IsNullOrEmpty(msg))
            {
                msg = PxConfigurationManager.PxConfig.Authentication.MultiFA.Message;
            }
            string refNo                     = generateReferenceNo(principleInfo.UserId);
            string verificationCode          = Toolkit.Instance.GenerateRandomNumber(6).ToString();
            string encryptedVerificationCode = encryptVerificationCode(verificationCode, principleInfo.PhoneNumber);
            string message                   = string.Format(msg, string.Format("#{0}#", encryptedVerificationCode));
            MFAWebServiceResult result       = null;

            using (MFAWebServicesClient svcClient = new MFAWebServicesClient(MFAWebServicesClient.EndpointConfiguration.MFAWebServicesSoapHttpPort, new System.ServiceModel.EndpointAddress(parameter.FesServiceUrl))) {
                result = svcClient.MFAWebSrvAsync(parameter.FesUser, parameter.FesUserPassword, parameter.FesServiceId, parameter.FesEnvironment, prepareInputXmlForFes(message, parameter.FesProjectId, principleInfo.PhoneNumber)).Result;
            }
            using (PeakDbContext dbContext = new PeakDbContext()) {
                MFAMessage mfa = new MFAMessage()
                {
                    Date             = DateTime.Now,
                    IsUsed           = false,
                    PhoneNumber      = principleInfo.PhoneNumber,
                    UserId           = principleInfo.UserId,
                    RereferenceCode  = refNo,
                    VerificationCode = encryptedVerificationCode
                };
                dbContext.MFAMessages.Add(mfa);
                dbContext.SaveChanges();
            }

            if (result.errorCode != "0")
            {
                throw new PxUnexpectedErrorException(new Exception(result.errorMsg));
            }
            principleInfo.Authentication.MFAReferenceCode = refNo;
            PxSession session = PxSession.Get();

            session.Principal = principleInfo;
            PxSession.Save(session);
        }
Пример #4
0
 /// <summary>
 ///
 /// </summary>
 public void Logout()
 {
     using (TransactionScope trn = new TransactionScope()) {
         using (PeakDbContext dbContext = new PeakDbContext()) {
             ActiveSession     activeSession      = dbContext.ActiveSessions.FirstOrDefault(x => x.SessionKey == PxSession.Current.Principal.Authentication.Token);
             TerminatedSession sessionToTerminate = new TerminatedSession(activeSession);
             sessionToTerminate.TerminationType = SessionTerminationType.Logout;
             sessionToTerminate.TerminationDate = DateTime.Now;
             dbContext.ActiveSessions.Remove(activeSession);
             dbContext.TerminatedSessions.Add(sessionToTerminate);
             dbContext.SaveChanges();
         }
         trn.Complete();
     }
 }
Пример #5
0
 public static void UpdateUser()
 {
     using (PeakDbContext dbContext = new PeakDbContext()) {
         User user = dbContext.Users.FirstOrDefault(x => x.Id == 2);
         user.Code         = "p12314";
         user.CultureCode  = "en-US";
         user.Email        = "*****@*****.**";
         user.Name         = "Ali";
         user.PasswordSalt = Toolkit.Instance.Security.GetSecureSalt();
         user.Password     = Toolkit.Instance.Security.GetSecureHash("1234", user.PasswordSalt, Encoding.UTF8, Peak.Common.Enums.HashFormat.Base64);
         user.PhoneNumber  = "5555555555";
         user.Surname      = "Veli";
         dbContext.SaveChanges();
     }
 }
Пример #6
0
        public void ChangeOwnPassword(PxPasswordChangeInfo info)
        {
            if (PxSession.Current.Principal.UserId != info.UserId)
            {
                throw AuthExceptions.TryToChangeOrhersPassword();
            }

            if (string.IsNullOrEmpty(info.New) || !Regex.IsMatch(info.New, PxConfigurationManager.PxConfig.Authentication.Policy.Regex))
            {
                throw AuthExceptions.PasswordRegexNotMatch();
            }
            using (PeakDbContext dbContext = new PeakDbContext()) {
                User usr = dbContext.Users.FirstOrDefault(x => x.Id == info.UserId);
                if (usr == null)
                {
                    throw AuthExceptions.InvalidUserNameOrPassword();
                }
                string encryptedOldPassword = Toolkit.Instance.Security.GetSecureHash(info.Old, usr.PasswordSalt, Encoding.UTF8, HashFormat.Base64);
                string encryptedNewPassword = Toolkit.Instance.Security.GetSecureHash(info.New, usr.PasswordSalt, Encoding.UTF8, HashFormat.Base64);
                if (encryptedOldPassword != usr.Password)
                {
                    throw AuthExceptions.InvalidUserNameOrPassword();
                }
                int passwordHistoryCheckFlag = dbContext.PasswordHistories.Where(x => x.UserId == info.UserId).OrderByDescending(x => x.Date).Take(PxConfigurationManager.PxConfig.Authentication.Policy.LastUsedPasswordsRestriction)
                                               .Union(dbContext.PasswordHistories.Where(y => y.UserId == info.UserId && y.Date > (DateTime.Now.AddDays(-PxConfigurationManager.PxConfig.Authentication.Policy.OldPasswordReusabilityPeriod))))
                                               .Where(z => z.Password == encryptedNewPassword).Count();
                if (passwordHistoryCheckFlag > 0)
                {
                    throw AuthExceptions.LastUsedPasswords(PxConfigurationManager.PxConfig.Authentication.Policy.LastUsedPasswordsRestriction, PxConfigurationManager.PxConfig.Authentication.Policy.OldPasswordReusabilityPeriod);
                }
                usr.IsPwdMustChange    = false;
                usr.PasswordChangeDate = DateTime.Today;
                usr.Password           = encryptedNewPassword;
                PxSession session = PxSession.Current;
                session.Principal.Authentication.IsPasswordMustChanged = false;
                session.Save();
                PasswordHistory history = new PasswordHistory();
                history.Date     = DateTime.Now;
                history.Password = encryptedNewPassword;
                history.UserId   = info.UserId;
                using (TransactionScope trn = new TransactionScope()) {
                    dbContext.SaveChanges();
                    trn.Complete();
                }
            }
        }
Пример #7
0
        public static void AddUser()
        {
            User user = new User();

            user.Code         = "p18928";
            user.CultureCode  = "tr-TR";
            user.Email        = "*****@*****.**";
            user.Name         = "Sinan";
            user.PasswordSalt = Toolkit.Instance.Security.GetSecureSalt();
            user.Password     = Toolkit.Instance.Security.GetSecureHash("123456", user.PasswordSalt, Encoding.UTF8, Peak.Common.Enums.HashFormat.Base64);
            user.PhoneNumber  = "5555555555";
            user.Surname      = "Oran";
            using (PeakDbContext dbContext = new PeakDbContext()) {
                dbContext.Users.Add(user);
                dbContext.SaveChanges();
            }
        }
Пример #8
0
 public void Excecute(DateTime scheduledTime)
 {
     using (PeakDbContext dbContext = new PeakDbContext()) {
         DateTime expiredTime     = DateTime.Now.AddMinutes(-PxConfigurationManager.PxConfig.Session.DefaultExpireDuration);
         var      expiredSessions = dbContext.ActiveSessions.Where(x => x.OpenDate <= expiredTime).ToList();
         dbContext.ActiveSessions.RemoveRange(expiredSessions);
         foreach (var expiredSession in expiredSessions)
         {
             TerminatedSession terminatedSession = new TerminatedSession()
             {
                 Ip               = expiredSession.Ip,
                 OpenDate         = expiredSession.OpenDate,
                 TerminationDate  = DateTime.Now,
                 SessionKey       = expiredSession.SessionKey,
                 TerminationType  = Dal.Enums.SessionTerminationType.Expire,
                 BrowserUserAgent = expiredSession.BrowserUserAgent,
                 UserId           = expiredSession.UserId
             };
             dbContext.TerminatedSessions.Add(terminatedSession);
         }
         dbContext.SaveChanges();
     }
 }
Пример #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="credential"></param>
        public PxPrincipalInfo Login(PxCredentialInfo credential)
        {
            User            user      = null;
            PxPrincipalInfo info      = null;
            PxSession       axSession = PxSession.Get();

            try {
                using (TransactionScope scope = new TransactionScope()) {
                    using (PeakDbContext dbContext = new PeakDbContext()) {
                        user = dbContext.Users.FirstOrDefault(x => x.Code == credential.UserName);
                        if (user == null)
                        {
                            throw AuthExceptions.InvalidUserNameOrPassword();
                        }
                        if (user.PasswordState == PasswordState.Blocked)
                        {
                            throw AuthExceptions.UserHasBeenLocked();
                        }
                        string pwd = Toolkit.Instance.Security.GetSecureHash(credential.Password, user.PasswordSalt, Encoding.UTF8, HashFormat.Base64);
                        if (user.Password != pwd)
                        {
                            user.PasswordTryCount++;

                            if (user.PasswordTryCount > PxConfigurationManager.PxConfig.Authentication.Policy.IncorrectPasswordCount)
                            {
                                user.PasswordState = PasswordState.Blocked;
                            }
                            dbContext.SaveChanges();
                            if (user.PasswordState == PasswordState.Blocked)
                            {
                                throw AuthExceptions.UserHasBeenLocked();
                            }
                            throw AuthExceptions.InvalidUserNameOrPassword();
                        }


                        if (user.CancelDate.HasValue && user.CancelDate <= DateTime.Now)
                        {
                            throw AuthExceptions.InvalidUserNameOrPassword();
                        }

                        // kullanıcı henüz aktive edilmediyse hata at.
                        if (user.StartDate > DateTime.Now)
                        {
                            throw AuthExceptions.UserActivationIsNotStartedYet();
                        }

                        // kullanıcı aktivasyonu sona ermişse hata at.
                        if (user.EndDate.HasValue && user.EndDate < DateTime.Now)
                        {
                            throw AuthExceptions.UserActivationIsEnded();
                        }
                        string sessionKey = Toolkit.Instance.CreateUniqueId();

                        ActiveSession activeSession = new ActiveSession()
                        {
                            Ip               = axSession.Client.IPAddress,
                            OpenDate         = DateTime.Now,
                            SessionKey       = sessionKey,
                            BrowserUserAgent = axSession.Client.BrowserUserAgent,
                            UserId           = user.Id
                        };

                        dbContext.ActiveSessions.Add(activeSession);
                        user.PasswordTryCount = 0;

                        dbContext.SaveChanges();

                        info = new PxPrincipalInfo();
                        info.Authentication.ExpireDate = DateTime.Now.AddMinutes(PxConfigurationManager.PxConfig.Session.DefaultExpireDuration);
                        info.Authentication.Token      = sessionKey;
                        info.Authentication.Timeout    = PxConfigurationManager.PxConfig.Session.DefaultTimeoutDuration;
                        if (!PxConfigurationManager.PxConfig.Authentication.MultiFA.Enabled)
                        {
                            info.Authentication.IsAuthenticated = true;
                        }
                        info.Authentication.IsPasswordMustChanged = user.IsPwdMustChange;
                        info.Authentication.Name = user.Name;

                        info.CultureCode  = user.CultureCode;
                        info.UserName     = user.Code;
                        info.EmailAddress = user.Email;
                        info.UserId       = user.Id;
                        info.ProfileImage = user.Image;
                        info.MiddleName   = user.MiddleName;
                        info.Name         = user.Name;
                        info.PhoneNumber  = user.PhoneNumber;
                        info.Surname      = user.Surname;
                    }

                    scope.Complete();
                }

                axSession.Principal = info;
                this.authorizeAndGetMenu(axSession); //Authorization verisi ve ana menu bilgileri alınıyor
                PxSession.Save(axSession);

                return(info);
            }
            catch {
                //Başarısız oturum denemeleri tablosuna kayıt atılıyor.
                using (PeakDbContext dbContext = new PeakDbContext()) {
                    UnsuccessfulSession unSuccesfulSession = new UnsuccessfulSession()
                    {
                        UserId           = user != null ? user.Id : 0,
                        Ip               = axSession.Client.IPAddress,
                        Date             = DateTime.Now,
                        BrowserUserAgent = axSession.Client.BrowserUserAgent
                    };
                    dbContext.UnsuccessfulSessions.Add(unSuccesfulSession);
                    dbContext.SaveChanges();
                }
                throw;
            }
        }