How to get a date in a link? MVC 5 - c#

I'm implementing a web page, doing the homepage, I have a button that the user uses in order to recover his password (due to forgetting it). Then my program sends him a link to his e-mail after verifying it in the database. This link let's the user reset his password.
I want to add a date to the link, so that if when the user gets redirected to the reset pass page, it's date is verified and if it is higher than 1 hour it tells the user he needs to re-do the process.
Do I use,
DateTime saveNow = DateTime.Now;?
Sorry for the bad English, thank you

You can use DateTime.Now.Ticks. This gives you an integer that can easily be posted in an url and then be converted to a DateTime again.

Ok, this doesn't quite answer your question, however there is a better way of handling password reset timeouts. If you are using the following code in your action:
WebSecurity.GeneratePasswordResetToken(emailAddress);
You can also pass in a second parameter which specifies how long the password token is valid for in minutes otherwise the default time out is 24 hours.
From there you can validate the token is valid in a bool type action by using something similar to the below:
var repository = repository.GetByPasswordResetToken(resetToken);
isValid = membership != null && repository.PasswordVerificationTokenExpirationDate > DateTime.Now;
This is based on the assumption you are utilising WebMatrix within your server side logic.

Related

C# How can I mark a URL invalid/obsolete?

I have a URL something like below. The URL gets generated each time, basically links are ephemeral. I want to mark this link as obsolete/invalid once it has been accessed in a browser. The second time when we access this URL, it should say invalid link. URL format is having an auth token. How can we do this in C#?
http://example.com/ui/landing?authToken=wwlC7bjUugIT5lo8uuX8d2wQhS__k6l80fSwPKzFuJWwDANgGVQtNT6C3q1lGcNk1p_ApBdurzPTayOzaGb6YibAdTKfzBdhKCcTNZwO54mg1KU_lPD6Zmg
Link must be marked as invalid once used.
I don't think this can be done just by code.
I think a workaround would be to store the links on your server (database, file or watever). When someone uses the link you can check on that db if the link has been used and mark it as "used" if not.
Something like:
id
Link (string)
Used (boolean)
1
https://stack...
1
2
https://stack...
1
3
https://stack...
0

Find the referring URL and parse it

Okay my problem is there are two websites with two different servers. What I'm trying to do is write some of the buttons for website 1, but on a page on my server (website 2).
So to do this the approach is
User clicks on button from website 1.
User is redirected to website 2.
I need to know what page they came from so I know what product they are looking at. Which will be done by getting the referrer URL.
I then need to parse the URL's productID's number.
example URL: website1.com/ProductDetails/?referrerPage=1&productID=#######&tab=Tile
I know that I need to use this piece of code to store the referrer URL in a string:
myReferrer = Request.UrlReferrer.ToString();
I don't really know where to place it tho. I'm guessing in my .cs file where my button is?
protected void btnEstimate_Click(object sender, EventArgs e)
{
connection strings
{
does stuff
{
does stuff
}
So my question is how do I get the referring URL, and then parse out the item ID?
Thanks for the help in advance. If anything is unclear please ask... this is my first time asking a question so I may be unclear. Thanks!
This should give you what you want:
Making Sense of ASP.NET Paths
Note that a fully qualified URL including querystring and extra path is a Uri instance rather than string. You can use the UriBuilder.Query Property to extract the query string parameter(s):
You need to parse the URI in the Page_Load method of the receiving site's page.
UriBuilder.Query Property
There's a server variable called HTTP_REFERER. You can access it with Request.ServerVariables("HTTP_REFERER")
It's misspelled, I know, but that's how you really need to call the server variable.
Your referrer server variable is only going to be populated if the user clicks on a link. AFAIK if you redirect, that variable is going to be empty.
Wikipedia Referer Article

Showing webpage if user just changed password

I am using directory services to get the last date the user changed his password. If this date was within 5 minutes I want to show a particular webpage when the user logs in. So for example a user gets prompted to change password. Rigth after changing windows password they login, because the change was within the 5 minute time frame the user will be presented with say google.com. If the user logs off and logs back in tomorrow nothing would happen. Here are some ideas I had but don't work.
if(datepasswordchanged < datepasswordchanged.AddMinutes(5))
However this would happen everytime.
I also had
if(DateTime.Now.AddMinutes(-5) == datepasswordchanged)
however this would only happen if it was exactly 5 minutes ago. How could I specify a range?
if(DateTime.Now < datepasswordchanged.AddMinutes(5))
will be "If current time is less than five minutes after time in variable."

Optimal way to cache time of day description

What is the best method to cache the following? I am creating an intranet web application template that will display the message, e.g., Good Morning, Justin Satyr! near the top of my master page header. Obviously, I will have to determine whether to show Morning, Afternoon or Evening. For clarity, my code is below:
string partOfDay;
var hours = DateTime.Now.Hour;
if (hours > 16)
{
partOfDay = "evening";
}
else if (hours > 11)
{
partOfDay = "afternoon";
}
else
{
partOfDay = "morning";
}
I do not want to re-determine this on each page load because that seems moderately redundant and because I have to poll a SQL server to retrieve the user's full name. What is the best way to cache this information? If I cache it for the length of the session, then if the user begins using the application at 11:00 AM and finishes at 3:00 PM, it will still say Good Morning.
Is the best thing to do simply re-determine the M/A/E word each page load and cache the person's full name for the session? Or is there a better way?
I would just keep the user name in the Session object, the rest honestly is not worth caching and checking if it is out of date etc., just re-run it on each page - provided you put the implementation into a common library /class so you keep your code DRY.
In my opinion there is absolutely no need to cache the part of day. User information can be made available in the Session.
If you are talking in ASP.NET MVC context, you can use System.Web.Helpers namespace, where you can find WebCache helper. Than you need to calculate minutes to time of day_time will be changed and call WebCache.Set method with paramters: value="your string", minutesToCache=calculated_value.
Old, I know, but I don't cache mine, due to the obvious reason that the users time may change during the session. I store their calculated time in my session (calculates based on their timezone), and then use this code at the top of all pages:
<strong>#string.Format("Good {0}, ", SessionManager.GetUserCurrentDate().Hour > 16 ? "Evening" : SessionManager.GetUserCurrentDate().Hour > 11 ? "Afternoon" : "Morning") + SessionManager.GetDisplayName())</strong>
Works well for me!

How to implement Stack Overflow's "are you a human" feature?

On this site if you do too many clicks or post comments too fast or something like that you get redirected to the "are you a human" screen. Does anybody know how to do something similar?
It's almost certainly a heuristic that tries to "guess" that a user is some form of automated process, rather than a person, for example:
More than "x" requests to do the same thing in a row
More than "x" actions in a "y" period of time
Ordinarily the "x" and "y" values would be formulated to be ones that it would be unlikely for a "real person" to do, like:
Editing the same answer 5 times in a row
Downvoting 10 questions within 1 minute
Once you've got your set of rules, you can then implement some code that checks them at the start of each request, be it in a method that's called in Page_Load, something in your masterpage, something in the asp.net pipeline, that's the easy bit! ;)
Here is a very nice Captcha Control for asp.net that first of all you need
http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx
Then you can use it together with this idea that try to find the dos attacks
http://weblogs.asp.net/omarzabir/archive/2007/10/16/prevent-denial-of-service-dos-attacks-in-your-web-application.aspx
be ware of a bug in this code in line if( context.Request.Browser.Crawler ) return false;, its must return true, or totally remove it for sure.
and make it your compination for the clicks, or submits.
If a user make too many clicks on a period of time, or many submits, then you simple open the capthaControl, and if the clicks are by far too many, then triger the dos attact. This way you have 2 solution in one, Dos attact prevent, with captcha at the same time.
I have made somthing similar my self, but I have change the source code of both, a lot to feet my needs.
One more interesting link for a different code for the dos attack.
http://madskristensen.net/post/Block-DoS-attacks-easily-in-ASPNET.aspx
Hope this help you.
At a guess...
Write a HTTP handler that records requests and store them in session.
When a new request comes in, check to see how many requests are stored (and expire old ones).
If the amount of requests in the past few minutes exceeds a given threshold, redirect the user.
If you're doing this in ASP.NET webforms, you could do this check on the site master page, ( or write a IHttpHandler).
If you're using an MVC framework, you could write a base controller that does this check for every action.
With rails, you could write a before_request filter.
With asp.net MVC, you could write a [ActionFilterAttribute] attribute
You should have a session to track the user activity.
In session you can have counter for commenting and posting like:
(pseudo code instead of C#, sorry :)
if (post_event) {
posts_during_1_minute_interval++;
if (time_now-reference_time > 1_minute) {
reference_time = time_now;
posts_during_1_minute_interval=0;
}
}
...
if (posts_during_1_minute_interval > 10) redirect("/are-you-human.htm");
where on are-you-human.htm page you can have recaptcha, as they have here on StcakOverflow.com
see also:https://blog.stackoverflow.com/2009/07/are-you-a-human-being/
just check how many hit / minutes you get from a specific ip or session or whatever and decide what are your preferred threshold and your good to go
I'd also check the user agent header of the request - if it doesn't look like a popular browser (or is empty) then throw the "are you a human?" page.

Categories

Resources