All files / services/config-service/src/models User.js

71.08% Statements 59/83
100% Branches 1/1
0% Functions 0/2
71.08% Lines 59/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x                                           1x 1x 1x
const mongoose = require('mongoose');
 
const userSchema = new mongoose.Schema({
  googleId: {
    type: String,
    unique: true,
    sparse: true,
    index: true
  },
  googleEmail: {
    type: String,
    unique: true,
    sparse: true,
    lowercase: true,
    index: true
  },
  email: {
    type: String,
    lowercase: true,
    trim: true
  },
  name: {
    type: String,
    required: true,
    trim: true
  },
  picture: {
    type: String,
    default: null
  },
  role: {
    type: String,
    enum: ['user', 'tester', 'admin'],
    default: 'user'
  },
  isActive: {
    type: Boolean,
    default: true
  },
  lastLogin: {
    type: Date,
    default: null
  },
  defaultOrganizationId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Organization',
    default: null
  }
}, {
  timestamps: true
});
 
userSchema.methods.toJSON = function() {
  const user = this.toObject();
  delete user.__v;
  return user;
};
 
userSchema.statics.findOrCreateFromGoogle = async function(profile) {
  let user = await this.findOne({ googleId: profile.googleId });
  
  if (user) {
    user.name = profile.name;
    user.picture = profile.picture;
    user.googleEmail = profile.email;
    user.lastLogin = new Date();
    await user.save();
    return user;
  }
  
  user = await this.create({
    googleId: profile.googleId,
    googleEmail: profile.email,
    email: profile.email,
    name: profile.name,
    picture: profile.picture,
    lastLogin: new Date()
  });
  
  return user;
};
 
module.exports = mongoose.model('User', userSchema);