I only seem to be able to set one Cookie - HttpCookie, asp.net - asp.net

I have a system with a two-stage login.
Stage one is a Company Login which identifies the Company using my system.
Stage two is a Staff Login where a member of staff belonging to the above company logs in.
In both stage an option is offered to save certain login details (Location/Company but not password)
A user should be able, if they wish, to set the Company Login Cookie, but not the Staff Cookie, there is no need to set a Staff Cookie without a Company Cookie, although it doesn't really matter if they do!
Stage one login, amongst database checks etc does this:
If SaveCookie Then
Dim loginCookie As New HttpCookie("LogInCompany")
loginCookie.Values("database") = Database
loginCookie.Values("savedKey") = SavedKey
loginCookie.Values("samCompanyId") = CompanyId
loginCookie.Values("samCompanyName") = Common.htmlDecode(CompanyName)
loginCookie.Expires = Date.Now.AddDays(7)
HttpContext.Current.Response.Cookies.Add(loginCookie)
End If
Then stage two does this:
If SaveCookie Then
Dim loginCookie As New HttpCookie("LogInStaff")
loginCookie.Values("locationId") = locationID
loginCookie.Expires = Date.Now.AddDays(7)
HttpContext.Current.Response.Cookies.Add(loginCookie)
End If
Obviously they are entirely separate functions, so I don't think the variable naming being the same is the issue.
What happens is:
Company Login successful > Company Cookie is Saved, User proceeds to
User Login User Login > User Cookie is Saved, BUT the Company Cookie
is deleted.
This is using Chrome, I haven't checked other browsers but Chrome is the most important to me.
I know that this is definitely what is happening as I have checked in the Chrome Console, the Cookies are added and removed as per description above.
Can someone help point out where I am going wrong here?
EDIT - Nothing wrong with this code!
Argh... after a day of messing about with this, it turns out that the Cookie was being cleared by an unexpected, and caught, error in a different, but related section of code! This question can be closed if required, or left ...?

Related

Paypal Processing - Need to grab TransactionId, CorrelationId and TimeStamp

Current Project:
ASP.NET 4.5.2
MVC 5
PayPal API
I am using this example to build myself a PayPal transaction (and yes, my code is virtually identical), as I do not know of any other method that will return the three values in the title.
My main problem is that, the example I am utilizing is much more concise and compact than the one I used for a much older Web Forms application, and as such, I am unsure as to where or even how to grab the three values I need.
My initial thought was to do so right after the ACK, and indeed I was able to obtain the CorrelationId as well as the TimeStamp, but because this was prior to the user being carted off to PayPal’s site (sandbox in this case -- see the return new PayPalRedirect contained within the if), the TransactionId was blank. And in this example, PayPal explicitly redirects the user to a Success page without returning to the Action that sent the user to PayPal in the first place, and I am not seeing any GET values in the URL at all aside from the Token and the PayerId, much less ones that could provide me with the TransactionId.
Suggestions?
I have also looked at the following examples:
For ASP.NET Core, was unsure how to adapt to my current project particularly due to appsettings.json, but it looked quite well done. I really liked how the values were rolled up in lists.
For MVC 4, but I couldn’t find where ACK was being used to determine success or successwithwarning so I couldn’t hook into that.
I have also found the PayPal content to be like trying to drink from a fire hose at full blast -- not only was the content was hopelessly outdated (Web Forms code, FTW!) but there was also so many different examples it would have taken me days to determine which one was most appropriate to use.
Any assistance would be greatly appreciated.
Edit: my initial attempt at modifying the linked code has this portion:
values = Submit(values);
var ack = values["ACK"].ToLower();
if(ack == "success" || ack == "successwithwarning") {
using(_db = new ApplicationDbContext()) {
var updateOrder = await _db.Orders.FirstOrDefaultAsync(x => x.OrderId == order.OrderId);
if(updateOrder != null) {
updateOrder.OrderProcessed = false;
updateOrder.PayPalCorrelationId = values["CORRELATIONID"];
updateOrder.PayPalTransactionId = values["TRANSACTIONID"];
updateOrder.PayPalTimeStamp = values["TIMESTAMP"];
updateOrder.IPAddress = HttpContext.Current.Request.UserHostAddress;
_db.Entry(updateOrder).State = EntityState.Modified;
await _db.SaveChangesAsync();
}
}
return new PayPalRedirect {
Token = values["TOKEN"],
Url = $"https://{PayPalSettings.CgiDomain}/cgi-bin/webscr?cmd=_express-checkout&token={values["TOKEN"]}"
};
}
Everything within and including the using() is my added content. As I mentioned, the CorrelationId and the TimeStamp come through just fine, but I have yet to successfully obtain the TransactionId.
Edit 2:
More problems -- the transactions that are “successful” through the sandbox site (the ReturnUrl is getting called) aren’t reflecting properly on my Facilitator and Buyer accounts, even when I do payments straight from the buyer’s PayPal account (not using the Credit Card). I know I am supposed to see transactions in the Buyer’s account, either through the overall Dev account (Accounts -> Profile -> balance or Accounts -> Notifications) or through the Buyer’s account in the sandbox front end. And yet -- multiple transactions returning me to the ReturnUrl path, and yet no transactions in either.
Edit 3:
Okay, this is really, really weird. I have gone over all settings with a fine-toothed comb, and intentionally introduced errors to see where things should crap out. It turns out that the entire process goes swimmingly - except nothing shows up in my notifications and no amounts get moved between my different accounts (Facilitator and Buyer). It’s like all my transactions are going into /dev/null, yet the process is successful.
Edit 4: A hint!
In the sandbox, where Buyer accepts the transaction, there is a small note, “You will be able to review the transaction before completing it” or something like that -- suggesting that an additional page is not coming up and that the user is being uncerimoniously dumped back to the success page. Why the success page? No clue. But it’s happening.
It sounds like you are only doing the first part of the process.
Express Checkout consists of 3 API calls:
SetExpressCheckout
GetExpressCheckoutDetails
DoExpressCheckoutPayment
SEC generates a token, and then you redirect to PayPal where the user signs in and reviews the transactions before agreeing to pay.
They are then sent to the ReturnURL included in your SEC request, and this is where you'll call GECD in order to obtain all the buyer details that are now available since they signed in.
Using that data you can complete the final DECP request, which is what finalizes the procedure. No money is actually processed until this final call is completed successfully.

Registering new users via OAuth2 : what to set as user identifier for future log ins?

I have managed to successfully configure this. The problem is, when I change the lines below :
//I have set all requested data with the user's username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
into the information I want to retrive, such as real name, email, my generated password etc, when I click the Login button for Facebook per say, I am asked again if I want to connect with my local testing site.
From what I understand, in the documentation I linked above, this :
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
is the line that checks if the user exists or not, and the initial code by itself, sets either facebook_id or twitter_id (this is how I save them) as a new User *username*. If I change the line
$user->setUsername($username); //same as facebook/twitter _id
into
$user->setUsername(setProperUsername()); //sets a proper unique username
Then everytime I try to login I get the "Register" message. So, I have a general idea of how it works but I am having a hard time understanding some things:
1. When I have registered with Facebook and I login with twitter, I register again, no knew row is created, but missing twitter_id fields are updated/populated, username stays intact. How come HWI/FOSUB knows I am the same person when my previous data were from Facebook not Twitter?
2. If there is a global way of knowing I am the same person, what data from the $response object should I use as a key to identify already registered users?
After testing a lot with this, I have the answer if anyone runs into this type of situation
Check your default_target path, make it so it is /profile, /account etc, don't default to login again. Also, if a user is already logged in, do not make him access your login page. This was why my data was being updated. I was basically logged in with my Facebook account and registering with my Twitter account too.
No, there is no global way of knowing I am the same person. The $response object sent me a unique ID for that specific user according to the provider policy. You might use this to identify already registered users and log them in.

Membership.GetAllUsers in ASP.Net

I am building a User Management page and am trying to retrieve both the number of registered users and the number currently online using the following code.(FYI...I am using mySQL as the membership provider) There are currently 4 users in the asp_net_users table so at least 4 should come up on the GetAllUsers request.
lblOnlineUsers.Text = Membership.GetNumberOfUsersOnline().ToString()
lblTotalUsers.Text = Membership.GetAllUsers.Count.ToString()
The labels are always blank. Even if I put a MsgBox(Membership.GetAllUsers.Count.ToString()) in the pageload, that msgbox never comes up. Any thoughts on what I'm doing wrong here?
You valid your user credential with ValidateUser or UpdateUser method , and you re-test

ASP.NET see if member is online

I'm developing a ASP.NET site in umbraco, and I need to see if a member with a given ID is online. How can I do that?
So far, I've tried to get the member by so:
Member m = new Member(myID);
But how can I check, if the returned member is logged in or not?
EDIT: I followed the link, and extracted the following code from it:
var users = Membership.GetAllUsers();
foreach(MembershipUser user in users){
Response.Write(user.IsOnline.ToString() +"<br/>");
Response.Write(user.LastActivityDate.ToString() + "<br/>");
Response.Write(user.LastLoginDate.ToString() + "<br/>");
}
However, the returned result shows that the property isOnline is true for every member, even though they're not online. I'm aware that it is because of the fact that the LastActivityDate updates automatically whenever I access the user, as stated here: Is it possible to access a profile without updating LastActivityDate?. Unfortunately, I don't get the solution to that question.
I've also tried to access the member by:
MembershipUser m = Membership.GetUser('myID',false);
But even though I put false as the second parameter, the LastActivityDate still updates. How can I work around this? I should note that I work with ASP.NET v. 4.0 in umbraco 4.7 at a localhost.
Thanks!
:EDIT END
Best regards,
Brinck10
You can use the MembershipUser.IsOnline Property that show true if the current date and time minus the UserIsOnlineTimeWindow property value is earlier than the lastActivityDate for the user.
There is an example on the MSDN page.
relative:
Proper 100% IsOnline implementation for asp.net membership
How to check in ASP.NET if the user is online?
asp.net custom membership provider: IsOnline property
The solution to the problem:
(1) I made a costum field in the membertype called lastActivityDate.
(2) I placed a macro on the masterpage, update the member's lastActivityDate to the current time given that the member was online.
(3) On the validation page I checked if the lastActivityDate + CostumBuffer was bigger than DateTime.Now.
Thanks for your patience Aristos.

asp.net multiple users?

I have an asp.net c# web application where a user can log in and see his schedule for the last week, which is stored in a remote database. Logging into the site consists of just an SQL check to see if the username and password matches the uname & pass records in the database. Once logged in, they can manipulate the time entries for the schedule, etc. While debugging, I logged in as two different users. User B had all of user A's stuff on his form. I wrote the program like I was writing a regular c# app, and didn't really give any thought to multiple people using the website at the same time. I guess I thought that instance handling would be automatic? I've only been working with asp.net for a week or so, and don't have much support.
My main question is, if I have multiple users on my site at the same time, how do I keep their sessions separate?
update - after adding Session variables
This is my sql statement to get user information. Now, using session variables:
string sqlquery = "SELECT FirstName, LastName, OperatorID FROM operators WHERE EmpID = '" + sql + "'";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["EobrConnectionString"].ConnectionString))
{
conn.Open();
using (MySqlCommand comm = new MySqlCommand(sqlquery, conn))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(comm))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Session["Fname"] = dr[1].ToString();
Session["Lname"] = dr[2].ToString();
Session["opID"] = dr[3].ToString();
}
}
}
}
In the main menu page I have this:
protected void Page_Load(object sender, EventArgs e)
{
firstname = Session["Fname"].ToString();
lastname = Session["Lname"].ToString();
lblwelcome.Text = "Welcome, " + firstname + " " + lastname + ", make your selection below.";
}
When User A logs in, they see their name "Frank Drebbin". When User B logs in they see their name, "Jake Gaston". But now, if I reload the first users page, they see the name as "Jake Gaston".
You need to use seperate browsers. You're using sessions to identify users, and sessions are matched to a cookie in your browser From your comments above, here's what happens
log in as steve -> session created -> steve stored as username -> cookie returned to browser
in a new window, log in as frank -> session already exists, rename username to frank.
in 1st window refresh. -> session username no frank -> return data based on that username.
New IE windows all share the same context. this means if 1 window gets a cookie, they all do. There are 2 ways around this (actually 3).
Use physically different machines
Use 2 broswers, eg IE & Firefox
In IE press alt to get the menu, then click new session from the file menu. This makes a physically separate window that won't share cookies (although there's nothing to indicate this to you)
Having done the above, try again logging in as Steve & Frank & you should see they don't interfere with each other.
I would guess the problem is that, while the sessions are kept separately (you are storing things in Session, right?), the queries that load data from the database are not taking the username into account.
Have a look at the SQL query that loads tasks and see if you include the username (or a user ID) in that query. Feel free to post the query if you need help looking at it.
So to directly answer your main question, if you store things in Session, they will be properly isolated from other sessions. However, wrong data in, wrong data out.
EDIT:
Use another browser to test this, you can't use the same browser in another tab, or the same browser in another window, it almost will be the same session
If you are using "Session" to save user's data then they are separated, that means you should store any per-user data into "Session" or cookies.
NOTE:
You should maintain concurrency http://msdn.microsoft.com/en-us/library/cs6hb8k4(v=vs.80).aspx
The solution is very simple( USER DIFFERENT BROWSERS SIMONTANIOUSLY) like IE, Firefox, Chrome etc........
You are not using transact SQL so need to bother about concurrency,
but when u login the current browser create a session if you use the same browser it will still has that session,
If you use another browser the browser will have the session but the value wont be the same.
e.g.
Each mobilephones have different browsers now if you have 100 mobile phones that would mean you can store 100 same USER session but all will have different values varies on the data you providing or operation handles.
Hope this help you understand.

Resources