User registration and login

User registration and login
0
#1

Hello,

I have one question, I’m using MERN stack and right now I set up passport-jwt auth and saving users to database like this, Schema:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const UserSchema = new Schema({
    username: {
        type: 'String',
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now()
    }
})

module.exports = User = mongoose.model('users', UserSchema)

If I add another strategy like facebook or google do I still have to store those users in database and use this Schema or do I need separate Schema?

I hope you guys understand my question.
Thanks

0 Likes

#2

Yes,

That’s up to you, I typically keep all users in one schema, since one schema maps to one collection, I just segregate the different authentication strategies into different objects within that schema, for example, with yours I’d add your existing strategy to local and add the 3rd party strategies as newer properties of the schema, this way all the users of the app are in one collection, while still having access to the strategy that the user used to login in the db.

const UserSchema = new Schema({
 local: {
    username: {
    type: 'String',
    required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now()
    }
  },
  twitter: {
            id    : String,
            displayName  : String,
            username     : String
  },
  google: {
            id    : String,
            displayName  : String,
            username  : String
  }
})

module.exports = User = mongoose.model('users', UserSchema)
1 Like

#3

Also, if I may add, there is also the case of authorization which is different to authentication, say you want an existing user to authorize a different account under the umbrella of their current account, then authorization may require a different strategy, if you are using passport If I recall correctly it has it’s own authorization method.

1 Like

#4

Thanks man, that example really helped to get a better idea of what I’m trying to achieve :slight_smile:

0 Likes