Pre remove hook for the User model.
Validates that the root user cannot be deleted.

@api private
@param {Function} next - The mongoose middleware callback
@returns {*} If an error occurs the passed callback with an Error as its argument is called
174747
function preRemove(next) {
  // jshint validthis: true
  if (auth.roles.isRoot(this.role)) {
    return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted'));
  }

  return next();
}
283154
function remove(clientModelDoc, callback) {
      var cb = callback || angular.noop;

      return ClientModelDoc.remove({id: clientModelDoc._id},
        function (clientModelDoc) {
          return cb(clientModelDoc);
        },
        function (err) {
          return cb(err);
        }).$promise;
    }
655695
def delete_user_action(model, request):
    
    try:
        users = model.parent.backend
        uid = model.model.name
        del users[uid]
        users()
        model.parent.invalidate()
        localizer = get_localizer(request)
        message = localizer.translate(_(
            'delete_user_from_database',
            default="Deleted user '${uid}' from database.",
            mapping={'uid': uid}
        ))
        return {
            'success': True,
            'message': message
        }
    except Exception as e:
        return {
            'success': False,
            'message': str(e)
        }
480852
function removeOthers(mongoose, model, retainedNames) {
    //console.log('here collectionname' + Object.keys(model));
    //console.log('here collectionname' + model.collectionname);
    return model.aggregate({ $project: { modelname: 1 } }).then((r) => r.map(o => o.modelname)).then((modelnames) => {
        debuglog(" present models " + modelnames.length + ' ' + modelnames);
        var delta = _.difference(modelnames, retainedNames);
        debuglog(' spurious models' + delta.length + ' ' + delta);
        if (delta.length === 0) {
            return Promise.resolve(true);
        }
        return Promise.all(delta.map(modelname => model.remove({ modelname: modelname })));
    });
}
1037928
function deleteUser (params, cb) {
      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { id, organizationId } = params
      const tasks = [
        (job, next) => {
          Joi.validate({ id, organizationId }, validationRules.deleteUser, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.id = id
          next()
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM user_policies WHERE user_id = ${id}`

          job.client.query(sqlQuery, utils.boomErrorWrapper(next))
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM team_members WHERE user_id = ${id}`

          job.client.query(sqlQuery, utils.boomErrorWrapper(next))
        },
        (job, next) => {
          const sqlQuery = SQL`DELETE FROM users WHERE id = ${id} AND org_id = ${organizationId}`

          job.client.query(sqlQuery, (err, result) => {
            if (err) return next(Boom.badImplementation(err))
            if (result.rowCount === 0) return next(Boom.notFound(`User ${id} not found`))

            next()
          })
        }
      ]

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        cb()
      })

      return promise
    }
745157
function remove(node) {
    var next = node.nextSibling || node.parentNode;

    node.parentNode.removeChild(node);

    return next;
}
157041
function(req,res,next){
  var token = req.get('X-OOSE-Token')
  if(!token || user.session.token !== token){
    res.status(401)
    res.json({error: 'Invalid session'})
  } else {
    req.session = user.session
    next()
  }
}
1228211
function destroy(publicAPI, model = {}) {
  const previousDestroy = publicAPI.destroy;

  if (!model.subscriptions) {
    model.subscriptions = [];
  }

  publicAPI.destroy = () => {
    if (previousDestroy) {
      previousDestroy();
    }
    while (model.subscriptions && model.subscriptions.length) {
      model.subscriptions.pop().unsubscribe();
    }
    Object.keys(model).forEach((field) => {
      delete model[field];
    });

    // Flag the instance beeing deleted
    model.deleted = true;
  };
}
180351
public function handle(Request $request, Closure $next)
    {
        if (! $this->auth->check()) {
            // Retrieve the users account name from the request.
            if ($account = $this->account($request)) {
                // Retrieve the users username from their account name.
                $username = $this->username($account);

                // Finally, retrieve the users authenticatable model and log them in.
                if ($user = $this->retrieveAuthenticatedUser($username)) {
                    $this->auth->login($user, $remember = true);
                }
            }
        }

        return $next($request);
    }
928510
function preSave(next) {
		const _ref = this.get(options.createdName);

		if (!options.disableUpdated) {
			this[options.updatedName] = new Date();
		}
		if (!options.disableCreated && (_ref === undefined || _ref === null)) {
			this[options.createdName] = new Date();
		}

		next();
	}
533095
function nextPostHook(res) {
                    response = checkResponse(res, response);

                    if (currentPost + 1 < totalPost && self.__hooksEnabled !== false) {
                        currentPost += 1;

                        // Reference to current post hook
                        const currPost = posts[currentPost];
                        const hookMethod = currPost.displayName || currPost.name;
                        scope = getScope(self, name, res, hookMethod, 'post');

                        // Recursively call all the "post" hooks
                        return currPost.call(scope, response).then(nextPostHook, postHookErrorHandler);
                    }

                    /**
                     * All "post" hook process done.
                     * If the response has an "__override" property it will be our response
                     */
                    if (is.object(response) && {}.hasOwnProperty.call(response, '__override')) {
                        response = response.__override;
                    }

                    return resolveFn(response);
                }
277907
function undeploy(req, res, next) {
  var removeParams = {
    _id: req.params.id
  };

  logger.debug("Middleware: undeploy form: ", {params: removeParams});

  forms.deleteForm(_.extend(req.connectionOptions, removeParams), formsResultHandlers(constants.resultTypes.forms, req, next));
}
261448
function(request, response, next){
		if (!utils.Misc.isNullOrUndefined(request.user)) {
			next();
		}
		else {
			var error = new Error(errors['213']);
			response.end(utils.Misc.createResponse(null, error, 213));
		}
	}
1153053
function(username, password, callback) {

            var args = Array.prototype.slice.call(arguments);

            if (args.length === 1) {
                callback = arguments[0];
            } else {
                this.set({
                    username: username,
                    password: password
                });
            }

            this.validateAndSave(null, function(err, session) {
                if (!err && session) {
                    session.set("password", null);

                    session.fetch({
                        fetchSubModels: ["user"]
                    }, callback);
                } else {
                    callback(err);
                }
            });
        }
1213318
function() {
        if (AV._config.disableCurrentUser) {
          console.warn(
            'AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'
          );
          return Promise.resolve(null);
        }

        if (AV.User._currentUser !== null) {
          AV.User._currentUser._logOutWithAll();
          AV.User._currentUser._isCurrentUser = false;
        }
        AV.User._currentUserMatchesDisk = true;
        AV.User._currentUser = null;
        return AV.localStorage
          .removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY))
          .then(() => AV._refreshSubscriptionId());
      }
904637
function handleLogin(user, req, res, next) {


    var token;
    var profile;
    var tokenExpiresInMinutes;
    var envelope = {
      data: user,
      isAuthenticated: true,
      meta: {}
    };

    // First handle the case where the user was not logged in.
    if (!user) {
      if (authConfig.maintenance === 'cookie') {
        req.logout();
      }
      return res.status(401).send('Wrong password or no such user.');
    }
    // user_id is how it is in the schema
    /* jshint ignore:start */
    // Now handle the case where we did get a user record.
    if (authConfig.maintenance === 'token') {
      // For token authentication we want to add a token.
      profile = {
        username: user.username,
        email: user.email,
        userdata_id: user.userdata_id
      };
      /* jshint ignore:end */
      tokenExpiresInMinutes = authConfig.expiresInMinutes || 60;
      envelope.meta.token = generateToken(profile, tokenExpiresInMinutes,
        secrets.authTokenSecret);

      envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes);
      return res.status(200).send(envelope);
    } else if (authConfig.maintenance === 'cookie') {
      // For cookie authentication we want to login the user.
      req.login(user, function (err) {
        if (err) {
          return next(err);
        } else {
          return res.status(200).send(envelope);
        }
      });
    }
  }
474320
function middleware(req, res, next) {
  req.security.csrf.exclude = true;
  next();
}