Skip to content

Commit

Permalink
Refactor code to check session espire time
Browse files Browse the repository at this point in the history
  • Loading branch information
cotarr committed Jan 25, 2024
1 parent 48af4dd commit 52814e8
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 31 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## v0.0.24-Dev

### Changed

Refactored some code from v0.0.23 related to expiration of session in the express-session store.
The change does not alter the functionality of the expiration check from v0.0.23.
It was recoded to be consistent with related repository collab-frontend.
More descriptive variables names were also used.

- In server/site.js - Removed middleware from POST /login route that was used to add login timestamp to the session.
- In server/auth.js - Added code to the passport localStrategy 'local' callback function to add login timestamp to the session.
- In server/session-auth.js - In the auth.check() function, refactored check for session expiration to match other changes.

## [v0.0.23](https://github.com/cotarr/collab-auth/releases/tag/v0.0.23) 2024-01-17

This update added the capability to disable client accounts in the client database.
Expand Down
6 changes: 4 additions & 2 deletions debug/modules/managed-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,11 @@ exports.managedFetch = (chain) => {
}

if ((response.ok) || (response.status === 302)) {
if (chain.parsedContentType.indexOf('application/json') >= 0) {
if ((chain.parsedContentType) &&
(chain.parsedContentType.indexOf('application/json') >= 0)) {
return response.json();
} else if (chain.parsedContentType.indexOf('text/html') >= 0) {
} else if ((chain.parsedContentType) &&
(chain.parsedContentType.indexOf('text/html') >= 0)) {
return response.text();
} else {
return response.text();
Expand Down
4 changes: 2 additions & 2 deletions debug/modules/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ exports.logRequest = (chain, options) => {
if (showChainFlag) {
console.log('-------------- DEBUG: chain object ----------------');
console.log('chain', JSON.stringify(chain, null, 2));
console.log('-------------- DEUBG: end chain -------------------');
console.log('-------------- DEBUG: end chain -------------------');
}
};

Expand Down Expand Up @@ -169,7 +169,7 @@ exports.showJwtMetaData = (chain) => {

/**
* Notify user if virtual host mismatch is reject requests
* @param {Number} chain.responseStatus - HTTP status code of previous fetch
* @param {Number} chain.responseStatus - HTTP status code of previous fetch
*/
exports.check404PossibleVhostError = (chain) => {
if (chain.responseStatus === 404) {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "collab-auth",
"version": "0.0.23",
"version": "0.0.24-Dev",
"description": "Oauth2 server used on a collaboration project for learning oauth2orize and passport",
"main": "bin/www",
"scripts": {
"lint": "npx eslint server bin/www SQL-tools *.js",
"lint": "npx eslint server bin/www debug SQL-tools *.js",
"start": "node ./bin/www",
"config-dev-script": "bash ./config-dev-script.sh",
"create-postgres-admin-user": "node ./SQL-tools/create-postgres-admin-user.js"
Expand Down
2 changes: 2 additions & 0 deletions server/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const { Strategy: LocalStrategy } = require('passport-local');
const { BasicStrategy } = require('passport-http');
const { Strategy: ClientPasswordStrategy } = require('passport-oauth2-client-password');
const validate = require('./validate');
const sessionAuth = require('./session-auth');
const { addScopeToPassportReqObj } = require('./scope');
const logUtils = require('./log-utils');
const stats = require('./stats');
Expand All @@ -25,6 +26,7 @@ const stats = require('./stats');
passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
db.users.findByUsername(username)
.then((user) => validate.user(user, password))
.then((user) => sessionAuth.addLoginTimestamp(req, user))
.then((user) => db.users.updateLoginTime(user))
.then((user) => logUtils.logPassportLocalLogin(req, user))
.then((user) => stats.incrementCounterPm(user, 'userLogin'))
Expand Down
45 changes: 22 additions & 23 deletions server/session-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,19 @@ const allowedAlternateRedirectRoutes = [
];

/**
* Middleware function to add session expiration time
* in milliseconds to session record.
* This is called from POST /login (password entry)
* @param {Object} req - ExpressJs request object
* @param {Object} res - ExpressJs response object
* @param {Function} next - ExpressJs function to call next handler
* Add user login timestamp (unix seconds) to session
* This is called from passport local strategy callback function in auth.js
* @param {Object} req - ExpressJs request object, modified by this function
* @param {Object} user - User object (not used, pass through only)
* @returns {Promise} - Returns promise resolving to user object
*/
exports.updateSessionExpireTime = function (req, res, next) {
if (req.session) {
if (!req.session.sessionExpiresMs) {
req.session.sessionExpiresMs = Date.now() + config.session.maxAge;
}
exports.addLoginTimestamp = function (req, user) {
// Add a timestamp property that may be used to expire sessions
if ((req) && (req.session)) {
// loginTimestamp in Unix seconds
req.session.loginTimestamp = Math.floor(Date.now() / 1000);
};
next();
return Promise.resolve(user);
};

/**
Expand All @@ -98,21 +97,21 @@ exports.updateSessionExpireTime = function (req, res, next) {
*/
exports.checkSessionAuth = function (options) {
return function (req, res, next) {
//
// Unless configured as rolling cookie, deny requests to expired sessions.
// Different session store packages handle expiration differently.
// This is an explicit check independent of session store touch/prune features.
//
let expired = false;

if (req.session.cookie) {
// For case of rolling cookies skip this block
if (!config.session.rollingCookie) {
// For case of session cookie, or fixed expiration cookie
// deny requests that exceed maxAge of session
if (req.session.sessionExpiresMs) {
const timeNowMs = Date.now();
if (timeNowMs > req.session.sessionExpiresMs) {
expired = true;
}
if (!config.session.rollingCookie) {
if ((req) && (req.session) && (Object.hasOwn(req.session, 'loginTimestamp'))) {
// loginTimestamp in Unix seconds
if (Math.floor(Date.now() / 1000) > req.session.loginTimestamp + config.session.ttl) {
expired = true;
}
}
}

//
// Case of not authorized, for valid routes redirect /login, else return status 401
//
Expand Down
3 changes: 1 addition & 2 deletions server/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const { requireScopeForWebPanel } = require('./scope');
const validate = require('./validate');
const inputValidation = require('./input-validation');
const logUtils = require('./log-utils');
const { updateSessionExpireTime, checkSessionAuth } = require('./session-auth');
const { checkSessionAuth } = require('./session-auth');

// const nodeEnv = process.env.NODE_ENV || 'development';

Expand Down Expand Up @@ -158,7 +158,6 @@ exports.login = [
checkCookieExists,
inputValidation.loginPostRequest,
csrfProtection,
updateSessionExpireTime,
passport.authenticate('local',
{
// V0.0.7 - Notes
Expand Down

0 comments on commit 52814e8

Please sign in to comment.