委任管理:書き込みフック
書き込みフックはユーザーを作成または更新するときに必ず実行され、以下などを行えるようにします。
ユーザーのパスワードを変更する
ユーザーのメールアドレスを変更する
ユーザープロファイルを更新する
また、書き込みフックを使用して、新たに作成されたユーザーにデフォルト値を自動的に設定することもできます。たとえば、ユーザーを自分と同じグループ、部署やベンダーに自動的に割り当てたい場合などです。
フックコントラクト
ctx:コンテキストオブジェクトです。
request.originalUser:payloadが新しいフィールドセットである現在のユーザーの値です。メソッドがupdateの場合にのみ使用できます。
payload:ペイロードオブジェクトです。
memberships:ユーザーの作成時にUIで選択されたメンバーシップの配列です。
email:ユーザーのメールアドレスです。
password:ユーザーのパスワードです。
connection:データベース接続の名前です。
app_metada:編集されたカスタムフィールドが
app_metadata
に保存されている場合に含まれるデータです。user_metadata:編集されたカスタムフィールドが
user_metadata
に保存されている場合に含まれるデータです。
userFields:ユーザーフィールドの配列です(設定クエリで指定されている場合)
methods:設定を呼び出した結果か、それとも更新を呼び出した結果かに応じて、createまたはupdateになります。
callback(error, user):Management APIに送信するべきエラーとユーザーオブジェクトを返すことができるコールバックです。
userFieldsの詳細については、「委任管理:設定クエリフック」をお読みください。
使用例
Kellyは経理部を管理しています。Kellyがユーザーが作成するときには、ユーザーが経理部のメンバーとして割り当てられなければなりません。
function(ctx, callback) {
var newProfile = {
email: ctx.payload.email,
password: ctx.payload.password,
connection: ctx.payload.connection,
user_metadata: ctx.payload.user_metadata,
app_metadata: {
department: ctx.payload.memberships && ctx.payload.memberships[0],
...ctx.payload.app_metadata
}
};
if (!ctx.payload.memberships || ctx.payload.memberships.length === 0) {
return callback(new Error('The user must be created within a department.'));
}
// Get the department from the current user's metadata.
var currentDepartment = ctx.request.user.app_metadata && ctx.request.user.app_metadata.department;
if (!currentDepartment || !currentDepartment.length) {
return callback(new Error('The current user is not part of any department.'));
}
// If you're not in the IT department, you can only create users within your own department.
// IT can create users in all departments.
if (currentDepartment !== 'IT' && ctx.payload.memberships[0] !== currentDepartment) {
return callback(new Error('You can only create users within your own department.'));
}
if (ctx.method === 'update') {
// If updating, only set the fields we need to send
Object.keys(newProfile).forEach(function(key) {
if (newProfile[key] === ctx.request.originalUser[key]) delete newProfile[key];
});
}
// This is the payload that will be sent to API v2. You have full control over how the user is created in API v2.
return callback(null, newProfile);
}
Was this helpful?