Exemple #1
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);
        }
Exemple #2
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();
                }
            }
        }
        public static void InitTest()
        {
            try {
                throw AuthExceptions.UserHasBeenClosed("p18928");
            }
            catch (Exception ex) {
                System.Console.WriteLine(ex.Message);
            }

            try {
                throw AuthExceptions.MFAAuthenticationFailed();
            }
            catch (Exception ex) {
                System.Console.WriteLine(ex.Message);
            }

            System.Console.ReadLine();
        }
Exemple #4
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);
        }
Exemple #5
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;
            }
        }