LoginSignup
2
5

More than 3 years have passed since last update.

Strapiのユーザーログイン時に処理を追加する

Last updated at Posted at 2020-08-20

Strapiのstrapi-plugin-users-permissionsID/PASSでのログイン時の処理に,
ビジネスロジックを入れ込むことをしたのでやり方の共有

strapiは3.1.4で検証

strapi/packages/strapi-plugin-users-permissions at master · strapi/strapi

新規にPoliciesを作成をする

ドキュメント通りにPoliciesを作ると、Strapiのstrapi-plugin-users-permissions/config/routes.jsonを書き換える必要が出てくる.
Strapiのアップデートが辛くなるので, この方法はやりたくない...

ので、estenstions/users-permissions/config/policies/までフォルダをく作って、その中に新規にPoliciesを作成をする.

// パス
// extensions/users-permissions/config/policies/send-mail-on-login-notify.js

'use strict';

module.exports = async (ctx, next) => {
  console.log('In sendMailOnLoginNotify policy.');

  await next();

  if (ctx.status === 200) {
    // ログイン成功時の処理
    console.log("success login.");
  } else {
    // ログイン失敗時の処理
    console.log("fail login.");
  }
};

ログイン時のauth/callbackPoliciesを追加する

GUIから動的に変更ができる.

ロールと権限 -> Publicロールを編集する
Strapi_-_Roles___Permissions.png

USERS-PERMISSIONScallbackの設定ボタンをタップすると,
高度な設定が設定できるので、そこから新規で作成をしたPliciesを選択する.
貼り付けた画像_2020_08_20_23_54.png

ログインをしてみる

ログイン成功時

strapi_1   | [2020-08-20T14:58:56.710Z] debug OPTIONS /auth/local (0 ms) 204
strapi_1   | In sendMailOnLoginNotify policy.
strapi_1   | success login.
strapi_1   | [2020-08-20T14:58:59.765Z] debug POST /auth/local (3051 ms) 200

ログイン失敗時

strapi_1   | [2020-08-20T15:00:24.445Z] debug OPTIONS /auth/local (1 ms) 204
strapi_1   | In sendMailOnLoginNotify policy.
strapi_1   | fail login.
strapi_1   | [2020-08-20T15:00:24.554Z] debug POST /auth/local (106 ms) 400

(๑•̀ㅂ•́)و✧ ヨッシ!

おまけ

起動時に動的に/auth/callbackのPoliciesを変更する方法
bootstrapに処理に追加をすれば, 共同開発者も幸せになれる.

// パス
// strapi/config/functions/bootstrap.js

module.exports = async () => {
  const role = await strapi.query('role', 'users-permissions')
    .findOne({type: 'public'});
  await strapi.query('permission', 'users-permissions')
    .update(
      {
        role: role.id,
        controller: 'auth',
        action: 'callback',
      },
      {
        policy: "send-mail-on-login-notify"
      });
};
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5