Checking how much time passed from creating objectid in mongodb - javascript

I'm building an app that allows the user to reset his password.
The process is really simple .The user enters his email address and I sending him a link with the number of the new objectid that was created.
For exemple -> /reset-password?x=55555444475d41a000001.
After clicking the link he reaches other page and then I want to check if 24 hours have passed from the time he got the link?and yes i know there is function called "getTimestamp" but how to use it..?
get: function (request, response) {
???????
},

You can set a "creation_date" property in your object when you create it, like this:
obj = {
id: "xxxxxx...",
creation_date: new Date()
...
}
Then you store the object somewhere in your server, and then when the user opens the link with the id of the object you will do something like this to check if the object has been created more than 24hours ago:
var now = new Date();
if (now - obj.creation_date > 86400000) {
// more than 24h (86400000ms = 24h)
// do something
}

Actually reading the JavaScript API docs for ObjectId might help.
Checking wether 24 hours have passed since the creation of the object should be as easy as
var now = new Date();
/* Subtract the milliseconds a day lasts from the current time.
* If the timestamp of the ID converted to msecs after epoch is smaller
* the ObjectId was created before that.
*/
if ( myId.getTimestamp() < ( now.getTime() - 86400000 ) {
console.log("24 h have passed since creation");
}
else {
console.log("24 h haven't passed since creation");
var passed = new Date( now - myId.getTimestamp() );
console.log(passed.getUTCHours()+":"+passed.getUTCMinutes()+" have passed.");
}
Note: I downvoted your question as it would have been easily solvable by googling "MongoDB ObjectId getTimestamp JavaScript api", you didn't show any sign of working on the problem yourself and didn't bother to ask a specific question. May I politely suggest reading ESR's How To Ask Questions The Smart Way, especially the chapter about StackOverflow?

Related

Firestore limit read snapshot by current time

I want to display the last 10 messages of a conversation. Then as the conversation progresses, obviously, I need to show those messages as well:
I am doing something like this:
//function a
db.collection("conversations/" + messageID + "/messages").orderBy("timestamp", "desc").limit(10).
get().then(function(querySnapshot) {
const time = Date.now();
//call function b and pass time as a parameter
//function b
db.collection("conversations/" + messageID + "/messages").where("timestamp", ">=", time)
What security rules will allow me ensure that time in function b is somewhat close to the current time?
Thanks!
You can use request.time for when the specific document was created, which is type of Timestamp, as stated in the Rules documentation.
I found this StackOverflow post which might help as well.

Replace builtin Date without being able to recover original constructor

I want to replace Date inside a JavaScript VM (V8 but this is not specific to V8), and make it impossible to access the original Date constructor. This is meant to be one part of a defence against timing attacks like Spectre with multi-tenant JavaScript running in the same process (but different JavaScript VM.) The idea is to deny access to high resolution timers. Cloudflare does this in their Workers, for the same reason. Time is advanced only when IO happens, not during computation. I know there are other ways to construct a timer, but I'm just focused on Date for this question.
I think this can be done in pure JavaScript, and this is my attempt. Is there a way to get the original Date constructor back after running this? Is there a way this differs functionally from the builtin Date - something that could break backwards compatibility?
// Current UNIX timestamp in milliseconds, but that we set manually on each call to runTasks.
// not advancing time during computation is one of our defenses against Spectre attacks.
let NOW = Date.now();
export function setDate(unixTimestampMillis) {
NOW = unixTimestampMillis;
}
Date = function (BuiltinDate) {
function Date(...args) {
if (new.target === undefined) {
// This is the deprecated naked Date() call which returns a string
return (new BuiltinDate(NOW)).toString();
}
// Otherwise it was the constructor called with new
if (args.length === 0) {
// Return the "current" time.
return new BuiltinDate(NOW);
}
// Build a Date with the specified datetime
return new BuiltinDate(...args);
}
// Make a copy of the BuiltinDate "class" and replace the constructor,
// It needs to be impossible for the user to grab an reference to BuiltinDate.
Date.prototype = BuiltinDate.prototype;
BuiltinDate.prototype.constructor = Date;
// Add the static methods now(), UTC(), and parse() - all of which return a numeric timestamp
function now() {
return NOW;
}
Date.now = now;
Date.parse = BuiltinDate.parse; // returns a number
Date.UTC = BuiltinDate.UTC; // returns a number
return Date;
}(Date);

Server-Side and Time-Specific script execution

I have a list of dates in an array(for now we can say that the dates are sorted). I want to have a script execute when the date matches a date in the array. My issue is figuring how to make this work on its own. I would like to have a server somehow act like an alarm clock that can run a script for a scheduled date and time. If anyone could help with suggestions to make this work I would appreciate it.
set date >>> if (currentDate == set date) >>> run script for the respective data
Please ask if you need clarification.
The way to do this with parse is a class with a date attribute. Create one object per date in your array of dates (they needn't be sorted).
Create a scheduled job that upon running, query's the class for the first date equal to the current date. If one is found, do whatever you want to do when an alarm is triggered.
So, something like...
Parse.Cloud.job("checkStatus", function(request, status) {
var today = new Date();
today.setHours(0, 0, 0, 0);
var tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
var query = new Parse.Query("MyAlarmClass");
query.greaterThanOrEqualTo('theDateAttribute', today);
query.lessThan('theDateAttribute', tomorrow);
return query.first().then(function(anAlarm) {
if (anAlarm) {
// do whatever should be done on the alarm
} else {
// do nothing
}
}).then(function() {
status.success();
}, function(error) {
status.error(JSON.stringify(error));
});
});
Schedule this to run at least twice per day (or faster than whatever resolution you need on the alarms).

Compare Server Time and Browser Time

My table that has 3 columns: FileName, LastUpdateTime, and a Restart button.
I need to display the restart button only if the last update time is more than 20 min ago. I get the last update time from the server. d = new Date() gives the local browser time but the lastUpdateTime is coming from the server. Server is in the different time zone than the clients browser.
The following code works if both server and browser are in the same time zone. Do you have any suggestions on how solve this if the server and browser are in a different time zone?
This application supposed to run anywhere in US and Europe.
var lastUpdatedTime = (gridData[i].LastTimeUpdated);
var d = new Date();
//deducting 20 min from current time
var deductTwenty = d.setMinutes(d.getMinutes() - 20);
var parsedupdatetime = Date.parse(lastUpdatedTime);
// If the last update time is not 20 ago, hide it.
if (parsedupdatetime > deductTwenty) {
newrestartButton.hide();
}
Use .NET in your .cshtml file to get the date server-side. Assuming you use MVC (since you tagged this question kendo-asp.net-mvc).
#{
var deductTwenty = DateTime.Now.AddMinutes(-20);
}
<script>
var jsDeductTwenty = new Date(#deductTwenty.Year, #deductTwenty.Month-1, #deductTwenty.Day, #deductTwenty.Hour, #deductTwenty.Minute);
</script>
Result:
What's probably going wrong is the server date parsing. Take a look at the Date.parse function spec - and make sure your server is returning something that will get parsed correctly like an ISO8601 formatted date.
You have to convert your lastUpdatedTime with client timezone, means you should convert server time to client time when subtracting date with 20 mins. You can use momentjs, moment-timezone and jstimezonedetect to achieve this.
Your code should be like this
// get current client timezone with jstimezonedetect
var currentTz = jstz.determine().name(); // e.g "Europe/London"
// parse last update time to moment object and change its timezone
var lastUpdateTime = moment(lastUpdatedTime, "M/DD/YYYY hh:mm a").tz(currentTz);
// create date using moment and deduct 20 mins from it
var deductTwenty = moment().subtract(20, 'minutes');
// now compare
if (lastUpdateTime > deductTwenty) {
newrestartButton.hide();
}
Hope this help.

Expiring a javascript variable?

I saved some data returned from ajax in javascript variable. I would like to invalidate this variable after some time period, say one hour.
I can potentially write some setTimeout functions to handle this, but I just feel this is not optimal.
Another way is to save in cookie and set expiration, but the overhead may be unnecessary.
Is there other way that can handle this situation more elegantly?
Assuming the actual variable actually exists that long (the page stays open), just do what every cache does: save a timestamp and check for it.
var cache = { timestamp : null, data : null };
function setData(data) {
cache.data = data;
cache.timestamp = new Date;
}
function getData(maxAge) {
if (/* compare cache.timestamp to now - maxAge */) {
return null;
}
return cache.data;
}
Keep a variable that indicates when the value expires.
var foo = "bar";
var foo_expires_on = new Date(new Date().getTime() + 60 * 60 * 5); // +5 hours
deceze's answer is a more formal (monad) implementation.

Categories

Resources