lib/middleware.js
/**
 * Middleware to check if a session id is present in the cookie, and if the
 * user credentials belonging to that session verify against Twitter. If so,
 * the user is authenticated and the handler will be called. If not, any
 * existing session data will be destroyed and a login page is rendered.
 *
 * @param  {Function} handler
 * @return {Function}
 */
Middleware to check if a session id is present in the cookie, and if the
user credentials belonging to that session verify against Twitter. If so,
the user is authenticated and the handler will be called. If not, any
existing session data will be destroyed and a login page is rendered.

@param  {Function} handler
@return {Function}
Middleware to check if a session id is present in the cookie and if the user credentials belonging to that session verify against Twitter . If so the user is authenticated and the handler will be called . If not any existing session data will be destroyed and a login page is rendered . @param { Function } handler @return { Function }
function authenticate(handler) {
	if (typeof handler !== 'function') {
		throw Error('Authentication middleware expects a function')
	}
	return async (req, res) => {
		const sessionId = req.cookies.session_id
		try {
			if (sessionId) {
				const { oauth_token, oauth_token_secret } = await getUserSession(sessionId)
				await verifyCredentials(oauth_token, oauth_token_secret)
				return handler(req, res)
			}
		} catch(error) {
			log(error)
			if (sessionId) {
				await deleteUserSession(sessionId)
				res.setHeader('Set-Cookie', 'session_id=destroyed; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT')
			}
		}
		sendLoginPage(req, res)
	}
}
function authenticate ( handler ) { if ( typeof handler !== 'function' ) { throw Error ( 'Authentication middleware expects a function' ) } return async ( req , res ) => { const sessionId = req . cookies . session_id try { if ( sessionId ) { const { oauth_token , oauth_token_secret } = await getUserSession ( sessionId ) await verifyCredentials ( oauth_token , oauth_token_secret ) return handler ( req , res ) } } catch ( error ) { log ( error ) if ( sessionId ) { await deleteUserSession ( sessionId ) res . setHeader ( 'Set-Cookie' , 'session_id=destroyed; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT' ) } } sendLoginPage ( req , res ) } }
Middleware to check if a session id is present in the cookie, and if the
 user credentials belonging to that session verify against Twitter.
Middleware to check if a session id is present in the cookie and if the user credentials belonging to that session verify against Twitter .
// Both `verifyCredentials` and destructuring `getUserSession` // will throw if they fail, which is why the catch handler kicks // in if either the session is missing from Redis, or Twitter // says the credentials are wrong // Deleting cookie is best done by setting it to an 'incorrect' // value and letting it expire in the past // https://stackoverflow.com/a/53573622