/// <summary> /// Initializes a new instance of the <see cref="YafReadTrackCurrentUser"/> class. The yaf read track current user. /// </summary> /// <param name="yafSession"> /// </param> /// <param name="boardSettings"> /// </param> /// <param name="sessionState"> /// The session State. /// </param> public YafReadTrackCurrentUser( IYafSession yafSession, YafBoardSettings boardSettings, HttpSessionStateBase sessionState) { this._yafSession = yafSession; this._boardSettings = boardSettings; this._sessionState = sessionState; }
public HttpSessionStateCache(HttpSessionStateBase sessionState) { if (sessionState == null) throw new ArgumentNullException("sessionState"); _sessionState = sessionState; }
/// <summary> /// Generates the CSRF state code. /// </summary> /// <param name="pSessionState">State of the p session.</param> /// <exception cref="System.ApplicationException">pSessionState cannot be null</exception> public string GenerateCSRFStateCode(HttpSessionStateBase pSessionState) { if (pSessionState == null) throw new ApplicationException("pSessionState cannot be null"); var statecode = Guid.NewGuid(); pSessionState["state"] = statecode.ToString(); return statecode.ToString(); }
public static void InitializationAuthVar(dynamic ViewBag, HttpSessionStateBase Session) { ViewBag.IsUser = false; ViewBag.IsModerator = false; ViewBag.IsAdmin = false; if (Session["user"] != null) { User user = (User)Session["user"]; foreach (Role role in user.Roles) { if (role.Name.Equals("USER_ROLE")) { ViewBag.IsUser = true; } if (role.Name.Equals("MODERATOR_ROLE")) { ViewBag.IsModerator = true; } if (role.Name.Equals("ADMIN_ROLE")) { ViewBag.IsAdmin = true; } } } }
internal static StaffMember getMember(HttpSessionStateBase Session ,int memberID,MemberType membertype) { Dictionary<String, List<LibraryMemberBase>> librarymembers = Session["LibraryMembers"] as Dictionary<String, List<LibraryMemberBase>>; List<LibraryMemberBase> staffmemberlist = librarymembers[membertype.ToString()]; StaffMember member = (StaffMember)staffmemberlist.Single(s => s.ID == memberID); return member; }
/// <summary> /// Private helper method to perform a new search or maintain a previous search through /// pagination and filter changes /// </summary> /// <param name="workouts">The base workout query result</param> /// <param name="search">The WorkoutSearch object containing the parameters to search</param> /// <param name="sortBy">The passed sort string if it exists, else null</param> /// <param name="page">The passed page param if it exists, else null</param> /// <param name="session">The Session object to get or set variables from/to</param> /// <param name="viewBag">The viewBag object to pass the set variables back to the view with</param> /// <returns>The searched workouts</returns> public static IQueryable<workout> doSearch(IQueryable<workout> workouts, WorkoutSearch search, string sortBy, int? page, HttpSessionStateBase session, dynamic viewBag) { if (page != null || !String.IsNullOrEmpty(sortBy)) { search = SessionVariableManager.setSearchFromSession(session, search); } else SessionVariableManager.setSessionFromSearch(session, search); if (!String.IsNullOrEmpty(search.name)) workouts = workouts.Where(w => w.name.Contains(search.name)); if (!String.IsNullOrEmpty(search.category)) workouts = workouts.Where(w => w.category.name.Contains(search.category)); if (!String.IsNullOrEmpty(search.username)) workouts = workouts.Where(w => w.user.username.Contains(search.username)); if (!String.IsNullOrEmpty(search.dateAdded)) { string[] dateArrayString = search.dateAdded.Split('-'); int year = Convert.ToInt16(dateArrayString[0]); int month = Convert.ToInt16(dateArrayString[1]); int day = Convert.ToInt16(dateArrayString[2]); workouts = workouts.Where(w => w.created_at.Year == year && w.created_at.Month == month && w.created_at.Day == day); } return workouts; }
private topCart getGuestCartItem(titizOtoEntities db, HttpSessionStateBase httpSessionStateBase, HttpRequestBase request, HttpResponseBase response, int langId) { httpSessionStateBase["userId"] = null; topCart helperItem = new topCart(); string guestGuid = ""; if (httpSessionStateBase["guestGuid"] != null) { guestGuid = httpSessionStateBase["guestGuid"].ToString(); if (guestGuid == "System.Web.HttpCookie" || guestGuid == "00000000-0000-0000-0000-000000000000") { guestGuid = getGuidCookieOrNew(request, response); httpSessionStateBase["guestGuid"] = guestGuid; } } else { guestGuid = getGuidCookieOrNew(request, response); } helperItem.guestGuid = guestGuid; var basketList = db.tbl_basket.Where(a => a.guestCode == guestGuid).ToList(); if (basketList != null && basketList.Count > 0) { helperItem.basketIdString = string.Join(",", basketList.Select(a => a.basketId).ToList()); helperItem.productCount = basketList.Sum(a => a.quantity); } return helperItem; }
public static int InvalidPasswordAttempts(HttpSessionStateBase session, int increment = 0) { if (session == null) { return 0; } int retVal = 0; if (session["InvalidPasswordAttempts"] == null) { retVal = retVal + increment; session.Add("InvalidPasswordAttempts", retVal); } else { retVal = Conversion.TryCastInteger(session["InvalidPasswordAttempts"]) + increment; session["InvalidPasswordAttempts"] = retVal; } if (increment > 0) { Log.Warning("{Count} Invalid attempt to sign in from {Host}/{IP} using {Browser}.", retVal, GetUserHostAddress(), GetUserIpAddress(), GetBrowser().Browsers); } return retVal; }
public static void AddRequestToSession(byte[] req, ElmahMailSAZConfig config, HttpSessionStateBase session) { var reqs = ((List<byte[]>)session[sessionKey]); reqs.Add(req); if (config.KeepLastNRequests.HasValue && reqs.Count > config.KeepLastNRequests) reqs.RemoveAt(0); }
public static void Update(HttpSessionStateBase session, MatchWord matchWord, string Word) { List<MatchWord> ModelObject = InitializeModelObject(session["Model"]); ModelObject.RemoveAll(x => x.Word == Word); UpdateModel(matchWord, ModelObject); session["Model"] = ModelObject; }
/// <summary> /// Attempts to login a user. /// </summary> /// <param name="session">The user's session.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>true if login was successful, false otherwise.</returns> /// <exception cref="System.ArgumentNullException">Thrown when session is null.</exception> /// <exception cref="System.ArgumentException">Thrown when username or password is null, empty, or white space.</exception> public bool Login(HttpSessionStateBase session, string username, string password) { // Sanitize if (session == null) { throw new ArgumentNullException("session"); } if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentException("cannot be null, empty, or white space", "username"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException("cannot be null, empty, or white space", "password"); } // Try and find the user by username and password var user = (User) null; // TODO: need a password! --> _userRepository.GetAll().FirstOrDefault(i => i.Email == username && i.Password == password); // If no user the login was unsuccessful if (user == null) { return false; } // Login was successful session[_sessionLoggedInKey] = user; return true; }
/// <summary> /// Does a setup of the session indexes that are used by controllers to check if a Client has logged in /// </summary> /// <param name="session"></param> public static void SetupUserSession(HttpSessionStateBase session, string username, int roleId) { session[SESSION_USERNAME_KEY] = username; session[SESSION_ROLE_KEY] = (Role) roleId; session[SESSION_RETRY_DELAY_KEY] = null; session[SESSION_RETRIES_KEY] = 0; }
public static void Logout(HttpSessionStateBase session, HttpResponseBase response) { var module = FederatedAuthentication.SessionAuthenticationModule; module.DeleteSessionTokenCookie(); module.SignOut(); session.Abandon(); }
private void checkCookie(titizOtoEntities db, HttpSessionStateBase httpSessionStateBase, HttpRequestBase request, HttpResponseBase response, DbWithController itemController) { if (httpSessionStateBase["userId"] == null && request.Cookies["userCookie"] != null && request.Cookies["userCookie"]["userHashVal"] != null && request.Cookies["userCookie"]["userHashValTwo"] != null) { var userList = db.tbl_user.Where(a => a.registerStatuId == (int)registerStatu.registered).ToList(); tbl_user selectedUser = null; string userHashVal = request.Cookies["userCookie"]["userHashVal"]; string userHashValTwo = request.Cookies["userCookie"]["userHashValTwo"]; foreach (var item in userList) { if (item.password.Length > 6 && userHashValTwo == item.password.Substring(0, 7) && itemController.MD5(item.email).Substring(0, 7) == userHashVal) { selectedUser = item; break; } } if (selectedUser != null) { httpSessionStateBase["userId"] = selectedUser.userId.ToString(); httpSessionStateBase["userRoleId"] = selectedUser.userTypeId.ToString(); } else { response.Cookies["userCookie"].Expires = DateTime.Now.AddDays(-1); } } }
public static bool ApiAuthenticate(Dictionary<string, string> sessionData, HttpSessionStateBase Session, System.Web.Http.Controllers.HttpActionContext actionContext) { string code = EncrDecrAction.Encrypt( EncrDecrAction.Encrypt(EncrDecrAction.Encrypt(Session["UserId"].ToString(), true), true) + EncrDecrAction.Encrypt(EncrDecrAction.Encrypt(Session["UserRoleId"].ToString(), true), true) + EncrDecrAction.Encrypt(EncrDecrAction.Encrypt(Session["UserName"].ToString(), true), true) + EncrDecrAction.Encrypt(EncrDecrAction.Encrypt(Session["RoleName"].ToString(), true), true) + EncrDecrAction.Encrypt(EncrDecrAction.Encrypt(Session["ParentRoleName"].ToString(), true), true), true); if (code == Session["SRES"].ToString()) { UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); var routeValueDictionary = urlHelper.RequestContext.RouteData.Values; string controller = routeValueDictionary["controller"].ToString(); string action = actionContext.Request.Method.ToString(); int argument = actionContext.Request.RequestUri.Segments.Count() - 3; string query = "select * from appviews where LOWER(Controller) = LOWER(@Controller) and LOWER(Action) = LOWER(@Action) and " + sessionData["RoleName"] + "= 1 and Argument=@Argument and ControllerType='api'"; Hashtable conditionTable = new Hashtable(); conditionTable["Controller"] = controller; conditionTable["Action"] = action; conditionTable["Argument"] = argument; DBGateway aDbGateway = new DBGateway(); DataSet aDataSet = aDbGateway.Select(query, conditionTable); if (aDataSet.Tables[0].Rows.Count > 0) { return true; } } return false; }
public static void InitializeDatabase(HttpSessionStateBase sessionState) { //ToDo : refacture so controllers use DatabaseServices instead of SessionStateManager var services = ObjectFactory.GetInstance<IDatabaseServices>(); services.SessionStateCache = new HttpSessionStateCache(sessionState); services.InitDatabase(); }
public static bool UserRoleValidation(HttpSessionStateBase session, string role) { User user = (User)session["User"]; if (user.role == role) return true; else return false; }
public static bool IsUserLoggedIn(HttpSessionStateBase session) { var user = session["User"]; if (user == null) return false; else return true; }
private void GetKey(HttpSessionStateBase session) { var data = session[EncryptFieldData] as Tuple<byte[], byte[]>; if (data == null) { throw new Exception("unexpected null: "); } key = data.Item1; iv = data.Item2; }
public HttpListenerContextAdapter(HttpListenerContext context, string virtualPath, string physicalPath) { this.request = new HttpListenerRequestAdapter(context.Request, virtualPath, MakeRelativeUriFunc(context.Request.Url, virtualPath)); this.response = new HttpListenerResponseAdapter(context.Response); this.server = new ConcoctHttpServerUtility(physicalPath); this.cache = new Cache(); this.session = new HttpListenerSessionState(); }
internal static List<LibraryMemberBase> GetAllMembers(HttpSessionStateBase Session) { Dictionary<String, List<LibraryMemberBase>> librarymembers = Session["LibraryMembers"] as Dictionary<String, List<LibraryMemberBase>>; List<LibraryMemberBase> memberlist = new List<LibraryMemberBase>(); memberlist.AddRange(librarymembers[MemberType.Staff.ToString()]); memberlist.AddRange(librarymembers[MemberType.Member.ToString()]); return memberlist; }
//用来判断当前用户是否拥有Action的权限 public static bool HasRole(HttpSessionStateBase se, string rolid) { //判断是否登录 MoLogin mo = MyLogin.GetLogin(se); if (mo == null) return false; return mo.ID == "admin" || HasRole(mo.ID, rolid); }
private static ILifetimeScope GetOrCreateSessionScope(HttpSessionStateBase session) { var scope = (ILifetimeScope) session[lifetimeScopeKey]; if (scope != null) return scope; scope = new DefaultLifetimeScope(); session[lifetimeScopeKey] = scope; return scope; }
public string Decrypt(HttpSessionStateBase session, string toDecrypt) { byte[] valueBytes = Convert.FromBase64String(toDecrypt); GetKey(session); using (ICryptoTransform decrypter = provider.CreateDecryptor(key, iv)) { byte[] decryptedBytes = decrypter.TransformFinalBlock(valueBytes, 0, valueBytes.Length); return Encoding.UTF8.GetString(decryptedBytes); } }
/// <summary> /// Sets the sortBy param to the session sort value if the session exists. /// If the session does not exist the passed in sortBy param is returned. /// </summary> /// <param name="sortBy">The current sort filter</param> /// <returns>The sort parameter set from the session else the original sort param</returns> public static string setSortFromSession(HttpSessionStateBase Session, string sortBy) { if (Session != null) { sortBy = Session["SortBy"] as String; } return sortBy; }
public string Encrypt(HttpSessionStateBase session, string toEncrypt) { byte[] valueBytes = Encoding.UTF8.GetBytes(toEncrypt); CreateOrUpdateKey(session); using (ICryptoTransform encrypter = provider.CreateEncryptor(key, iv)) { byte[] encryptedBytes = encrypter.TransformFinalBlock(valueBytes, 0, valueBytes.Length); return Convert.ToBase64String(encryptedBytes); } }
// Methods public HttpSessionStateBaseWrapper(HttpSessionStateBase httpSessionState) { if (httpSessionState == null) { throw new ArgumentNullException("httpSessionState"); } this._session = httpSessionState; }
public void Init() { _session = Isolate.Fake.Instance<HttpSessionStateBase>(); _connection = Isolate.Fake.Instance<IDbConnection>(); _cache = new HttpSessionStateCache(_session); Isolate.WhenCalled(() => _session[HttpSessionStateCache.ConnectionSetting] = null).ReturnRecursiveFake(); }
public static void SetCurrentThreadCulture(HttpSessionStateBase session) { if (session != null && session["Culture"] != null) { System.Threading.Thread.CurrentThread.CurrentCulture = (System.Globalization.CultureInfo)session["Culture"]; System.Threading.Thread.CurrentThread.CurrentUICulture = (System.Globalization.CultureInfo)session["Culture"]; } }
protected virtual bool IsUserAuthenticated(HttpSessionStateBase session) { if (session == null) { throw new ArgumentNullException("session"); } return session["User"] != null; }
public static HttpContextBase DynamicHttpContextBase(this MockRepository mocks, HttpRequestBase request, HttpResponseBase response, HttpSessionStateBase session, HttpServerUtilityBase server, IPrincipal user) { var context = mocks.DynamicMock <HttpContextBase>(); SetupResult.For(context.User).Return(user); SetupResult.For(context.Request).Return(request); SetupResult.For(context.Response).Return(response); SetupResult.For(context.Session).Return(session); SetupResult.For(context.Server).Return(server); mocks.Replay(context); return(context); }
public StatefulStoragePerSession(System.Web.HttpSessionStateBase session) : base(key => session[key], (key, value) => session[key] = value) { }
public void Logout(HttpRequestBase request, System.Web.HttpResponseBase response, System.Web.HttpSessionStateBase session) { //HttpCookie myCookie = new HttpCookie("rfs.username"); //myCookie = Request.Cookies["rfs.username"]; //if (myCookie != null) //{ // Session[myCookie.Value] = ""; //} //HttpCookie currentUserCookie = Request.Cookies["rfs.username"]; //Response.Cookies.Remove("rfs.username"); //if (currentUserCookie != null) //{ // currentUserCookie.Expires = DateTime.Now.AddDays(-10); // currentUserCookie.Value = null; // Response.SetCookie(currentUserCookie); //} }
public void Logout(System.Web.HttpRequestBase request, System.Web.HttpResponseBase response, System.Web.HttpSessionStateBase session) { HttpCookie myCookie = new HttpCookie("rfs.username"); myCookie = request.Cookies["rfs.username"]; if (myCookie != null) { session[myCookie.Value] = ""; } HttpCookie currentUserCookie = request.Cookies["rfs.username"]; response.Cookies.Remove("rfs.username"); if (currentUserCookie != null) { currentUserCookie.Expires = DateTime.Now.AddDays(-10); currentUserCookie.Value = null; response.SetCookie(currentUserCookie); } }
/// <summary> /// Проверяет подлинность человека по значению с картинки для заданной сессии /// </summary> public static System.Boolean Validate(System.Web.HttpSessionStateBase session, System.String captchaValue) { // check captcha key from session return((session["CAPTCHA"] as System.String) == captchaValue); }