public UserSessions CreateNewUserSession(int id, LoginModel user) { string token = CreateRandomToken(); string tokenSalt = string.Empty; //use User create timestamp and web.config secret key to encrypt newly created token (guids...) string tokenEncryptKey = DateTime.Now + ConfigurationManager.AppSettings["ENCRYPT_LINK_KEY"]; string encryptedToken = AesEncryptionHelper.Encrypt(token, tokenEncryptKey, ref tokenSalt); // use newly created token (guids...) and web.config secret to encrypt session id, use same salt as used by token string sessionCookieEncryptKey = token + ":" + ConfigurationManager.AppSettings["ENCRYPT_LINK_KEY"]; string doubleSubmitSessionCookie = AesEncryptionHelper.Encrypt(Guid.NewGuid().ToString(), sessionCookieEncryptKey, ref tokenSalt); var userSession = new UserSessions { UserId = id, AuthToken = encryptedToken.Base64ToBase64URL(), //since we may use this authToken in a URL later, let's make sure it's URL safe. AuthExpiration = DateTime.UtcNow.AddMinutes(12 * 60), IsExpired = false, HardAbsoluteExpirationTime = DateTime.UtcNow.AddMinutes(12 * 60), AuthTokenSalt = tokenSalt, AuthDoubleSubmitSessionIdCookie = doubleSubmitSessionCookie, }; return(userSession); }
public async Task <bool> AssociateUserToSession(Guid userID, Guid sessionID, bool admin) { Console.WriteLine(String.Format("TRY Assosiating session {0} to user {1}", sessionID, userID)); if (UserSessions.TryGetValue(userID, out Guid oldSessionID)) { SessionSockets.Remove(oldSessionID, out _);//remove stale socket - TODO check } UserSessions.AddOrUpdate(userID, sessionID, (key, _) => sessionID); if (admin) { AdminSessions.AddOrUpdate(userID, sessionID, (key, _) => sessionID); } if (!SessionSockets.TryGetValue(sessionID, out WebSocket socket)) { Console.WriteLine(String.Format("No websocket for session {0} to user {1}", sessionID, userID)); return(false);// no socket assigned to session } if (UserPending.GetValueOrDefault(userID, false)) { byte[] msg = Encoding.UTF8.GetBytes("Alert"); ArraySegment <byte> buffer = new ArraySegment <byte>(msg, 0, msg.Length); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); UserPending.TryUpdate(userID, false, true); } Console.WriteLine(string.Format("DONE Assosiating session {0} to user {1}", sessionID, userID)); return(true); }
public void PostOrderToDataPak(int orderId) { string req = new DataPak().GetRequest(orderId, false, false); // Posting order to OMX string res = CommonHelper.HttpPost(config.Attributes["transactionUrl"].Value, req); Dictionary <string, AttributeValue> orderAttributes = new Dictionary <string, AttributeValue>(); orderAttributes.Add("Request", new CSBusiness.Attributes.AttributeValue(CSCore.Utils.CommonHelper.Encrypt(req))); orderAttributes.Add("Response", new CSBusiness.Attributes.AttributeValue(res)); XmlDocument doc = new XmlDocument(); doc.LoadXml(res); XmlNode xnResult = doc.SelectSingleNode("/DatapakServices/Order/Result/Code"); if (xnResult.InnerText.ToLower().Equals("001")) { //CSResolve.Resolve<IOrderService>().SaveOrderInfo(orderId, 2, req.ToLower().Replace("utf-8", "utf-16"), res.ToLower().Replace("utf-8", "utf-16")); CSResolve.Resolve <IOrderService>().UpdateOrderAttributes(orderId, orderAttributes, 2); OrderHelper.SendOrderCompletedEmail(orderId); } else { //CSResolve.Resolve<IOrderService>().SaveOrderInfo(orderId, 5, req.ToLower().Replace("utf-8", "utf-16"), res.ToLower().Replace("utf-8", "utf-16")); CSResolve.Resolve <IOrderService>().UpdateOrderAttributes(orderId, orderAttributes, 5); //sending email to admins OrderHelper.SendEmailToAdmins(orderId); } UserSessions.InsertSessionEntry(HttpContext.Current, true, 0, 0, orderId); }
//////////////////////////////////////////////////////////////////////////////// // Creates a new process as SYSTEM //////////////////////////////////////////////////////////////////////////////// public bool GetSystem(string newProcess) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); NTAccount systemAccount = (NTAccount)securityIdentifier.Translate(typeof(NTAccount)); Console.WriteLine("[*] Searching for {0}", systemAccount.ToString()); processes = UserSessions.EnumerateUserProcesses(false, systemAccount.ToString()); foreach (uint process in processes.Keys) { if (OpenProcessToken((int)process)) { Console.WriteLine(" [+] Opened {0}", process); SetWorkingTokenToRemote(); if (DuplicateToken(Winnt._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) { SetWorkingTokenToNewToken(); if (StartProcessAsUser(newProcess)) { return(true); } } } } Misc.GetWin32Error("GetSystem"); return(false); }
public static void Logout(string sessionID) { var sesh = UserSessions.Where(X => X.sessionID == sessionID).FirstOrDefault(); UserSessions.Remove(sesh); //isLoggedIn = false; //LoginToken = null; }
public Guid CreateCart(Guid clientId, String password) { Client aClient = GetClient(clientId, password); Cart aCart = new Cart(); UserSession userSession = new UserSession(Clock.TimeNow(), aClient, aCart); UserSessions.Add(userSession); return(userSession.CartId); }
public void AddAQuantityOfAnItem(int quantity, string aBook, Guid aCartId) { UserSession userSession = FindUserSessionByCartId(aCartId); userSession.VerifyCartExpired(Clock.TimeNow()); userSession.AddQuantityOfAnItem(aBook, quantity, Clock); UserSessions.Add(userSession); }
public IActionResult UpdateSwipeStatus(UserSessions statusToUpdate) { var user = _repository.UpdateSwipeStatus(statusToUpdate); if (user == null) { return(BadRequest("User's swipe status cannot be updated. Please try again.")); } return(Ok(user)); }
//////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// private static void _SampleProcessWMI() { Dictionary <string, uint> users = UserSessions.EnumerateTokensWMI(); Console.WriteLine("{0,-40}{1,-20}{2}", "User", "Process ID", "Process Name"); Console.WriteLine("{0,-40}{1,-20}{2}", "----", "----------", "------------"); foreach (string name in users.Keys) { Console.WriteLine("{0,-40}{1,-20}{2}", name, users[name], Process.GetProcessById((int)users[name]).ProcessName); } }
public bool DisassociateUser(Guid userID) { if (!UserSessions.TryRemove(userID, out Guid found)) { return(false);// No session associated } AdminSessions.TryRemove(userID, out _); SessionSockets.TryRemove(found, out _);//remove stale socket - TODO check Console.WriteLine(string.Format("Dissacociated user {0}", userID)); return(true); }
public static string storeLoginSession(string Token) { string sessionGuid = Guid.NewGuid().ToString(); UserSessionItem sesh = new UserSessionItem(); sesh.sessionID = sessionGuid; sesh.authToken = Token; sesh.expiryTimestamp = DateTime.Now.AddDays(LoginExpiryDays); UserSessions.Add(sesh); return(sessionGuid); }
public void RemoveUserSession(User user) { UserSession us = UserSessions.Where(u => u.Session == this && u.User == user).FirstOrDefault(); if (us != null) { UserSessions.Remove(us); } else { throw new Exception($"User not found for session: {this}"); } }
private async Task AddHistoryToDb(int userId, Movies result) { var userSession = new UserSessions() { MovieName = result.Name, UserId = userId, ReleaseDate = result.ReleasedDate, SearchedOn = DateTime.UtcNow }; _context.Add(userSession); //await _context.SaveChangesAsync(); }
public static bool isLoggedIn(string sessionID) { var currentSesh = UserSessions.Where(x => x.sessionID == sessionID); if (currentSesh.Any()) { return(true); } else { return(false); } }
public static string retrieveToken(string sessionID) { var currentSesh = UserSessions.Where(x => x.sessionID == sessionID).FirstOrDefault(); if (currentSesh != null && !(currentSesh.expiryTimestamp < DateTime.Now)) { return(currentSesh.authToken); } else { UserSessions.Remove(currentSesh); return("expired"); } }
public void AddUserSession(User user) { if (!SessionFull() && user.UserStatus != UserStatus.BLOCKED && !UserSessions.Where(us => us.User == user).Any()) { UserSession us = new UserSession(); us.User = user; us.UserId = user.UserId; us.SessionId = SessionId; us.Session = this; UserSessions.Add(us); } else { throw new Exception("Er moeten beschikbare plekken zijn en je mag geen blocked user zijn"); } }
/// <summary> /// Gets an UserSession or creates new if not exists /// </summary> /// <param name="userID">User ID</param> /// <returns></returns> public UserSession ObtainUserSession(long userID) { UserSession userSession = null; // Try to get the User's respective UserSession from UserConcurrentList, create new if not exists. userSession = UserSessions? .Where(uS => uS.UserID == userID) .FirstOrDefault(); if (userSession == null) { // Create new UserSession for the User and add to UserSessions UserSessions.Add(userSession = new UserSession(userID)); } return(userSession); }
public async Task AlertUser(Guid userID) { if (UserSessions.TryGetValue(userID, out Guid sessionID)) { if (SessionSockets.TryGetValue(sessionID, out WebSocket socket)) { Console.WriteLine(string.Format("allertin session {0} user {1}", sessionID, userID)); byte[] msg = Encoding.UTF8.GetBytes("Alert"); ArraySegment <byte> buffer = new ArraySegment <byte>(msg, 0, msg.Length); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); UserPending.AddOrUpdate(userID, false, (key, _) => false); return; } } UserPending.AddOrUpdate(userID, true, (key, _) => true); }
//////////////////////////////////////////////////////////////////////////////// // Use WMI to find processes that a user is running //////////////////////////////////////////////////////////////////////////////// private static void _FindUserProcessesWMI(CommandLineParsing cLP) { string user; if (!cLP.GetData("username", out user)) { Console.WriteLine("[-] Username not specified"); return; } Dictionary <uint, string> processes = UserSessions.EnumerateUserProcessesWMI(user); Console.WriteLine("{0,-30}{1,-30}", "Process ID", "Process Name"); Console.WriteLine("{0,-30}{1,-30}", "----------", "------------"); foreach (uint pid in processes.Keys) { Console.WriteLine("{0,-30}{1,-30}", pid, processes[pid]); } }
public UserSessions AddUsersToASession(UserSessions usersToAdd) { var sql = @"insert into UserSessions (SessionId, UserId, isSwiped) output inserted.* values (@sessionId, @userId, 0)"; using (var db = new SqlConnection(ConnectionString)) { var parameters = new { sessionId = usersToAdd.SessionId, userId = usersToAdd.UserId, }; var newUsers = db.QueryFirstOrDefault <UserSessions>(sql, parameters); return(newUsers); } }
public UserSessions UpdateSwipeStatus(UserSessions statusToUpdate) { var sql = @"update UserSessions set isSwiped = @isSwiped output inserted.* where SessionId = @sessionId and userId = @userId"; using (var db = new SqlConnection(ConnectionString)) { var parameter = new { sessionId = statusToUpdate.SessionId, userId = statusToUpdate.UserId, isSwiped = statusToUpdate.isSwiped, }; var updatedStatus = db.QueryFirstOrDefault <UserSessions>(sql, parameter); return(updatedStatus); } }
protected override void OnDropDownOpening(EventArgs e) { this.menuWindowTranslucent.Checked = PdnBaseForm.EnableOpacity; this.menuWindowTools.Checked = AppWorkspace.Widgets.ToolsForm.Visible; this.menuWindowHistory.Checked = AppWorkspace.Widgets.HistoryForm.Visible; this.menuWindowLayers.Checked = AppWorkspace.Widgets.LayerForm.Visible; this.menuWindowColors.Checked = AppWorkspace.Widgets.ColorsForm.Visible; if (UserSessions.IsRemote()) { this.menuWindowTranslucent.Enabled = false; this.menuWindowTranslucent.Checked = false; } bool pluralDocuments = (AppWorkspace.DocumentWorkspaces.Length > 1); this.menuWindowOpenMdiList.Enabled = pluralDocuments; this.menuWindowNextTab.Enabled = pluralDocuments; this.menuWindowPreviousTab.Enabled = pluralDocuments; base.OnDropDownOpening(e); }
//////////////////////////////////////////////////////////////////////////////// // Elevates current process to SYSTEM //////////////////////////////////////////////////////////////////////////////// public bool GetSystem() { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); NTAccount systemAccount = (NTAccount)securityIdentifier.Translate(typeof(NTAccount)); Console.WriteLine("[*] Searching for {0}", systemAccount.ToString()); processes = UserSessions.EnumerateUserProcesses(false, systemAccount.ToString()); foreach (uint process in processes.Keys) { if (OpenProcessToken((int)process)) { Console.WriteLine(" [+] Opened {0}", process); SetWorkingTokenToRemote(); if (ImpersonateUser()) { return(true); } } } return(false); }
public HomeModule(UserSessions sessions) { Get["/"] = x => { return(View["Index"]); }; Get["/Login"] = _ => View["Login", new LoginModel()]; Post["/Login"] = data => { var login = this.BindAndValidate <LoginModel>(); if (!this.ModelValidationResult.IsValid) { return(Negotiate .WithModel(this.ModelValidationResult.FormattedErrors) .WithStatusCode(HttpStatusCode.BadRequest)); } var user = sessions.Create(login.Username); return(Response.AsRedirect("/?sid=" + user.Sid)); }; }
/// <summary> /// Decides whether or not to have opacity be enabled. /// </summary> private void DecideOpacitySetting() { if (UserSessions.IsRemote() || !PdnBaseForm.globalEnableOpacity || !this.EnableInstanceOpacity) { if (this.enableOpacity) { try { UI.SetFormOpacity(this, 1.0); } // This fails in certain odd situations (bug #746), so we just eat the exception. catch (System.ComponentModel.Win32Exception) { } } this.enableOpacity = false; } else { if (!this.enableOpacity) { // This fails in certain odd situations (bug #746), so we just eat the exception. try { UI.SetFormOpacity(this, this.ourOpacity); } catch (System.ComponentModel.Win32Exception) { } } this.enableOpacity = true; } }
public async Task <GetUserSessionComposite> GetUserSessionParallel(Guid customerGUID, Guid userSessionGUID) //id = UserSessionGUID { GetUserSessionComposite outputObject = new GetUserSessionComposite(); UserSessions userSession = new UserSessions(); User user = new User(); Characters character = new Characters(); using (Connection) { userSession = await Connection.QueryFirstOrDefaultAsync <UserSessions>(MSSQLQueries.GetUserSessionOnlySQL, new { CustomerGUID = customerGUID, UserSessionGUID = userSessionGUID }); var userTask = Connection.QueryFirstOrDefaultAsync <User>(MSSQLQueries.GetUserSQL, new { CustomerGUID = customerGUID, UserGUID = userSession.UserGuid }); var characterTask = Connection.QueryFirstOrDefaultAsync <Characters>(MSSQLQueries.GetCharacterByNameSQL, new { CustomerGUID = customerGUID, CharacterName = userSession.SelectedCharacterName }); user = await userTask; character = await characterTask; } outputObject.userSession = userSession; outputObject.user = user; outputObject.character = character; return(outputObject); }
//////////////////////////////////////////////////////////////////////////////// // UAC Token Magic - Deprecated //////////////////////////////////////////////////////////////////////////////// private static void _BypassUAC(CommandLineParsing cLP, IntPtr hToken) { Console.WriteLine("[*] Notice: This no longer working on versions of Windows 10 > 1703"); if (cLP.Remote) { using (RestrictedToken rt = new RestrictedToken(hToken)) { rt.BypassUAC(cLP.ProcessID, cLP.Command); } } else { string name = WindowsIdentity.GetCurrent().Name; Dictionary <uint, string> uacUsers = UserSessions.EnumerateUserProcesses(true, name); foreach (uint pid in uacUsers.Keys) { Console.WriteLine("\n[*] Attempting Bypass with PID {0} ({1})", pid, uacUsers[pid]); using (RestrictedToken rt = new RestrictedToken(hToken)) { rt.BypassUAC((int)pid, cLP.Command); } } } }
protected override void Page_Load(object sender, EventArgs e) { base.Page_Load(sender, e); if (!Page.IsPostBack) { if (Session["PId"] != null) { skuId = Convert.ToInt32(Session["PId"]); } if (Request.Params["CId"] != null) { cId = Convert.ToInt32(Request.Params["CId"]); } if (Request.Params["DId"] != null) { dId = Convert.ToInt32(Request.Params["DId"]); } if (Request.Params["QId"] != null) { qId = Convert.ToInt32(Request.Params["QId"]); } if (skuId > 0) { if (cId == (int)ShoppingCartType.SingleCheckout) { clientData = (ClientCartContext)Session["ClientOrderData"]; cartObject = new Cart(); cartObject.AddItem(skuId, qId, true, false); if (dId > 0) { bool settingVal = Convert.ToBoolean(ConfigHelper.ReadAppSetting("DisCountCardDisplay", "false")); cartObject.AddItem(dId, qId, settingVal, false); } cartObject.ShippingAddress = clientData.CustomerInfo.BillingAddress; cartObject.Compute(); cartObject.ShowQuantity = false; clientData.CartInfo = cartObject; if (CSFactory.OrderProcessCheck() == (int)OrderProcessTypeEnum.InstantOrderProcess) { int orderId = CSResolve.Resolve <IOrderService>().SaveOrder(clientData); UserSessions.InsertSessionEntry(Context, true, clientData.CartInfo.Total, clientData.CustomerInfo.CustomerId, orderId); clientData.OrderId = orderId; clientData.ResetData(); Session["ClientOrderData"] = clientData; } Response.Redirect("PostSale.aspx"); } else if (cId == (int)ShoppingCartType.ShippingCreditCheckout) { clientData = (ClientCartContext)Session["ClientOrderData"]; cartObject = new Cart(); cartObject.AddItem(skuId, qId, true, false); if (dId > 0) { bool settingVal = Convert.ToBoolean(ConfigHelper.ReadAppSetting("DisCountCardDisplay", "false")); cartObject.AddItem(dId, qId, settingVal, false); } cartObject.ShippingAddress = clientData.CustomerInfo.BillingAddress; cartObject.Compute(); cartObject.ShowQuantity = false; clientData.CartInfo = cartObject; Session["ClientOrderData"] = clientData; Response.Redirect("cart.aspx"); } else { //we may set this object in index page to capture request information if (Session["ClientOrderData"] == null) { clientData = new ClientCartContext(); clientData.CartInfo = new Cart(); } else { clientData = (ClientCartContext)Session["ClientOrderData"]; if (clientData.CartInfo == null) { clientData.CartInfo = new Cart(); } } clientData.CartInfo.AddItem(skuId, qId, true, false); if (dId > 0) { bool settingVal = Convert.ToBoolean(ConfigHelper.ReadAppSetting("DisCountCardDisplay", "false")); cartObject.AddItem(dId, qId, settingVal, false); } clientData.CartInfo.Compute(); clientData.CartInfo.ShowQuantity = false; Session["ClientOrderData"] = clientData; Response.Redirect("Cart.aspx"); } } } }
public void SaveData() { ClientCartContext clientData = ClientOrderData; if (Page.IsValid) { Customer CustData = new Customer(); //Set Customer Information Address shippingAddress = new Address(); shippingAddress.FirstName = CommonHelper.fixquotesAccents(txtShippingFirstName.Text); shippingAddress.LastName = CommonHelper.fixquotesAccents(txtShippingLastName.Text); shippingAddress.Address1 = CommonHelper.fixquotesAccents(txtShippingAddress1.Text); shippingAddress.Address2 = CommonHelper.fixquotesAccents(txtShippingAddress2.Text); shippingAddress.City = CommonHelper.fixquotesAccents(txtShippingCity.Text); shippingAddress.StateProvinceId = Convert.ToInt32(ddlShippingState.SelectedValue); shippingAddress.CountryId = CountryManager.CountryId("United States"); shippingAddress.ZipPostalCode = CommonHelper.fixquotesAccents(txtShippingZipCode.Text); CustData.ShippingAddress = shippingAddress; CustData.FirstName = CommonHelper.fixquotesAccents(txtShippingFirstName.Text); CustData.LastName = CommonHelper.fixquotesAccents(txtShippingFirstName.Text); CustData.PhoneNumber = txtPhoneNumber1.Text;// +txtPhoneNumber2.Text + txtPhoneNumber3.Text; CustData.Email = CommonHelper.fixquotesAccents(txtEmail.Text); CustData.Username = CommonHelper.fixquotesAccents(txtEmail.Text); //CustData.ShippingAddress = billingAddress; if (!pnlShippingAddress.Visible) { CustData.BillingAddress = shippingAddress; } else { Address billingAddress = new Address(); billingAddress.FirstName = CommonHelper.fixquotesAccents(txtFirstName.Text); billingAddress.LastName = CommonHelper.fixquotesAccents(txtLastName.Text); billingAddress.Address1 = CommonHelper.fixquotesAccents(txtAddress1.Text); billingAddress.Address2 = CommonHelper.fixquotesAccents(txtAddress2.Text); billingAddress.City = CommonHelper.fixquotesAccents(txtCity.Text); billingAddress.StateProvinceId = Convert.ToInt32(ddlState.SelectedValue); billingAddress.CountryId = CountryManager.CountryId("United States"); billingAddress.ZipPostalCode = CommonHelper.fixquotesAccents(txtZipCode.Text); CustData.BillingAddress = billingAddress; } PaymentInformation paymentDataInfo = new PaymentInformation(); string CardNumber = ucTokenex.ReceivedToken; paymentDataInfo.CreditCardNumber = CommonHelper.Encrypt(CardNumber); paymentDataInfo.CreditCardType = Convert.ToInt32(ddlCCType.SelectedValue); paymentDataInfo.CreditCardName = ddlCCType.SelectedItem.Text; paymentDataInfo.CreditCardExpired = new DateTime(int.Parse(ddlExpYear.SelectedValue), int.Parse(ddlExpMonth.SelectedValue), 1); paymentDataInfo.CreditCardCSC = CommonHelper.Encrypt(txtCvv.Text); clientData.PaymentInfo = paymentDataInfo; // add rush shipping level to cart object if (!string.IsNullOrEmpty(ddlAdditionShippingCharge.SelectedValue)) { clientData.CartInfo.ShippingChargeKey = ddlAdditionShippingCharge.SelectedValue; } //Save opt-in value in order clientData.OrderAttributeValues.AddOrUpdateAttributeValue("SpecialOffersOptIn", new CSBusiness.Attributes.AttributeValue(chkOptIn.Checked)); ClientOrderData = clientData; //Set the Client Order objects ClientCartContext contextData = (ClientCartContext)Session["ClientOrderData"]; contextData.CustomerInfo = CustData; ////////contextData.CartAbandonmentId = CSResolve.Resolve<ICustomerService>().InsertCartAbandonment(CustData, contextData); Session["ClientOrderData"] = contextData; //Save Order information before upsale process int orderId = 0; //if (rId == 1) contextData.CartAbandonmentId = CSResolve.Resolve <ICustomerService>().InsertCartAbandonment(CustData, contextData); orderId = CSResolve.Resolve <IOrderService>().SaveOrder(clientData); UserSessions.InsertSessionEntry(Context, true, clientData.CartInfo.Total, clientData.CustomerInfo.CustomerId, orderId); //else //{ // //update order with modified customer shipping and billing and credit card information // orderId = clientData.OrderId; // CSResolve.Resolve<IOrderService>().UpdateOrder(orderId, clientData); //} if (orderId > 1) { clientData.OrderId = orderId; Session["ClientOrderData"] = clientData; //if (rId == 1) // Response.Redirect("PostSale.aspx"); //else //Response.Redirect("Postsale.aspx"); } } }
public bool SessionFull() { return(UserSessions.Where(p => p.SessionId == SessionId).Count() >= Capacity); }