Accountsまわりについて

自己紹介

  • TeYmmt (Teruhisa Yamamoto)
  • Javascript, nodejs歴1年ちょい
  • Meteor歴1ヶ月ぐらい
  • リアルタイムアプリを日々模索中

発表内容

  • Meteorで標準搭載されている、
    アカウント(Accounts)機能について
    調べたことをお伝えします

    = 以下のドキュメントの中身を喋ります
    • Meteor Guide (Users and Accounts)
    • meteor-useraccounts/core パッケージ

Tutorialでは。

  • meteor add accounts-ui accounts-password して
  • {{> loginButtons}} って書いて
  • Meteor.userId() でログイン中のユーザーID参照したり

どうやら、 

  • 簡単に使えるUIとユーザー(アカウント)管理用のパッケージが用意されてるっぽい
  • facebookとかtwitterとかのアカウントも使えるっぽい
  • なんとなく宜しくやってくれてるっぽい

、ってことは何となく分かる。

Accountsの基本

  • accounts-base
    Meteor.user()Meteor.userId(), etc.
    ログイン管理、ユーザー管理などの基本機能を提供
    (※デフォルトでインストール済み)
     
  • accounts-ui
    簡素なログインUIを提供
    以下のパッケージで好きなものを追加して使用
    accounts-password (オリジナルなアカウント管理が可能), accounts-facebook, accounts-google, accounts-github, accounts-twitter, accounts-meetup, accounts-meteor-developer

accounts-facebook

accounts-password

{{> loginButtons}}

HTML ( with Blaze )

Accountsの基本

  • useraccounts:core
    • Meteorのユーザーアカウント機能の根幹
    • カスタマイズ可能
    • 他言語対応
    • バリデーション機能の提供
    • ログイン後のリダイレクト設定

( インストールする必要なし )

useraccounts:core

  • スタイルのバージョン
    今のところ、以下から選択可能
    Twitter Bootstrap (useraccounts:bootstrap) 
    Zurb Foundation (
    useraccounts:foundatio)
    Ionic (useraccounts:ionic)
    Materialize (useraccounts:materialize)
    Polymer (WIP) (useraccounts:polymer)
    Ratchet (useraccounts:ratchet)
    Semantic UI (useraccounts:semantic-ui)
    plus others coming soon...

    *plain html and no CSS rules (useraccounts:unstyled )

useraccounts:core

Setup方法(※うまくいかない場合は一度入れなおしてみることをおすすめ:追記2016/3/2)

meteor add useraccounts:bootstrap

meteor add accounts-password
meteor add accounts-facebook
meteor add accounts-google
meteor add service-configuration
meteor add accounts-ui

サードパーティーログインサービス設定

※設定しないとfacebook等のログインボタンなどが表示されない

useraccounts:core

使用できるテンプレート

{{> atForm}}

のみ。

だけど、

sign in, sign up, forgot password, reset password, change password, and enroll account forms
アカウント機能に必要なものは網羅している。

※navbars用に、基本的なログインボタンがあったりもする
{{> atNavButton}

{{> atForm}}

  • 特定の機能のみを提供できるように、変数が用意されている
    ex.)  {{> atForm state='signUp'}}

{{> atForm}}

Basic Customization

  • I18n Support (他言語化)
    T9n.setLanguage('<lang>'); //任意の場所に記述
     
  • API設定
    AccountsTemplates.configureRoute(route_code, options);
    AccountsTemplates.configure(options);
    ※Meteor.startup()内で記述してはダメ
    ※サーバーとクライアント両方から呼び出しの出来るファイルに記述すること(たとえば、lib/config/at_config.js)

    optionsで設定できる例
     confirmPassword, sendVerificationEmail, 
     showForgotPasswordLink, positiveValidation, onLogoutHook,
     texts (ボタンなどの文字列変更), etc....

Basic Customization

  • reCaptcha が使える

Google が提供してくれるコレ

Basic Customization

  • アカウント用フォームの準備待ちと完了検知
<template name="myLogin">
 {{#if atDisabled}}
  Please wait...
 {{/if}}
 <div class="{{atClass}}">
  {{> atForm}}
 </div>
</template>
Template.myLogin.helpers({
 atDisabled: function() {
  //成功失敗にかかわらず完了したらfalseを返す
  return AccountsTemplates.disabled(); 
 },
 atClass: function() {
  return AccountsTemplates.disabled() ? 'disabled' : 'active';
 }
});

Advanced Customization

  • フォーム項目のテキスト変更、
    ソーシャルログインのアイコン変更が可能
     
  • クライアント側でのユーザー作成を禁止する
AccountsTemplates.configure({
    forbidClientAccountCreation: true
});

Advanced Customization

  • 登録フォームの項目のカスタマイズが可能
AccountsTemplates.addField({
    _id: 'name', // ユニークなフィールド名
    type: 'text', // 他にはpassword, email, tel, url, checkbox, select, radio, hidden
    displayName: "Name",
    func: function(value){return value !== 'Full Name';}, // バリデーション用
    errStr: 'Only "Full Name" allowed!',
});

Advanced Customization

  • Checkboxes, Selects, Radios, Hidden も追加可能
AccountsTemplates.addField({
    _id: "fruit",
    type: "radio",
    displayName: "Preferred Fruit",
    select: [
        {
        text: "Apple",
        value: "aa",
      }, {
        text: "Banana",
        value: "bb",
      }, {
        text: "Carrot",
        value: "cc",
      },
    ],
});

Advanced Customization

  • フィールドの削除
  • 特別なフィールドの再定義
AccountsTemplates.removeField('password');
AccountsTemplates.addField({
    _id: 'password',
    type: 'password',
    required: true,
    minLength: 6,
    re: /(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/,
    errStr: 'At least 1 digit, 1 lower-case and 1 upper-case',
});

Advanced Customization

var pwd = AccountsTemplates.removeField('password'); 
//↑表示するフォームの順番を変更するため
AccountsTemplates.removeField('email');
AccountsTemplates.addFields([
  {
      _id: "username", 
     type: "text", displayName: "username",  required: true,  
     minLength: 5,
  },
  {
      _id: 'email', 
      type: 'email', displayName: "email", required: true, 
      re: /.+@(.+){2,}\.(.+){2,}/,
      errStr: 'Invalid email',
  },
  {
      _id: 'username_and_email',
      type: 'text',
      required: true,
      displayName: "Login",
  },
  pwd //ここに配置
]);

Advanced Customization

  • フォームのテンプレート拡張
     
  • フィールドを自由に設定できるので、
    複数 email アドレス設定
     
  • パスワード変更確認、
    管理者によるユーザー追加通知などの設定
     
  • メールに提示する各種URLリンクの設定
     
  • メール内容の変更
    (悪夢をみるHTMLメールはやめたほうが良さそう)

Custom data about users

  • Add top-level fields onto the user document
    任意のフィールドを作る場合は、最上位のフィールドに作ること
  • Adding fields on user registration
    例えば、facebookアカウント等でユーザー作成がされた最初のタイミングで任意のフィールドを作りたい場合、Accounts.onCreateUser関数を使うこと
  • Don’t use profile
    profileフィールドは、デフォルトでクライアントサイドでの編集が許されてしまっているので、安易に管理者フラグみたいなものを作らないこと。(Meteor.users.deny()は設定しておくこと)

Custom data about users

  • Publishing custom data
    ユーザー情報は個人情報を含むので、publishする場合は気をつけること。(サーバーサイドでフィルターかけておく)
  • Roles and permissions
    例えば、ブログ記事投稿でアドミンや一般ユーザーのパーミッションを考える場合、2通りの方法が思いつく。
    ・Role-based permissions
    ・Per-document permissions

Roles and permissions

  • Role-based permissionsalanning:rolesの利用
// Give Alice the 'admin' role
Roles.addUsersToRoles(aliceUserId, 'admin', Roles.GLOBAL_GROUP);

// Give Bob the 'moderator' role for a particular category
Roles.addUsersToRoles(bobsUserId, 'moderator', categoryId);
const forumPost = Posts.findOne(postId);

const canDelete = Roles.userIsInRole(userId,
  ['admin', 'moderator'], forumPost.categoryId);

if (! canDelete) {
  throw new Meteor.Error('unauthorized',
    'Only admins and moderators can delete posts.');
}

Posts.remove(postId);

ユーザーが権限を持っているかチェックする

Roles and permissions

  • Per-document permissions
    collectionのhelpersに編集可能かどうかを判別する関数を定義 (dburles:collection-helpers)
Lists.helpers({
  // ...
  editableBy(userId) {
    if (!this.userId) {
      return true;
    }

    return this.userId === userId;
  },
  // ...
});
const list = Lists.findOne(listId);

if (! list.editableBy(userId)) {
  throw new Meteor.Error('unauthorized',
    'Only list owners can edit private lists.');
}

まとめ

  • UIも含め簡単に導入できるけど、お作法は大事
  • カスタマイズする場合も十分に対応
  • useraccounts:coreのドキュメント読むべし

Thank you.

Have a nice Meteor Life.

about accounts

By Teruhisa Yamamoto

about accounts

  • 109