Search code examples
node.jsmongoosepassport.jspassport-localpassport-google-oauth

How is this actually done?


I am doing a project with authentication using passport js with the Strategies (Google, Facebook, Local). I am working on the google part now but there is a small problem. When users register locally I save their data to the db (email,username,hashedPassword) but now when they register/signin through google I do not have access to their password (obviously). It is required in the user schema and I do not want to create a new user schema.

Could I save the password as the user id I received from google? I really want to know the correct path I should take.


Solution

  • You could add another field to your schema like provider that specifies the type of authentication that was used. Then you can use the mongoose required validator to make password only required if provider is 'local.' Something like this:

    const userSchema= new Schema({
      firstName: String,
      lastName: String,
      email: String,
      username: String,
      provider: {
        type: String,
        enum: ['local', 'google', 'facebook']
      },
      password: {
        type: String,
        required: function() {
          return this.provider === 'local';
        }
      }
    });