public void Logout() { PxSession session = PxSession.Current; session.Abandon(); session.Save(); }
public void Login(string pUserName, string pPassword, bool pMFAEnabled) { /* MFA Enabled durumda Login işlemi sırasında sadece Authentication yapılır, authorization yapılmaz * MFA disabled ise Login işlemi sırasnda hem Authentication hem Authorization gerçekleştirilir */ try { PxSession session = PxSession.Current; PxPrincipalInfo principalInfo; PxCredentialInfo credentials = new PxCredentialInfo(); //TODO: pUserName ve pPassword geldiği haliyle kullanılmamalı! Validate edilmeli credentials.UserName = pUserName; credentials.Password = pPassword; principalInfo = this.Authentication.Login(credentials); if (!pMFAEnabled) { principalInfo.Authorization = this.Authorization.Authorize(principalInfo.UserId); } session.Principal = principalInfo; session.Save(); } catch (Exception ex) { Logging.Loggers.PxErrorLogger.Log(ex); throw; } }
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"); }
private void authorizeAndGetMenu(PxSession pSession) { if (pSession == null || pSession.Principal == null) { return; } PxAuthorization authEngine = new PxAuthorization(); pSession.Principal.Authorization = authEngine.Authorize(pSession.Principal.UserId); pSession.Menu = authEngine.GetMenu(pSession.Principal.UserId); }
/// <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; } }
/// <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); }
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); } } } }
/// <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))); }
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(); } } }
/// <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); }
public static string Get(string code) { return(Get(code, PxSession.Get().Principal.CultureCode)); }
/// <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; } }
/// <summary> /// ConfigureServices'de eklenen servisleri configure eder. /// Error sayfası için Error Controller'daki Index actionı kullanılmaktadır. /// Error StatusCode'lar için "/Error/Status/{0}" yapısı kullanılmaktadır. /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="loggerFactory"></param> public static void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } if (env.IsDevelopment()) { loggerFactory.AddConsole() .AddDebug(); } app.UseStatusCodePagesWithReExecute("/Error/Status/{0}"); //PxWebMemoryCacheManager.Instance.MemoryCache = app.ApplicationServices.GetService<IMemoryCache>(); PxRazorViewToStringRenderer.Configure(app.ApplicationServices.GetRequiredService <PxRazorViewToStringRenderer>()); PxHttpContext.Configure(app.ApplicationServices.GetRequiredService <Microsoft.AspNetCore.Http.IHttpContextAccessor>()); /* Session kullanımı için gerekli */ app.UseSession(new SessionOptions() { CookieHttpOnly = true, IdleTimeout = TimeSpan.FromMinutes(PxConfigurationManager.PxConfig.Session.DefaultTimeoutDuration) }); /* Biz session üzerinde kullanıcı IP bilgisini veriyoruz. Load Balancer'lar arkasında bulunan bir sunucuda client IP bilgisini alabilmek için * Forwarded Header'lara bakmak gerekiyor */ app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); if (PxConfigurationManager.PxConfig.UseCompression) { app.UseCompression(); } IPxSessionStore iPxContextStore = app.ApplicationServices.GetService <IPxSessionStore>(); IPxClientInfoHelper iPxClientInfoHelper = app.ApplicationServices.GetService <IPxClientInfoHelper>(); PxSession.Initilize(iPxContextStore, iPxClientInfoHelper); app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = context => { // Cache static file for 1 year if (!string.IsNullOrEmpty(context.Context.Request.Query["v"])) { context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" }); context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddDays(1).ToString("R") }); } } }); CultureInfo culture = new CultureInfo("tr-TR"); culture.NumberFormat.NumberDecimalSeparator = "."; culture.NumberFormat.NumberGroupSeparator = ","; culture.NumberFormat.CurrencyDecimalSeparator = "."; culture.NumberFormat.CurrencyGroupSeparator = ","; CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(culture), SupportedCultures = new List <CultureInfo> { culture }, SupportedUICultures = new List <CultureInfo> { culture } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); PxLocalizationManager.Initialize(); if (PxConfigurationManager.PxConfig.Schedule.Enabled) { PxTaskScheduler.Instance.Start(); } }
/// <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()); } }
public void PropertyChangeTest() { PxSession x = PxSession.Get(); x.Principal.CultureCode = "en-GB"; }