SetTimeout is not working in Mongoose schema post middlewareReferencing another schema in MongooseSetting expiry time for a collection in mongodb using mongooseHow can I pass a parameter to a setTimeout() callback?What is Node.js' Connect, Express and “middleware”?How do I update/upsert a document in Mongoose?Mongoose Changing Schema FormatSub documents inheritance in mongoose and mongoose-schema-extendMongoose middleware post update not workingObject.assign() Issues on Mongoose SubDocument SchemaMongoose schema validations not running on updateMongoose pre.remove middleware of objects in array are never calledCan I perform mongoose update from post save middleware?

How seriously should I take a CBP interview where I was told I have a red flag and could only stay for 30 days?

Linear Programming with additional "if-then"/"Default to zero" constraints?

What was the relationship between Einstein and Minkowski?

Can a new chain significantly improve the riding experience? If yes - what else can?

Can I toggle Do Not Disturb on/off on my Mac as easily as I can on my iPhone?

Sol Ⅲ = Earth: What is the origin of this planetary naming scheme?

Glue or not to glue boots

Is there a reliable way to hide/convey a message in vocal expressions (speech, song,...)

The Planck constant for mathematicians

Were Roman public roads build by private companies?

Gas pipes - why does gas burn "outwards?"

Is there an inconsistency about Natasha Romanoff's middle name in the MCU?

Telling my mother that I have anorexia without panicking her

Gravity on an Orbital Ring

Why don’t low light cameras just use bigger sensors?

How are chord ratios developed exactly?

Is English tonal for some words, like "permit"?

Why did it become so much more expensive to start a university?

Where can I find vomiting people?

Where can I get an anonymous Rav Kav card issued?

Random point on a sphere

The Voice That Beckons

How to run Death House for 3 new players with no healer?

Is the union of a chain of elementary embeddings elementary?



SetTimeout is not working in Mongoose schema post middleware


Referencing another schema in MongooseSetting expiry time for a collection in mongodb using mongooseHow can I pass a parameter to a setTimeout() callback?What is Node.js' Connect, Express and “middleware”?How do I update/upsert a document in Mongoose?Mongoose Changing Schema FormatSub documents inheritance in mongoose and mongoose-schema-extendMongoose middleware post update not workingObject.assign() Issues on Mongoose SubDocument SchemaMongoose schema validations not running on updateMongoose pre.remove middleware of objects in array are never calledCan I perform mongoose update from post save middleware?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am trying to update forgetpassword_token to null in mongodb document after 24 hours of generating forgetpassword_token. So I am using Mongoose schema middleware and setTimeout, but setTimeout is not working.



I have tried to implement async await which is also not working as per my result.



CompanySchema.post('updateOne',true, function(doc,next)
next();
setTimeout(this.update(, $set: forgetpassword_token: null ).then(result=>
console.log(result);
),10000000000);
);









share|improve this question


























  • setTimeout takes a function as a parameter. However, you're passing a Promise to it.

    – Sergeon
    Mar 28 at 9:41

















1















I am trying to update forgetpassword_token to null in mongodb document after 24 hours of generating forgetpassword_token. So I am using Mongoose schema middleware and setTimeout, but setTimeout is not working.



I have tried to implement async await which is also not working as per my result.



CompanySchema.post('updateOne',true, function(doc,next)
next();
setTimeout(this.update(, $set: forgetpassword_token: null ).then(result=>
console.log(result);
),10000000000);
);









share|improve this question


























  • setTimeout takes a function as a parameter. However, you're passing a Promise to it.

    – Sergeon
    Mar 28 at 9:41













1












1








1








I am trying to update forgetpassword_token to null in mongodb document after 24 hours of generating forgetpassword_token. So I am using Mongoose schema middleware and setTimeout, but setTimeout is not working.



I have tried to implement async await which is also not working as per my result.



CompanySchema.post('updateOne',true, function(doc,next)
next();
setTimeout(this.update(, $set: forgetpassword_token: null ).then(result=>
console.log(result);
),10000000000);
);









share|improve this question
















I am trying to update forgetpassword_token to null in mongodb document after 24 hours of generating forgetpassword_token. So I am using Mongoose schema middleware and setTimeout, but setTimeout is not working.



I have tried to implement async await which is also not working as per my result.



CompanySchema.post('updateOne',true, function(doc,next)
next();
setTimeout(this.update(, $set: forgetpassword_token: null ).then(result=>
console.log(result);
),10000000000);
);






node.js settimeout mongoose-schema






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 10:11









lifeisfoo

7,9053 gold badges46 silver badges74 bronze badges




7,9053 gold badges46 silver badges74 bronze badges










asked Mar 28 at 9:29









deekshadeeksha

908 bronze badges




908 bronze badges















  • setTimeout takes a function as a parameter. However, you're passing a Promise to it.

    – Sergeon
    Mar 28 at 9:41

















  • setTimeout takes a function as a parameter. However, you're passing a Promise to it.

    – Sergeon
    Mar 28 at 9:41
















setTimeout takes a function as a parameter. However, you're passing a Promise to it.

– Sergeon
Mar 28 at 9:41





setTimeout takes a function as a parameter. However, you're passing a Promise to it.

– Sergeon
Mar 28 at 9:41












1 Answer
1






active

oldest

votes


















2
















The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.



Manual token verification



A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.



You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.



@NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).



The Mongo expire option



A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.



const secondsInADay = 60 * 60 * 24;

const tokenSchema = mongoose.Schema(
value: String
, timestamps: true);

tokenSchema.index(createdAt: 1,expireAfterSeconds: secondsInADay);
const Token = mongoose.model('Token', tokenSchema);


Then add to your existing CompanySchema a reference to this schema:



forgetpassword_token: type: mongoose.Schema.Types.ObjectId, ref: 'Token'


A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.



The job scheduler



Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check @NikKyriakides comments below for potential drawbacks of this solution.






share|improve this answer



























  • Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

    – Nik Kyriakides
    Mar 28 at 10:24












  • Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

    – lifeisfoo
    Mar 28 at 10:40











  • I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

    – Nik Kyriakides
    Mar 28 at 12:05












  • Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

    – Nik Kyriakides
    Mar 28 at 12:07












  • @NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

    – lifeisfoo
    Mar 28 at 12:57










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394154%2fsettimeout-is-not-working-in-mongoose-schema-post-middleware%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2
















The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.



Manual token verification



A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.



You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.



@NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).



The Mongo expire option



A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.



const secondsInADay = 60 * 60 * 24;

const tokenSchema = mongoose.Schema(
value: String
, timestamps: true);

tokenSchema.index(createdAt: 1,expireAfterSeconds: secondsInADay);
const Token = mongoose.model('Token', tokenSchema);


Then add to your existing CompanySchema a reference to this schema:



forgetpassword_token: type: mongoose.Schema.Types.ObjectId, ref: 'Token'


A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.



The job scheduler



Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check @NikKyriakides comments below for potential drawbacks of this solution.






share|improve this answer



























  • Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

    – Nik Kyriakides
    Mar 28 at 10:24












  • Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

    – lifeisfoo
    Mar 28 at 10:40











  • I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

    – Nik Kyriakides
    Mar 28 at 12:05












  • Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

    – Nik Kyriakides
    Mar 28 at 12:07












  • @NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

    – lifeisfoo
    Mar 28 at 12:57















2
















The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.



Manual token verification



A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.



You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.



@NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).



The Mongo expire option



A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.



const secondsInADay = 60 * 60 * 24;

const tokenSchema = mongoose.Schema(
value: String
, timestamps: true);

tokenSchema.index(createdAt: 1,expireAfterSeconds: secondsInADay);
const Token = mongoose.model('Token', tokenSchema);


Then add to your existing CompanySchema a reference to this schema:



forgetpassword_token: type: mongoose.Schema.Types.ObjectId, ref: 'Token'


A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.



The job scheduler



Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check @NikKyriakides comments below for potential drawbacks of this solution.






share|improve this answer



























  • Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

    – Nik Kyriakides
    Mar 28 at 10:24












  • Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

    – lifeisfoo
    Mar 28 at 10:40











  • I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

    – Nik Kyriakides
    Mar 28 at 12:05












  • Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

    – Nik Kyriakides
    Mar 28 at 12:07












  • @NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

    – lifeisfoo
    Mar 28 at 12:57













2














2










2









The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.



Manual token verification



A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.



You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.



@NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).



The Mongo expire option



A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.



const secondsInADay = 60 * 60 * 24;

const tokenSchema = mongoose.Schema(
value: String
, timestamps: true);

tokenSchema.index(createdAt: 1,expireAfterSeconds: secondsInADay);
const Token = mongoose.model('Token', tokenSchema);


Then add to your existing CompanySchema a reference to this schema:



forgetpassword_token: type: mongoose.Schema.Types.ObjectId, ref: 'Token'


A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.



The job scheduler



Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check @NikKyriakides comments below for potential drawbacks of this solution.






share|improve this answer















The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.



Manual token verification



A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.



You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.



@NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).



The Mongo expire option



A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.



const secondsInADay = 60 * 60 * 24;

const tokenSchema = mongoose.Schema(
value: String
, timestamps: true);

tokenSchema.index(createdAt: 1,expireAfterSeconds: secondsInADay);
const Token = mongoose.model('Token', tokenSchema);


Then add to your existing CompanySchema a reference to this schema:



forgetpassword_token: type: mongoose.Schema.Types.ObjectId, ref: 'Token'


A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.



The job scheduler



Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check @NikKyriakides comments below for potential drawbacks of this solution.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 28 at 13:14

























answered Mar 28 at 10:10









lifeisfoolifeisfoo

7,9053 gold badges46 silver badges74 bronze badges




7,9053 gold badges46 silver badges74 bronze badges















  • Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

    – Nik Kyriakides
    Mar 28 at 10:24












  • Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

    – lifeisfoo
    Mar 28 at 10:40











  • I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

    – Nik Kyriakides
    Mar 28 at 12:05












  • Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

    – Nik Kyriakides
    Mar 28 at 12:07












  • @NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

    – lifeisfoo
    Mar 28 at 12:57

















  • Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

    – Nik Kyriakides
    Mar 28 at 10:24












  • Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

    – lifeisfoo
    Mar 28 at 10:40











  • I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

    – Nik Kyriakides
    Mar 28 at 12:05












  • Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

    – Nik Kyriakides
    Mar 28 at 12:07












  • @NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

    – lifeisfoo
    Mar 28 at 12:57
















Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

– Nik Kyriakides
Mar 28 at 10:24






Can't you like encode/encrypt the creation datetime in the token itself, then decrypt it and check if it's expired based on current time? IRRC JWT does something similar.

– Nik Kyriakides
Mar 28 at 10:24














Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

– lifeisfoo
Mar 28 at 10:40





Yes @NikKyriakides, this is another possible approach. But when security is involved I'll prefer to write less code/logic as possible, because when writing the encoding/comparison procedure we can add risky bugs to it. And during the lifecycle of the project the code can be inadvertently changed. Moreover, delegating a specific component (mongo itself or agenda) to actively looking for expired tokens, we can be sure that they are deleted as soon as possible. Security is also about tiny details. Obviously this is my POV.

– lifeisfoo
Mar 28 at 10:40













I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

– Nik Kyriakides
Mar 28 at 12:05






I think you're violating KISS with what you're suggesting. What if your job scheduler goes down? What if the DB has a lock when the job scheduler runs? Doesn't that mean that expired tokens won't be deleted? What if I attempt to execute forgot password after token is expired but before job scheduler runs? Code can be inadvertently be changed on what you're proposing as well. Someone modified your job scheduler to simply.. well not run. Passive measures are always better than active measures.

– Nik Kyriakides
Mar 28 at 12:05














Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

– Nik Kyriakides
Mar 28 at 12:07






Also when security is involved I'll prefer to write less code/logic as possible.... How is involving and configuring a job scheduler that needs to be always on, less code than simply writing a middleware that decodes a JWT and compares the datetime with currenttime? I think I don't need to say that I'm not attacking you, but rather the logic of your proposed solution.

– Nik Kyriakides
Mar 28 at 12:07














@NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

– lifeisfoo
Mar 28 at 12:57





@NikKyriakides my statement was mainly referred to the mongo expire option. Yes, the scheduler solution can be overkilling and has its cons, but in some cases it could be required (e.g. notify the user about that or when more logic is needed in the token management). I used many times in the past a solution based on date comparison, and now I'll update the answer with another solution based on your suggestion. Thank you also for your criticism: when it's based on fatcs it's always useful.

– lifeisfoo
Mar 28 at 12:57








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394154%2fsettimeout-is-not-working-in-mongoose-schema-post-middleware%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해