LoginSignup
16
17

More than 5 years have passed since last update.

Hubot の標準的な権限管理 (hubot-auth)

Last updated at Posted at 2014-11-13

問題

Hubot 2.9.x 時代の標準的な権限管理についての日本語リソースが少ない。

解決策

ぼくが書く。覚え書きをかねて。

ここでは hubot-auth@1.1.2 について説明する。

github/hubot-scripts の auth.coffee

deprecated。忘れろ。

hubot-auth

Hubot 2.9.x 現在で、標準的な権限管理の仕組み。以下の機能を提供する。

  • Hubot の User 向けの Auth クラスの提供
  • それを操作するコマンドの提供

インストール

一般的な Hubot スクリプトと同様。

npm install --save hubot-auth からの external-scripts.json への追記。

設定

HUBOT_AUTH_ADMIN ... 管理者を設定する。カンマ区切りで user.id を設定する。これは adapter 依存の値なので一概には言えない。

コマンド

# Commands:
# hubot <user> has <role> role - Assigns a role to a user
# hubot <user> doesn't have <role> role - Removes a role from a user
# hubot what roles does <user> have - Find out what roles a user has
# hubot what roles do I have - Find out what roles you have
# hubot who has <role> role - Find out who has the given role
  • hubot <user> has <role> role - ロールをユーザーに割り当てる。管理者しか実行できない。
  • hubot <user> doesn't have <role> role - ロールをユーザーから取り除く。管理者しか実行できない。
  • hubot what roles does <user> have - ユーザーに割り当てられたロールを返す。
  • hubot what roles do I have - 発言者自身に割り当てられたロールを返す。
  • hubot who has <role> role - ロールの割り当てられたユーザーを返す。

Auth クラス

  class Auth
    isAdmin: (user) ->
      user.id.toString() in admins

    hasRole: (user, roles) ->
      userRoles = @userRoles(user)
      if userRoles?
        roles = [roles] if typeof roles is 'string'
        for role in roles
          return true if role in userRoles
      return false

    usersWithRole: (role) ->
      users = []
      for own key, user of robot.brain.data.users
        if @hasRole(user, role)
          users.push(user.name)
      users

    userRoles: (user) ->
      roles = []
      if user? and robot.auth.isAdmin user
        roles.push('admin')
      if user.roles?
        roles = roles.concat user.roles
      roles

  robot.auth = new Auth

他のスクリプトからの使いかた

#   * Call the method: robot.auth.hasRole(msg.envelope.user,'<role>')
#   * returns bool true or false

robot.auth.hasRole(msg.envelope.user, '<role>') でロールの有無をチェックできる。

具体例

管理者には 'Sir! Yes! Sir!' を返し、
developer ロールを持っているユーザーには Hi. を返し、
それ以外には '???' を返す例。

module.exports = (robot) ->
  robot.respond /hello/, (msg) ->
    # 権限チェック
    if robot.auth.isAdmin(msg.envelope.user)
      msg.send 'Sir! Yes! Sir!'
    else if robot.auth.hasRole(msg.envelope.user, 'developer')
      msg.send 'Hi.'
    else
      msg.send '???'

その他注意事項

  • 管理者権限の書き換えはできない。環境変数のみで設定できる。
  • 設定した権限は永続化していないと再起動などで消えてしまう。hubot-redis-brain などの brain 系スクリプトで、永続化しておくこと。

関連 Qiita 投稿

16
17
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
16
17