bump package version to 1.1.1
[squeep-authentication-module] / lib / authenticator.js
index 15089a020f5a977f09239537e210c40c6ca61173..1cff2108f309e2ac51245070281e0ec346f6168c 100644 (file)
@@ -335,6 +335,40 @@ class Authenticator {
     return this.sessionCheck(req, res, ctx, undefined, false);
   }
 
+
+  /**
+   * Require auth for an API endpoint.
+   * Check for valid local identifier in Authorization header; optionally
+   * fall back to session cookie if no header provided.
+   * Prompts for Basic auth if not valid.
+   * @param {http.ClientRequest} req
+   * @param {http.ServerResponse} res
+   * @param {Object} ctx
+   * @param {Boolean} sessionAlsoValid
+   */
+  async apiRequiredLocal(req, res, ctx, sessionAlsoValid = true) {
+    const _scope = _fileScope('apiRequiredLocal');
+    this.logger.debug(_scope, 'called', { ctx, sessionAlsoValid });
+
+    // If a Authorization header was provided, never consider session as a fallback.
+    const authorizationHeader = req.getHeader(Enum.Header.Authorization);
+    if (authorizationHeader) {
+      if (await this.isValidAuthorization(authorizationHeader, ctx)) {
+        this.logger.debug(_scope, 'valid authorization', { ctx, sessionAlsoValid });
+        return true;
+      }
+    } else {
+      if (sessionAlsoValid
+      &&  await this.sessionCheck(req, res, ctx, undefined, false, false)) {
+        this.logger.debug(_scope, 'valid session', { ctx, sessionAlsoValid });
+        return true;
+      }
+    }
+
+    this.logger.debug(_scope, 'invalid authorization', { ctx, sessionAlsoValid });
+    this.requestBasic(res);
+  }
+
 }
 
 module.exports = Authenticator;
\ No newline at end of file