Source: connector/sampleBasicAuth.js

Source: connector/sampleBasicAuth.js

/**
 * Copyright (c) 2019 Oracle and/or its affiliates. All rights reserved.
 * Licensed under the Universal Permissive License v 1.0 as shown at http://oss.oracle.com/licenses/upl.
 */
/* globals app, module, __dirname */
/* jshint esversion: 6 */


/**
 * An example of protecting requests to the translation connector using Basic Auth <br/>
 * <b>NOTE: DO NOT USE THIS SAMPLE IN PRODUCTION</b>
 * @constructor
 * @alias SampleBasicAuth
 */
var SampleBasicAuth = function () {};

/**
 * Validate that incoming request against Basic Auth credentials.
 * If validation fails, request is rejected.<br/>
 * <b>NOTE: DO NOT USE THIS SAMPLE IN PRODUCTION</b>
 * @param {object} req - The HTTPS request object
 * @param {object} res - The HTTPS response object
 * @param {object} req.headers - Parameters passed on via the header.
 * @param {string} req.headers.Authorization - Authorization header containing the un/pw
 * @param {function} next - Callback function upon successful validation.
 */
SampleBasicAuth.prototype.validate = function (req, res, next) {
    // only protect connector API calls
    if (!req.path.startsWith('/api/connector')) {
        return next();
    }

    // allow access to the server config
    if (req.path.startsWith('/api/connector/v1/server')) {
        return next();
    }

    // ok, secured calls, check for basic auth header
    var users = {
        "admin:Welcome1": "admin@myconnector.com"
    };

    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        return res.status(401).json({
            message: 'Missing Authorization Header'
        });
    }

    // get the authentication credentials
    var base64Credentials = req.headers.authorization.split(' ')[1],
        credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');

    // validate credentials
    user = users[credentials];
    if (!user) {
        return res.status(401).json({
            message: 'Invalid Authentication Credentials'
        });
    }

    // attach user to request object
    req.user = user;

    next();
};

module.exports = new SampleBasicAuth();