public SC_USER Save(SC_USER obj) { var currentUser = _general.Get <SC_USER>(obj.IdUser); currentUser.Soyadi = obj.Soyadi; currentUser.Adi = obj.Adi; currentUser.CepTelefonu = obj.CepTelefonu; currentUser.Aciklama = obj.Aciklama; currentUser.ModUser = currentUser.IdUser; currentUser = _general.Update(currentUser); _session.Set(Strings.Authorization.UserSessionKey, currentUser); return(currentUser); //if (obj.IdUser > 0) //{ // obj = _general.Update(obj); // _logger.LogSuccess(new Log() // { // ActionName = "Save", // ControllerName = "ProfileController", // RequestUrl = "/Profile", // ShortMessage = Strings.Messages.User.Update(obj) // }); // _sessionProvider.Set(Strings.Authorization.UserSessionKey, obj); // return Json(obj); //} //else //{ // return Json(false); //} }
public async Task SignOut() { var session = await _sessionManager.GetSession(); await _sessionProvider.Clear(); await _httpContextAccessor.HttpContext.SignOutAsync(); // keep essential variables if the user continues to browse around await _sessionProvider.Set(SessionConstants.IsDebug, session.IsDebug); await _sessionProvider.Set(SessionConstants.SessionLogId, session.SessionLogId); // keeps state for the duration of the current request }
public async Task <GetSessionResponse> GetSession() { var response = new GetSessionResponse(); // get or create a new session var session = await _sessionProvider.Get <SessionEntity>(SessionConstants.SessionEntity); if (session == null) { // flush any authenticated cookies in the event the application restarts await _httpContextAccessor.HttpContext.SignOutAsync(); await _sessionProvider.Clear(); var userAgent = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.UserAgent].FirstOrDefault(); using (var uow = _uowFactory.GetUnitOfWork()) { response.SessionEntity = await uow.SessionRepo.CreateSession(new Repositories.DatabaseRepos.SessionRepo.Models.CreateSessionRequest() { User_Agent = userAgent, Created_By = ApplicationConstants.SystemUserId }); uow.Commit(); } await _sessionProvider.Set(SessionConstants.SessionEntity, response.SessionEntity); return(response); } response.SessionEntity = session; var sessionLogId = await _sessionProvider.Get <int?>(SessionConstants.SessionLogId); if (sessionLogId != null) { response.SessionLogId = sessionLogId.Value; } var isDebug = await _sessionProvider.Get <bool?>(SessionConstants.IsDebug); if (isDebug != null) { response.IsDebug = isDebug ?? false; } return(response); }
// GetAll with IdUser public IEnumerable <SC_MENU> GetAll(int idUser) { // Cache olayı IEnumerable <SC_MENU> _menu = null; // Cache Key tanımlanır. Her kullanıcı ve firma için farklı olması gerekiyor. string cacheMenuKey = "SC_MENU_Comp" + "_User" + idUser.ToString(); // Kullanıcı ilk giriş yaptığını kontrol ediyoruz. if (_session.Get(Strings.Authorization.IsLoginSessionKey)) { _menu = _cache.Get <IEnumerable <SC_MENU> >(cacheMenuKey); } if (_menu != null) { if (_menu.ToList().Count > 0) { return(_menu.ToList()); } } // Menü objesi veritabanından sorgulanıyor ve getiriliyor. _menu = _repository.GetAll(idUser); // Menü obkesi cache atanıyor. _cache.Set(cacheMenuKey, _menu); // IsLoginSessionKey değeri true yapıyoruz. Cacheden okuyabilmek için. _session.Set(Strings.Authorization.IsLoginSessionKey, true); return(_menu); }
public async Task <CreateAdminUserResponse> CreateAdminUser(CreateAdminUserRequest request) { var response = new CreateAdminUserResponse(); var username = request.Username; var session = await _sessionManager.GetSession(); var duplicateResponse = await _accountService.DuplicateUserCheck(new DuplicateUserCheckRequest() { Username = username }); if (duplicateResponse.Notifications.HasErrors) { response.Notifications.Add(duplicateResponse.Notifications); return(response); } int userId; using (var uow = _uowFactory.GetUnitOfWork()) { userId = await uow.UserRepo.CreateUser(new Repositories.DatabaseRepos.UserRepo.Models.CreateUserRequest() { Username = username, First_Name = username, Password_Hash = PasswordHelper.HashPassword(request.Password), Created_By = ApplicationConstants.SystemUserId, Registration_Confirmed = true, Is_Enabled = true }); await uow.UserRepo.CreateUserRole(new Repositories.DatabaseRepos.UserRepo.Models.CreateUserRoleRequest() { User_Id = userId, Role_Id = 1, // the first role should always be admin Created_By = ApplicationConstants.SystemUserId }); var sessionEntity = await uow.SessionRepo.AddUserToSession(new Repositories.DatabaseRepos.SessionRepo.Models.AddUserToSessionRequest() { Id = session.SessionEntity.Id, User_Id = userId, Updated_By = ApplicationConstants.SystemUserId }); await _sessionProvider.Set(SessionConstants.SessionEntity, sessionEntity); uow.Commit(); } _cacheProvider.Set(CacheConstants.AdminUserExists, true); await _authenticationManager.SignIn(session.SessionEntity.Id); return(response); }
public void Add(Course course) { var cart = GetContent(); var cartPosition = cart.SingleOrDefault(c => c.Course.CourseId == course.CourseId); if (cartPosition == null) { cart.Add(new ShoppingCartPosition { Quantity = 1, Course = course, Price = course.Price }); } else { cartPosition.Quantity++; } sessionProvider.Set(CartContentKey, cart, TimeSpan.Zero); }
private string GetRandomText() { StringBuilder randomText = new StringBuilder(); string alphabets = "ABCDEFGHJKLMNPRSTUVYZ123456789"; Random r = new Random(); for (int j = 0; j <= 3; j++) { randomText.Append(alphabets[r.Next(alphabets.Length)]); } _session.Set(Strings.SessionKeys.Captcha, randomText.ToString().ToUpper()); return(randomText.ToString().ToUpper()); }
public static void Set(string key, object value) { provider.Set(key, value); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { // validate feature is enabled var config = await _cache.Configuration(); if (!config.Session_Logging_Is_Enabled) { await next(); return; } var session = await _sessionService.GetSession(); int sessionLogId; using (var uow = _uowFactory.GetUnitOfWork()) { var dbRequest = new Infrastructure.Repositories.SessionRepo.Models.CreateSessionLogRequest() { Session_Id = session.Id, Method = context.HttpContext.Request.Method, Controller = (string)context.RouteData.Values["Controller"], Action = (string)context.RouteData.Values["Action"], Url = context.HttpContext.Request.GetDisplayUrl(), Created_By = ApplicationConstants.SystemUserId }; if (context.ActionArguments.Any()) { var jsonString = JsonConvert.SerializeObject(context.ActionArguments, Formatting.Indented).Trim(); dbRequest.Action_Data_JSON = JsonHelper.ObfuscateFieldValues(jsonString, ApplicationConstants.ObfuscatedActionArgumentFields); } sessionLogId = await uow.SessionRepo.CreateSessionLog(dbRequest); uow.Commit(); // required for session event logging await _sessionProvider.Set(SessionConstants.SessionLogId, sessionLogId); } // do something before the action executes var resultContext = await next(); // do something after the action executes; resultContext.Result will be set if (resultContext.Exception != null && !resultContext.ExceptionHandled) { var events = await _cache.SessionEvents(); var eventItem = events.FirstOrDefault(e => e.Key == SessionEventKeys.Error); using (var uow = _uowFactory.GetUnitOfWork()) { var dbRequest = new Infrastructure.Repositories.SessionRepo.Models.CreateSessionLogEventRequest() { Session_Log_Id = sessionLogId, Event_Id = eventItem.Id, Message = resultContext.Exception.Message, Created_By = ApplicationConstants.SystemUserId }; await uow.SessionRepo.CreateSessionLogEvent(dbRequest); uow.Commit(); } } }
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { // validate feature is enabled var config = await _cache.Configuration(); if (!config.Session_Logging_Is_Enabled) { await next(); return; } _stopwatch.Start(); // do something before the action executes var resultContext = await next(); // do something after the action executes; resultContext.Result will be set var session = await _sessionManager.GetSession(); int sessionLogId; using (var uow = _uowFactory.GetUnitOfWork()) { var methodInfo = context.HandlerMethod.MethodInfo.Name; var method = context.HttpContext.Request.Method; var isAjax = !(methodInfo == "OnGet" || methodInfo == "OnPost" || methodInfo == "OnGetAsync" || methodInfo == "OnPostAsync"); var dbRequest = new Repositories.DatabaseRepos.SessionRepo.Models.CreateSessionLogRequest() { Session_Id = session.SessionEntity.Id, Page = (string)context.RouteData.Values["Page"], Handler_Name = context.HandlerMethod.Name, Method = method, Controller = (string)context.RouteData.Values["Controller"], Action = (string)context.RouteData.Values["Action"], IsAJAX = isAjax, Url = context.HttpContext.Request.GetDisplayUrl(), Created_By = ApplicationConstants.SystemUserId }; if (method == "POST" || !string.IsNullOrEmpty(context.HandlerMethod.Name)) { var postData = new Dictionary <string, object>(); var hasHandlerArguments = context.HandlerArguments.Any(); if (hasHandlerArguments) { postData.Add("Handler_Arguments", context.HandlerArguments); } var formData = context.HandlerInstance.GetType().GetProperty("FormData"); var hasFormData = formData != null; if (hasFormData && !isAjax) { postData.Add("Form_Data", ((dynamic)context.HandlerInstance).FormData); } if (hasHandlerArguments || hasFormData) { var jsonString = JsonConvert.SerializeObject(postData, Formatting.Indented).Trim(); dbRequest.Action_Data_JSON = JsonHelper.ObfuscateFieldValues(jsonString, ApplicationConstants.ObfuscatedActionArgumentFields); } } _stopwatch.Stop(); dbRequest.Elapsed_Milliseconds = _stopwatch.ElapsedMilliseconds; sessionLogId = await uow.SessionRepo.CreateSessionLog(dbRequest); uow.Commit(); // required for session event logging await _sessionProvider.Set(SessionConstants.SessionLogId, sessionLogId); if (resultContext.Exception != null && !resultContext.ExceptionHandled) { await _sessionManager.WriteSessionLogEvent(new Models.ManagerModels.Session.CreateSessionLogEventRequest() { EventKey = SessionEventKeys.Error, Info = new Dictionary <string, string>() { { "Message", resultContext.Exception.Message } } }); } } }
public bool LoginByUsernameAndPassword(string username, string password) { var encryptedPassword = _encrypter.Encrypt(password); var lstUser = _general.GetAll <SC_USER>(); var userModel = lstUser.Where(r => r.UserName == username && r.Password == encryptedPassword && r.Active && r.Deleted == false && r.FailedLoginCount < 4).FirstOrDefault(); if (userModel != null) { _sessionProvider.Set(Strings.Authorization.UserSessionKey, userModel); _sessionProvider.Set(Strings.Authorization.IsLoginSessionKey, false); userModel.FailedLoginCount = 0; _repository.Update(userModel); //_repository.SetContext(userModel.IdUser); _logger.LogInformation(new LogModel { ActionName = "Login", ControllerName = "LoginController", RequestUrl = "/Login", ShortMessage = Strings.Messages.LoginPage.Login(userModel) }); } else { var user2 = lstUser.Where(r => r.UserName == username && r.Deleted == false).FirstOrDefault(); if (user2 != null) { _logger.LogInformation(new LogModel { ActionName = "Login", ControllerName = "LoginController", RequestUrl = "/Login", ShortMessage = Strings.Messages.LoginPage.FailedLogin(user2) }); if (user2.FailedLoginCount < 4) { user2.FailedLoginCount++; _repository.Update(user2); return(false); } else { user2.Active = false; _repository.Update(user2); return(false); } } else { return(false); } } _cookieProvider.SetCookie(Strings.CookieKeys.UserName, userModel.UserName, TimeSpan.FromDays(1)); _cookieProvider.SetCookie(Strings.CookieKeys.IdUser, userModel.IdUser.ToString(), TimeSpan.FromDays(1)); return(true); }
public async Task <LoginResponse> Login(LoginRequest request) { var response = new LoginResponse(); var config = await _cache.Configuration(); var session = await _sessionService.GetSession(); UserEntity user; using (var uow = _uowFactory.GetUnitOfWork()) { user = await uow.UserRepo.GetUserByUsername(new Infrastructure.Repositories.UserRepo.Models.GetUserByUsernameRequest() { Username = request.Username }); // check if we found a user or if their password was incorrect if (user == null || !PasswordHelper.Verify(request.Password, user.Password_Hash)) { // if we found the user, handle invalid login attempts else generic fail message if (user != null) { // check if we need to lock the user if (user.Invalid_Login_Attempts >= config.Max_Login_Attempts && !user.Is_Locked_Out) { await uow.UserRepo.LockoutUser(new Infrastructure.Repositories.UserRepo.Models.LockoutUserRequest() { Id = user.Id, Lockout_End = DateTime.Now.AddMinutes(config.Account_Lockout_Expiry_Minutes), Updated_By = ApplicationConstants.SystemUserId }); await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest() { EventKey = SessionEventKeys.UserLocked }); } else { var dbRequest = new Infrastructure.Repositories.UserRepo.Models.AddInvalidLoginAttemptRequest() { User_Id = user.Id, Updated_By = ApplicationConstants.SystemUserId }; // if we are already locked out then extend the lockout time if (user.Lockout_End.HasValue) { dbRequest.Lockout_End = DateTime.Now.AddMinutes(config.Account_Lockout_Expiry_Minutes); } await uow.UserRepo.AddInvalidLoginAttempt(dbRequest); } uow.Commit(); } response.Notifications.AddError("Username or password is incorrect"); return(response); } if (user.Is_Locked_Out) { if (user.Lockout_End <= DateTime.Now) { await uow.UserRepo.UnlockUser(new Infrastructure.Repositories.UserRepo.Models.UnlockUserRequest() { Id = user.Id, Updated_By = ApplicationConstants.SystemUserId }); uow.Commit(); await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest() { EventKey = SessionEventKeys.UserUnlocked }); } else { response.Notifications.AddError($"Your account has been locked, please try again in {config.Account_Lockout_Expiry_Minutes} minute(s)"); return(response); } } else if (user.Invalid_Login_Attempts > 0) // cleanup of old invalid login attempts { await uow.UserRepo.UnlockUser(new Infrastructure.Repositories.UserRepo.Models.UnlockUserRequest() { Id = user.Id, Updated_By = ApplicationConstants.SystemUserId }); uow.Commit(); } if (!user.Is_Enabled) { response.Notifications.AddError("Your account has been disabled, please contact the website administrator"); return(response); } if (!user.Registration_Confirmed) { response.Notifications.AddError("Please check your email to activate your account"); return(response); } var sessionEntity = await uow.SessionRepo.AddUserToSession(new Infrastructure.Repositories.SessionRepo.Models.AddUserToSessionRequest() { Id = session.Id, User_Id = user.Id, Updated_By = ApplicationConstants.SystemUserId }); uow.Commit(); await _sessionProvider.Set(SessionConstants.SessionEntity, sessionEntity); } await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest() { EventKey = SessionEventKeys.UserLoggedIn }); var claims = new List <Claim>() { new Claim(ClaimTypes.Name, session.Id.ToString()) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); await _httpContextAccessor.HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); // user principal is controlled in session return(response); }
public void CheckUserAuthentication(RequestContext context) { SC_USER user = _sessionProvider.Get <SC_USER>(Strings.Authorization.UserSessionKey); if (user == null) { var idUser = _cookieProvider.GetCookie(Strings.CookieKeys.IdUser); if (!string.IsNullOrEmpty(idUser) && idUser != "0") { user = _definitionBusiness.Get <SC_USER>(Convert.ToInt32(idUser)); _sessionProvider.Set(Strings.Authorization.UserSessionKey, user); _sessionProvider.Set(Strings.Authorization.IsLoginSessionKey, false); } else { throw new AuthorizationException("Bu sayfada işlem yapmaya yetkiniz bulunmamaktadır."); } } IEnumerable <SC_MENU> lstMenu = _menuBusiness.GetAll(user.IdUser); string _controllerName = string.Empty; string _action = string.Empty; string _param = string.Empty; string _fullPath = context.HttpContext.Request.FilePath; if (context.RouteData.Values.ContainsKey("controller")) { object value = context.RouteData.Values["controller"]; _controllerName = value.ToString(); } if (context.RouteData.Values.ContainsKey("action")) { object value = context.RouteData.Values["action"]; _action = value.ToString(); } if (context.RouteData.Values.ContainsKey("id")) { object value = context.RouteData.Values["id"]; _param = value.ToString(); } for (int i = 0; i < Strings.AuthenticationPages.PageNames().Length; i++) { string pageName = Strings.AuthenticationPages.PageNames()[i]; if (_controllerName.ToLower() == pageName.ToLower()) { return; } } for (int i = 0; i < Strings.AuthenticationPages.ActionPaths().Length; i++) { string actionPath = Strings.AuthenticationPages.ActionPaths()[i]; if (_fullPath.ToLower().Contains(actionPath.ToLower())) { return; } } SC_MENU objPage = null; if (_controllerName.ToLower() == "definition" && (_action.ToLower() == "index" || _action.ToLower() == "ındex")) { objPage = lstMenu.FirstOrDefault(k => k.Controller.ToLower() == _controllerName.ToLower() && k.Action.ToLower() == _action.ToLower() && k.Parametre.ToLower() == _param.ToLower()); } else { objPage = lstMenu.FirstOrDefault(k => k.Controller.ToLower() == _controllerName.ToLower()); } if (objPage == null) { throw new AuthorizationException("Bu sayfada işlem yapmaya yetkiniz bulunmamaktadır."); } }
public async Task <GetSessionResponse> GetSession() { var response = new GetSessionResponse(); // get or create a new session var session = await _sessionProvider.Get <SessionEntity>(SessionConstants.SessionEntity); if (session == null) { // flush any authenticated cookies in the event the application restarts await _httpContextAccessor.HttpContext.SignOutAsync(); await _sessionProvider.Remove(SessionConstants.User); using (var uow = _uowFactory.GetUnitOfWork()) { session = await uow.SessionRepo.CreateSession(new Infrastructure.Repositories.SessionRepo.Models.CreateSessionRequest() { Created_By = ApplicationConstants.SystemUserId }); uow.Commit(); await _sessionProvider.Set(SessionConstants.SessionEntity, session); } } response.Id = session.Id; response.SessionLogId = await _sessionProvider.Get <int>(SessionConstants.SessionLogId); // get or hydrate user from session var user = await _sessionProvider.Get <User>(SessionConstants.User); if (user == null && session.User_Id.HasValue) { using (var uow = _uowFactory.GetUnitOfWork()) { user = new User(); user.Entity = await uow.UserRepo.GetUserById(new Infrastructure.Repositories.UserRepo.Models.GetUserByIdRequest() { Id = session.User_Id.Value }); uow.Commit(); var usersRoles = await _cache.UserRoles(); var userRoleIds = usersRoles.Where(ur => ur.User_Id == user.Entity.Id).Select(ur => ur.Role_Id); var rolePermissions = await _cache.RolePermissions(); var userRolePermissionIds = rolePermissions.Where(rc => userRoleIds.Contains(rc.Role_Id)).Select(rc => rc.Permission_Id); var permissionsLookup = await _cache.Permissions(); var userPermissionsData = permissionsLookup.Where(c => userRolePermissionIds.Contains(c.Id)); var rolesLookup = await _cache.Roles(); var userRolesData = rolesLookup.Where(r => userRoleIds.Contains(r.Id)); foreach (var userPermission in userPermissionsData) { user.PermissionKeys.Add(userPermission.Key); } foreach (var userRole in userRolesData) { user.RoleIds.Add(userRole.Id); } await _sessionProvider.Set(SessionConstants.User, user); } } response.User = user; return(response); }