예제 #1
0
        public void GetSessionTest()
        {
            PxSession session = PxSession.Get();

            PersonTest pt = new PersonTest()
            {
                Ad = "Sinan", Soyad = "Oran", Yas = 35
            };

            int    a;
            string b;

            session.Set <PersonTest>("MY_TEST0", pt);


            if (session.Get <int>("MY_TEST1", out a))
            {
                //session'dan başarılı şekilde alındı
            }

            if (session.Get <string>("MY_TEST2", out b))
            {
                //session'dan başarılı şekilde alındı
            }

            session.Set <int>("MY_TEST1", 100);
            session.Set <string>("MY_TEST2", "sinan oran");
        }
예제 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            if (!log4net.ThreadContext.Properties.GetKeys().Contains("UserId"))
            {
                log4net.ThreadContext.Properties["UserId"] = PxSession.Get().Principal.UserId;
            }
            if (!log4net.ThreadContext.Properties.GetKeys().Contains("SessionKey"))
            {
                log4net.ThreadContext.Properties["SessionKey"] = PxSession.Get().Principal.Authentication.Token;
            }

            var message = formatter(state, exception);

            switch (logLevel)
            {
            case LogLevel.Trace:
            case LogLevel.Debug:
                _logger.Debug(message, exception);
                break;

            case LogLevel.Information:
                _logger.Info(message, exception);
                break;

            case LogLevel.Warning:
                _logger.Warn(message, exception);
                break;

            case LogLevel.Error:
                _logger.Error(message, exception);
                break;

            case LogLevel.Critical:
                _logger.Fatal(message, exception);
                break;

            case LogLevel.None:
                break;

            default:
                _logger.Warn($"Encountered unknown log level {logLevel}, writing out as Info.");
                _logger.Info(message, exception);
                break;
            }
        }
예제 #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
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     logRequest(context);
     if (context.ActionDescriptor.FilterDescriptors.FirstOrDefault(x => x.Filter is Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter) == null)
     {
         string    controller = context.RouteData.Values["controller"].ToString();
         string    action     = context.RouteData.Values["action"].ToString();
         PxSession session    = PxSession.Get();
         if (!session.Principal.Authentication.IsAuthenticated)
         {
             if (context.HttpContext.Request.IsAjaxRequest())
             {
                 context.HttpContext.Response.Headers.Add("REQUIRE_AUTHENTICATION", "1");
                 context.Result = new JsonResult(null);
             }
             else
             {
                 context.Result = new RedirectToActionResult("Login", "Account", null);
             }
         }
         else if (PxConfigurationManager.PxConfig.Authentication.MultiFA.Enabled &&
                  !session.Principal.Authentication.IsMFAAuthenticationCompleted &&
                  controller != "Account" && action != "TwoFA")
         {
             if (context.HttpContext.Request.IsAjaxRequest())
             {
                 context.HttpContext.Response.Headers.Add("REQUIRE_TWOFA_AUTHENTICATION", "1");
                 context.Result = new JsonResult(null);
             }
             else
             {
                 context.Result = new RedirectToActionResult("TwoFA", "Account", null);
             }
         }
         else if (session.Principal.Authentication.IsPasswordMustChanged && controller != "Account" && action != "ChangePassword")
         {
             if (context.HttpContext.Request.IsAjaxRequest())
             {
                 context.HttpContext.Response.Headers.Add("REQUIRE_CHANGE_PASSWORD", "1");
                 context.Result = new JsonResult(null);
             }
             else
             {
                 context.Result = new RedirectToActionResult("ChangePassword", "Account", null);
             }
         }
     }
 }
예제 #5
0
        /// <summary>
        /// Eğer gönderilen parametrede Text propertysine değer atanmamış ise gönderilen textlength parametresine göre random string oluşturur.
        /// Default textLength 8 karakterdir. Session'a CaptchaImageText adında yeni bir key oluşturup, oluşturduğu string değeri bu keye set eder.
        /// Geriye Image'in base64 stringi dönmektedir. Örnek : "data:image/png;base64, ........."
        /// </summary>
        /// <param name="textLength"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="fontFamily"></param>
        /// <returns></returns>
        public static string CreateCaptcha(PxCaptchaInfo info, int textLength = 8)
        {
            if (string.IsNullOrEmpty(info.Text))
            {
                info.Text = generateRandomCode(textLength);
            }
            byte[] image = null;
            using (CaptchaImage img = new CaptchaImage(info)) {
                ImageConverter converter = new ImageConverter();
                image = (byte[])converter.ConvertTo(img.Image, typeof(byte[]));
            }
            PxSession session = PxSession.Get();

            session.Set <string>("CaptchaImageText", info.Text);
            return(string.Format("data:image/png;base64,{0}", Convert.ToBase64String(image)));
        }
예제 #6
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);
        }
예제 #7
0
 public static string Get(string code)
 {
     return(Get(code, PxSession.Get().Principal.CultureCode));
 }
예제 #8
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;
            }
        }
예제 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            try {
                var       entities = ChangeTracker.Entries <EntityBase>();
                DateTime  originalModifyTimeStamp;
                PxSession session = PxSession.Get();
                foreach (var entity in entities)
                {
                    switch (entity.State)
                    {
                    case EntityState.Added:
                        entity.Entity.CreateDate      = DateTime.Now;
                        entity.Entity.CreateUserIp    = session.Client.IPAddress;
                        entity.Entity.CreateUserId    = session.Principal.UserId;
                        entity.Entity.ModifyTimeStamp = DateTime.Now;
                        break;

                    case EntityState.Detached:
                    case EntityState.Deleted:
                        originalModifyTimeStamp = entity.GetDatabaseValues().GetValue <DateTime>("ModifyTimeStamp");
                        if (originalModifyTimeStamp != entity.Entity.ModifyTimeStamp)
                        {
                            throw new DbUpdateConcurrencyException("Could not be saved successfully. Record may have been changed or canceled.");
                        }
                        entity.State                  = EntityState.Modified;
                        entity.Entity.CancelDate      = DateTime.Now;
                        entity.Entity.CancelUserIp    = session.Client.IPAddress;
                        entity.Entity.CancelUserId    = session.Principal.UserId;
                        entity.Entity.ModifyTimeStamp = DateTime.Now;
                        break;

                    case EntityState.Modified:
                        originalModifyTimeStamp = entity.GetDatabaseValues().GetValue <DateTime>("ModifyTimeStamp");
                        if (originalModifyTimeStamp != entity.Entity.ModifyTimeStamp)
                        {
                            throw new DbUpdateConcurrencyException("Could not be saved successfully. Record may have been changed or canceled.");
                        }
                        entity.Entity.ModifyTimeStamp = DateTime.Now;
                        break;

                    case EntityState.Unchanged:
                    default:
                        break;
                    }
                }
                return(base.SaveChanges());
            }
            catch (DbEntityValidationException e) {
                StringBuilder errorBuilder = new StringBuilder();
                foreach (var eve in e.EntityValidationErrors)
                {
                    errorBuilder.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        errorBuilder.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                    errorBuilder.AppendLine();
                }
                throw new PxException(DalErrorCodes.DbEntityValidationException, Common.Enums.ErrorPriority.High, errorBuilder.ToString());
            }
        }
예제 #10
0
        public void PropertyChangeTest()
        {
            PxSession x = PxSession.Get();

            x.Principal.CultureCode = "en-GB";
        }