1

Given a User Model in a node app with JugglingDB

User = schema.define('User', {
  name      : String,
  email     : String,
  API_KEY   : String,
  created   : {type: Date, default: Date.now},
});

I would like the API_KEY attribute to be "read-only". So the following data:

var data = {
  name     : 'Test account',
  email    : 'test@test.com',
  API_KEY  : 'Some key' 
}

Is accepted as:

var data = {
  name     : 'Test account',
  email    : 'test@test.com'
}

In:

var user = new User(data);

So this way only the server can create an API_KEY for users. Is this possible?

Tessmore
  • 1,054
  • 1
  • 9
  • 23

1 Answers1

1

You can do this through the use of hooks. In particular you could use a beforeCreate and beforeUpdate hook, which would get executed whenever a new user is being created or its properties are being updated.

For example, you could assign a server generated API key at user creation, and ensure it is not changed later on by using the following hooks:

User.beforeCreate = function(next, data) {
    data.API_KEY = server_generate_api_key();
    next();
};

User.beforeUpdate = function(next, data) {
    delete data.API_KEY;
    next();
};

Alternatively, you could look into the beforeSave hook.

Rick Deckard
  • 1,239
  • 1
  • 11
  • 10