How to use the passport.deserializeUser function in passport

To help you get started, we’ve selected a few passport 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 avoidwork / tenso / lib / utility.js View on Github external
obj.always(luscaNoSniff).blacklist(luscaNoSniff);
	}

	// Can fork to `middleware.keymaster()`
	obj.always(middleware.zuul).blacklist(middleware.zuul);

	passportInit = passport.initialize();
	obj.always(passportInit).blacklist(passportInit);

	if (stateless === false) {
		passportSession = passport.session();
		obj.always(passportSession).blacklist(passportSession);
	}

	passport.serializeUser((user, done) => done(null, user));
	passport.deserializeUser((arg, done) => done(null, arg));

	if (config.auth.basic.enabled) {
		let x = {};

		const validate = (arg, cb) => {
			if (x[arg] !== void 0) {
				cb(null, x[arg]);
			} else {
				cb(new Error(STATUS_CODES[401]), null);
			}
		};

		each(config.auth.basic.list || [], i => {
			let args = i.split(":");

			if (args.length > 0) {
github tkssharma / e-CommerseHub / e-Commerce-Cart / express.ts View on Github external
private routes(): void {
    passport.serializeUser((user, done) => {
      done(null, user);
    });
    passport.deserializeUser((user, done) => {
      done(null, user);
    });
    /* This is just to get up and running, and to make sure what we've got is
     * working so far. This function will change when we start to add more
     * API endpoints */
    this.express.use('/api/v1', router);
    this.express.use(errorHandlers.internalServerError);
    this.express.use(errorHandlers.PageNotFound);
  }
github async-labs / saas / book / 11-end / api / server / auth.ts View on Github external
passport.use(
    new Strategy(
      {
        clientID: GOOGLE_CLIENTID,
        clientSecret: GOOGLE_CLIENTSECRET,
        callbackURL: `${ROOT_URL}/oauth2callback`,
      },
      verify,
    ),
  );

  passport.serializeUser((user: UserDocument, done) => {
    done(null, user._id);
  });

  passport.deserializeUser((id, done) => {
    User.findById(id, User.publicFields(), (err, user) => {
      done(err, user);
    });
  });

  server.use(passport.initialize());
  server.use(passport.session());

  server.get('/auth/google', (req, res, next) => {
    const options = {
      scope: ['profile', 'email'],
      prompt: 'select_account',
    };

    if (req.query && req.query.next && req.query.next.startsWith('/')) {
      // eslint-disable-next-line
github avoidwork / tenso / lib / tenso.es6.js View on Github external
obj.server.use(luscaXssProtection).blacklist(luscaXssProtection);
	}

	protection = zuul(config.auth.protect);
	obj.server.use(protection).blacklist(protection);

	if (stateless && !stateful) {
		init(false);
	} else {
		init(true);

		passport.serializeUser(function (user, done) {
			done(null, user);
		});

		passport.deserializeUser(function (arg, done) {
			done(null, arg);
		});

		if (authUris.length > 0) {
			keys = array.keys(authMap).length > 0;

			if (keys) {
				config.routes.get["/auth"] = authMap;
			}

			(function () {
				let r = "(?!/auth/(";

				array.each(authUris, function (i) {
					r += i.replace("_uri", "") + "|";
				});
github Lambda-IT / chestnutJS / chestnut / server / src / auth / refresh-token-strategy.ts View on Github external
export function createRefreshTokenStrategy(store: Store, app: express.Express) {
    passport.use(
        new LocalStrategy((username, password, done) => {
            validateUserAsync(username, password, store)
                .then(done)
                .catch(done);
        }),
    );

    passport.serializeUser((user, done) => done(null, user.id));

    passport.deserializeUser((id, done) => {
        store.models.authUser.findById(id, done);
    });

    function verifyClient(clientId, clientSecret, done) {
        store.models.authClient.findOne({ clientId: clientId }, (error, client) => {
            if (error) return done(error);
            if (!client) return done(null, false);
            if (client.clientSecret !== clientSecret) return done(null, false);
            return done(null, client);
        });
    }

    passport.use(new BasicStrategy(verifyClient));

    passport.use(new ClientPasswordStrategy(verifyClient));
github arrowjs / ArrowjsCore / config / middleware / loadPassport.js View on Github external
module.exports = function loadPassport(setting) {
    let app = this;
    let passportConfig = require(__base + 'config/passport.js')(passport, app);
    //If passport is enabled then load its
    if (setting && setting.passport) {
        app.use(passport.initialize());
        app.use(passport.session());

        //Read and load all configuration js files in config/strategies
        __.getGlobbedFiles(app.arrFolder + 'config/strategies/**/*.js').forEach(function (strategy) {
            require(path.resolve(strategy))(passport,app.getConfig(), app);
        });
        passport.serializeUser(passportConfig.serializeUser);
        passport.deserializeUser(passportConfig.deserializeUser) ;
    }

    //Monkey patch
    let passportLogout = function () {
        var property = 'user';
        if (this._passport && this._passport.instance) {
            property = this._passport.instance._userProperty || 'user';
        }

        this[property] = null;
        if (this._passport && this._passport.session) {
            if (this.session && this.session.permissions) {
                delete this.session.permissions
            }
            delete this._passport.session.user;
        }
github microsoft / ghcrawler-dashboard / middleware / passport-config.js View on Github external
responseMode: 'form_post',
    validateIssuer: true
  }, activeDirectorySubset);

  passport.use('azure-active-directory', aadStrategy);

  app.use(passport.initialize());
  app.use(passport.session());

  const serializerOptions = {
    config: config,
    keyResolver: app.get('keyEncryptionKeyResolver'),
  };

  passport.serializeUser(serializer.serialize(serializerOptions));
  passport.deserializeUser(serializer.deserialize(serializerOptions));
  serializer.initialize(serializerOptions, app);

  return passport;
};
github shastajs / boilerplate / server / http / middleware / auth / index.js View on Github external
return o
}

const getUserById = (id, cb) => {
  User.get(id).run((err, existing) => {
    if (err && err.name !== 'DocumentNotFoundError') {
      return cb(err)
    }
    cb(null, existing || false)
  })
}

const router = Router({ mergeParams: true })

passport.serializeUser(userToId)
passport.deserializeUser(getUserById)

router.get('/auth/logout', (req, res) => {
  req.logout()
  res.redirect('/')
})

router.get('/initialState.js', (req, res) => {
  const initialState = {
    me: read(req.user, req.user)
  }
  res.status(200)
  res.type('text/javascript')
  res.send(`window.__INITIAL_STATE__ = (${JSON.stringify(initialState)});`)
  res.end()
})
github adeperio / base / src / server / middleware / auth / passport.js View on Github external
import facebookStrategy from './facebook/facebook-strategy.js';
import localSignInStrategy from './local/local-sign-in-strategy.js';
import localSignUpStrategy from './local/local-sign-up-strategy.js';

//auth strategies
passport.use(googleStrategy);
passport.use(facebookStrategy);
passport.use('local-signin', localSignInStrategy);
passport.use('local-signup', localSignUpStrategy);

//serialising and deserialising user objects
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

module.exports = passport;
github imheretw / imhere / src / app / boots / PassportHandler.js View on Github external
start() {
    passport.serializeUser((user, done) => {
      done(null, user.id);
    });

    passport.deserializeUser((id, done) => {
      User
        .forge({ id }).fetch()
        .then((user) => {
          done(null, user.toJSON());
        });
    });

    /**
     * Sign in using Email and Password.
     */
    passport.use(new LocalStrategy({ usernameField: 'email' }, async (email, password, done) => {
      const ERROR_MSG = 'Account or password error.';
      const errorCallback = cb => cb(null, false, { msg: ERROR_MSG });
      const user = await User.forge({ email: email.toLowerCase() }).fetch();

      if (!user) {