How to use the http-status-codes.UNAUTHORIZED function in http-status-codes

To help you get started, we’ve selected a few http-status-codes examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github re-figure / refigure / back / auth.js View on Github external
db.cbFind(db.model.TABLE_USER, {[db.model.ID]: userId}, (err, results) => {
            if (err) {
                callback({
                    http: httpStatus.UNAUTHORIZED,
                    error: constants.ERROR_SQL,
                    message: constants.ERROR_MSG_SQL
                });
            } else {
                if (results.length > 0) {
                    let user = results[0];
                    if (user.Password) {
                        delete user.Password;
                    }
                    if (user.Type === constants.USER_TYPE_NOTCONFIRMED) {
                        // registration is not completed yet
                        callback({
                            http: httpStatus.UNAUTHORIZED,
                            error: constants.ERROR_USERNOTREGISTERED
                        });
                    } else {
github Viveckh / Veniqa / shopping-server / services / shoppingService.js View on Github external
async deleteFromCart(userObj, arrayOfCartItemIds) {
        let result = {};
        try {
            // find the user first
            let user = await User.findOne({email: userObj.email}).exec();

            // If the user is not found, its most likely they are not authenticated and don't have user info under session
            if (!user) {
                result = {httpStatus: httpStatus.UNAUTHORIZED, status: "failed", errorDetails: httpStatus.getStatusText(httpStatus.UNAUTHORIZED)};
                return result;
            }

            // Remove the items from cart for which the ids exists in the arrayOfCartItemIds requested for removal
            for(let cartItemId of arrayOfCartItemIds) {
                user = await User.findOneAndUpdate({'cart.items._id': cartItemId},
                    {$pull: { 'cart.items': { _id: cartItemId}}},
                    {new: true}
                    ).exec()
            }

            // This means the deleteFromCart was successful if there were any elements worth removing, so return the cart details saving extra api calls from front end
            let updatedCartResponse = await this.getCart(userObj);
            return updatedCartResponse;
        }
        catch(err) {
github RouteInjector / route-injector / lib / engine / routeinjector / routes / model.js View on Github external
module.exports.getFormConfig = function (req, res) {
    var modelName = req.params.modelname;
    try {
        var Model = mongoose.model(modelName);
        var minjector = Model.injector();
        var shard = _.clone(minjector.shard, true);

        if (injector.security.permissions.shards) {
            if (!req.user || !req.user.role) {
                res.statusCode = statusCode.UNAUTHORIZED;
                res.json("Unauthorized");
                return res.end();
            }

            if (minjector.shard && minjector.shard.shardValues) {
                var restrictions = injector.config.permissions.shards[req.user.role];

                if (restrictions && restrictions.blacklist) {
                    shard.shardValues = _.xor(restrictions.blacklist, minjector.shard.shardValues);
                    shard.filtered = true;
                }

                if (restrictions && restrictions.whitelist) {
                    // Region "$OWN_REGION" is translated to the user own region
                    var list = _.clone(restrictions.whitelist);
                    var match = list.indexOf("$OWN_REGION");
github adobe / commerce-cif-common / src / web-action-transformer / exception-mapper-transformer.js View on Github external
*
 ******************************************************************************/

'use strict';

const ITransformerPipelineAction = require('./transformer-pipeline').ITransformerPipelineAction;
const HttpStatusCodes = require('http-status-codes');
const ErrorResponse = require('@adobe/commerce-cif-model').ErrorResponse;

const ERROR_NAME_TO_STATUS_CODE = {
    'InvalidArgumentError': HttpStatusCodes.BAD_REQUEST,
    'MissingPropertyError': HttpStatusCodes.BAD_REQUEST,
    'CommerceServiceResourceNotFoundError': HttpStatusCodes.NOT_FOUND,
    'CommerceServiceBadRequestError': HttpStatusCodes.BAD_REQUEST,
    'CommerceServiceForbiddenError': HttpStatusCodes.FORBIDDEN,
    'CommerceServiceUnauthorizedError': HttpStatusCodes.UNAUTHORIZED,
    'NotImplementedError': HttpStatusCodes.NOT_IMPLEMENTED
};

/**
 * If the action ended with an error, this transformer maps the error to a status code and updates the response message.
 *
 * @extends ITransformerPipelineAction
 */
class ExceptionMapperTransformerPipelineAction extends ITransformerPipelineAction {
    transform(httpResponse, resultFromOwSequence) {
        if (!httpResponse.error) {
            return httpResponse;
        }

        let message;
        let reason;
github Azure / meta-azure-service-broker / lib / broker / v2 / api-handlers.js View on Github external
credsAuthUser.write(credentials.authUser);

      var pwdLen = req.authorization.basic.password.length;
      pwdLen = pwdLen > credentials.authPassword.length ? pwdLen : credentials.authPassword.length;
      const reqAuthPassword = Buffer.alloc(pwdLen);
      reqAuthPassword.write(req.authorization.basic.password);
      const credsAuthPassword = Buffer.alloc(pwdLen);
      credsAuthPassword.write(credentials.authPassword);

      if (crypto.timingSafeEqual(credsAuthUser, reqAuthUser) & crypto.timingSafeEqual(credsAuthPassword, reqAuthPassword)) {
        return next();
      }
    }

    log.error('Invalid auth credentials for requests.');
    res.send(HttpStatus.UNAUTHORIZED, {});
    return next(false);
  };
};
github Sunbird-Ed / SunbirdEd-portal / src / app / helpers / announcement / index.js View on Github external
if(userProfile){
                var isAuthorized = isCreateRolePresent(userProfile, config.sourceid);
                if (isAuthorized) {
                    next()
                } else {
                    throw "UNAUTHORIZED_USER"
                }
            }else{
                throw 'UNAUTHORIZED_USER'
            }
            
        } catch (error) {
            if (error === 'USER_NOT_FOUND') {
                sendErrorResponse(responseObj, config.apiid, "USER_NOT_FOUND", HttpStatus.BAD_REQUEST)
            } else if (error === 'UNAUTHORIZED_USER') {
                 sendErrorResponse(responseObj, config.apiid, "UNAUTHORIZED_USER", HttpStatus.UNAUTHORIZED)
            } else {
                 sendErrorResponse(responseObj, config.apiid, "UNAUTHORIZED_USER", HttpStatus.UNAUTHORIZED)
            }
        }
    })
}
github microsoft / BotFramework-Emulator / packages / emulator / core / src / bot.ts View on Github external
async fetchWithAuth(url, options: any = {}, forceRefresh: boolean = false) {
    if (this.msaAppId) {
      options.headers = {
        ...options.headers,
        Authorization: `Bearer ${await this.getAccessToken(forceRefresh)}`
      };
    }

    const response = await this.options.fetch(url, options);

    if (
      (response.status === HttpStatus.UNAUTHORIZED || response.status === HttpStatus.FORBIDDEN)
      && (!forceRefresh && this.msaAppId)
    ) {
      return await this.fetchWithAuth(url, options, true);
    }

    return response;
  }
github RouteInjector / route-injector / lib / engine / routeinjector / routes / auth / utils.js View on Github external
function kick() {
                res.statusCode = statusCode.UNAUTHORIZED;
                res.json("Unauthorized. User role is " + req.user.role + " and this operation needs " + role);
                return res.end();
            }
github CodepediaOrg / bookmarks.dev-api / routes / users / users.js View on Github external
usersRouter.get('/:userId/pinned', keycloak.protect(), async (request, response) => {
  try {
    let userId = request.kauth.grant.access_token.content.sub;
    if ( userId !== request.params.userId ) {
      return response
        .status(HttpStatus.UNAUTHORIZED)
        .send(new MyError('Unauthorized', ['the userId does not match the subject in the access token']));
    }

    const userData = await User.findOne({
      userId: request.params.userId
    });
    if ( !userData ) {
      return response
        .status(HttpStatus.NOT_FOUND)
        .send(new MyError(
          'User data was not found',
          ['User data of the user with the userId ' + request.params.userId + ' was not found']
          )
        );
    } else {
      const bookmarks = await Bookmark.find({"_id": {$in: userData.pinned}});
github IntelAI / nauta / applications / nauta-gui / api / src / utils / requestWrapper.js View on Github external
request(options, function (err, response, body) {
      if (err) {
        logger.error('Request to api failed.', err);
        reject(errHandler(HttpStatus.INTERNAL_SERVER_ERROR, err));
      }
      if (response) {
        if (response.statusCode === HttpStatus.INTERNAL_SERVER_ERROR) {
          logger.debug('Internal Server Error');
          reject(errHandler(HttpStatus.INTERNAL_SERVER_ERROR, errMessages.GENERAL.INTERNAL_SERVER_ERROR));
        }
        if (response.statusCode === HttpStatus.UNAUTHORIZED) {
          logger.debug('Unauthorized request to API');
          reject(errHandler(HttpStatus.UNAUTHORIZED, errMessages.AUTH.UNAUTHORIZED_OPERATION));
        }
        if (response.statusCode === HttpStatus.FORBIDDEN) {
          logger.debug('Forbidden request to API');
          reject(errHandler(HttpStatus.FORBIDDEN, errMessages.AUTH.FORBIDDEN_OPERATION));
        }
        logger.debug('Data from API has been retrieved');

        try {
          const data = JSON.parse(body);
          resolve(data);
        } catch (err) {
          logger.warn('Cannot parse response body');
        }
        resolve(body);
      }
    });