MeteorJSとReactを勉強してみる その8: ユーザーアカウント機能を追加してみよう【公式翻訳】
MeteorJSを勉強してみるシリーズ第八弾です。
やっとユーザーアカウントを追加する段階に来ましたね。 しかもMeteorではユーザーアカウント機能をデフォルトで用意してくれているため、一から自分で作るよりも圧倒的に簡単に機能を追加できます。
ユーザーアカウント機能を追加する
Meteorはアカウント機能とログインユーザーインターフェースを備えており、マルチユーザー機能をアプリに追加することも簡単にできてしまいます。
なお現状ではこのUIコンポーネントはMeteor独自のUIエンジンである「Blaze」を使用しています。Reactを使ったコンポーネントはまだ用意されていませんが、将来的には実装されるかもしれません。
アカウント機能とそのUIを使えるようにするには、関連するパッケージをプロジェクトに追加しなくてはなりません。
アプリのディレクトリに行き、下記のコマンドを打ちましょう。
meteor add accounts-ui accounts-password
BlazeコンポーネントをReactで包む
Blazeのaccounts-ui
UIコンポーネントをReactで使うには、Reactコンポーネントでラップする必要があります。
そのためには、まずAccountsUIWrapperというReactコンポーネントを新しいファイルで作ってあげましょう。
imports/ui/AccountsUIWrapper.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Template } from 'meteor/templating'; import { Blaze } from 'meteor/blaze'; export default class AccountsUIWrapper extends Component { componentDidMount() { // Use Meteor Blaze to render login buttons this.view = Blaze.render(Template.loginButtons, ReactDOM.findDOMNode(this.refs.container)); } componentWillUnmount() { // Clean up Blaze view Blaze.remove(this.view); } render() { // Just render a placeholder container that will be filled in return <span ref="container" />; } }
今作成したこのコンポーネントをApp.jsで読み込んであげましょう。
imports/ui/App.js
before
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { withTracker } from 'meteor/react-meteor-data'; import { Tasks } from '../api/tasks.js'; import Task from './Task.js'; // App Component - represnts the whole app class App extends Component { constructor(props) { super(props); this.state = { hideCompleted: false, }; } handleSubmit(event) { event.preventDefault(); // find the text field via the React ref const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); Tasks.insert({ text, createdAt: new Date() }); // clear form ReactDOM.findDOMNode(this.refs.textInput).value = ''; } renderTasks() { let filteredTasks = this.props.tasks; if (this.state.hideCompleted) { filteredTasks = filteredTasks.filter((task) => !task.checked); } return filteredTasks.map((task) => ( <Task key={task._id} task={task} /> )); } toggleHideCompleted() { this.setState({ hideCompleted: !this.state.hideCompleted }); } render() { return ( <div className="container"> <header> <h1>Todo List ({this.props.incompleteCount})</h1> <label className="hide-completed"> <input type="checkbox" readOnly checked={this.state.hideCompleted} onClick={this.toggleHideCompleted.bind(this)} /> Hide Completed Tasks </label> <form className="new-task" onSubmit={this.handleSubmit.bind(this)}> <input type="text" ref="textInput" placeholder="Type to add new Tasks." /> </form> </header> <ul> {this.renderTasks()} </ul> </div> ); } } export default withTracker(() => { return { tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(), incompleteCount: Tasks.find({ checked: { $ne: true } }).count(), }; })(App);
after
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { withTracker } from 'meteor/react-meteor-data'; import { Tasks } from '../api/tasks.js'; import Task from './Task.js'; import AccountsUIWrapper from './AccountsUIWrapper.js'; // App Component - represnts the whole app class App extends Component { constructor(props) { super(props); this.state = { hideCompleted: false, }; } handleSubmit(event) { event.preventDefault(); // find the text field via the React ref const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); Tasks.insert({ text, createdAt: new Date() }); // clear form ReactDOM.findDOMNode(this.refs.textInput).value = ''; } renderTasks() { let filteredTasks = this.props.tasks; if (this.state.hideCompleted) { filteredTasks = filteredTasks.filter((task) => !task.checked); } return filteredTasks.map((task) => ( <Task key={task._id} task={task} /> )); } toggleHideCompleted() { this.setState({ hideCompleted: !this.state.hideCompleted }); } render() { return ( <div className="container"> <header> <h1>Todo List ({this.props.incompleteCount})</h1> <label className="hide-completed"> <input type="checkbox" readOnly checked={this.state.hideCompleted} onClick={this.toggleHideCompleted.bind(this)} /> Hide Completed Tasks </label> <AccountsUIWrapper /> <form className="new-task" onSubmit={this.handleSubmit.bind(this)}> <input type="text" ref="textInput" placeholder="Type to add new Tasks." /> </form> </header> <ul> {this.renderTasks()} </ul> </div> ); } } export default withTracker(() => { return { tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(), incompleteCount: Tasks.find({ checked: { $ne: true } }).count(), }; })(App);
Then, add the following code to configure the accounts UI to use usernames instead of email addresses:
さらに、imports
配下にstartup
ディレクトリを作成し、その中にaccounts-config.js
を作成しましょう。
これはaccounts-uiのログイン時にメールアドレスではなくユーザーネームを使用するようにするための設定です。
imports/startup/accounts-config.js
import { Accounts } from 'meteor/accounts-base'; Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY', });
We also need to import that configuration code in our client side entrypoint:
この設定コードはクライアント側のエントリーポイント(client/main.js
)で読み込んであげましょう。
client/main.js
before
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import App from '../imports/ui/App.js'; Meteor.startup(() => { render(<App />, document.getElementById('render-target')); });
after
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import '../imports/startup/accounts-config.js'; import App from '../imports/ui/App.js'; Meteor.startup(() => { render(<App />, document.getElementById('render-target')); });
ユーザーに関連する機能を追加する
これでユーザーはアカウントを作成し、アプリにログイン出来るようになりました。 とても素晴らしいのですが、ログインできるだけでは便利じゃありませんね。 ということで、二つ新しい機能を追加しましょう。
- ログイン中のユーザーにのみタスク入力欄を表示する
- どのユーザーがどのタスクを作ったのかを表示する
これらを実装するため、タスクコレクションに二つの新しいフィールドを持たせましょう。
- owner: タスクを作ったユーザーのid
- username: タスクを作ったユーザーのユーザーネーム
ここでは、タスクを表示するたびに毎回ユーザーを探しにいかなくても良いように、タスクオブジェクトに直接ユーザーネームを保存します。
まず、タスク追加時に上記のフィールドを保存するために、App.js
のhandleSubmit
イベントハンドラに追記しましょう。
現在ログインしているユーザーの情報を取得するため、データコンテナにも追記します。
そして入力フォームを表示するのはログインしているユーザーだけ、という条件を付け加えましょう。
imports/ui/App.js
before
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { withTracker } from 'meteor/react-meteor-data'; import { Tasks } from '../api/tasks.js'; import Task from './Task.js'; import AccountsUIWrapper from './AccountsUIWrapper.js'; // App Component - represnts the whole app class App extends Component { constructor(props) { super(props); this.state = { hideCompleted: false, }; } handleSubmit(event) { event.preventDefault(); // find the text field via the React ref const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); Tasks.insert({ text, createdAt: new Date() }); // clear form ReactDOM.findDOMNode(this.refs.textInput).value = ''; } renderTasks() { let filteredTasks = this.props.tasks; if (this.state.hideCompleted) { filteredTasks = filteredTasks.filter((task) => !task.checked); } return filteredTasks.map((task) => ( <Task key={task._id} task={task} /> )); } toggleHideCompleted() { this.setState({ hideCompleted: !this.state.hideCompleted }); } render() { return ( <div className="container"> <header> <h1>Todo List ({this.props.incompleteCount})</h1> <label className="hide-completed"> <input type="checkbox" readOnly checked={this.state.hideCompleted} onClick={this.toggleHideCompleted.bind(this)} /> Hide Completed Tasks </label> <AccountsUIWrapper /> <form className="new-task" onSubmit={this.handleSubmit.bind(this)}> <input type="text" ref="textInput" placeholder="Type to add new Tasks." /> </form> : '' </header> <ul> {this.renderTasks()} </ul> </div> ); } } export default withTracker(() => { return { tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(), incompleteCount: Tasks.find({ checked: { $ne: true } }).count() }; })(App);
after
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from 'meteor/meteor'; import { withTracker } from 'meteor/react-meteor-data'; import { Tasks } from '../api/tasks.js'; import Task from './Task.js'; import AccountsUIWrapper from './AccountsUIWrapper.js'; // App Component - represnts the whole app class App extends Component { constructor(props) { super(props); this.state = { hideCompleted: false, }; } handleSubmit(event) { event.preventDefault(); // find the text field via the React ref const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); Tasks.insert({ text, createdAt: new Date(), owner: Meteor.userId(), username: Meteor.user().username }); // clear form ReactDOM.findDOMNode(this.refs.textInput).value = ''; } renderTasks() { let filteredTasks = this.props.tasks; if (this.state.hideCompleted) { filteredTasks = filteredTasks.filter((task) => !task.checked); } return filteredTasks.map((task) => ( <Task key={task._id} task={task} /> )); } toggleHideCompleted() { this.setState({ hideCompleted: !this.state.hideCompleted }); } render() { return ( <div className="container"> <header> <h1>Todo List ({this.props.incompleteCount})</h1> <label className="hide-completed"> <input type="checkbox" readOnly checked={this.state.hideCompleted} onClick={this.toggleHideCompleted.bind(this)} /> Hide Completed Tasks </label> <AccountsUIWrapper /> { this.props.currentUser ? <form className="new-task" onSubmit={this.handleSubmit.bind(this)}> <input type="text" ref="textInput" placeholder="Type to add new Tasks." /> </form> : '' } </header> <ul> {this.renderTasks()} </ul> </div> ); } } export default withTracker(() => { return { tasks: Tasks.find({}, { sort: { createdAt: -1 } }).fetch(), incompleteCount: Tasks.find({ checked: { $ne: true } }).count(), currentUser: Meteor.user() }; })(App);
最後に、各タスクの左側に、そのタスクを追加したユーザーのユーザーネームを表示するためのコードを追記しましょう。
imports/ui/Task.js
before
import React, { Component } from 'react'; import { Tasks } from '../api/tasks.js'; // Task component - represents a single todo item export default class Task extends Component { toggleChecked() { // set the checked property to the opposite of its current value Tasks.update(this.props.task._id, { $set: { checked: !this.props.task.checked }, }) }; deleteThisTask() { Tasks.remove(this.props.task._id); }; render() { // give tasks a different className when they are checked off, // so that we can style them nicely in CSS. const taskClassName = this.props.task.checked ? 'checked' : ''; return ( <li className={ taskClassName }> <button className="delete" onClick={ this.deleteThisTask.bind(this) }> × </button> <input type="checkbox" readOnly checked={ !!this.props.task.checked } onClick={ this.toggleChecked.bind(this) } /> <span className="text">{ this.props.task.text }</span> </li> ); } }
after
import React, { Component } from 'react'; import { Tasks } from '../api/tasks.js'; // Task component - represents a single todo item export default class Task extends Component { toggleChecked() { // set the checked property to the opposite of its current value Tasks.update(this.props.task._id, { $set: { checked: !this.props.task.checked }, }) }; deleteThisTask() { Tasks.remove(this.props.task._id); }; render() { // give tasks a different className when they are checked off, // so that we can style them nicely in CSS. const taskClassName = this.props.task.checked ? 'checked' : ''; return ( <li className={ taskClassName }> <button className="delete" onClick={ this.deleteThisTask.bind(this) }> × </button> <input type="checkbox" readOnly checked={ !!this.props.task.checked } onClick={ this.toggleChecked.bind(this) } /> <span className="text"> <strong>{ this.props.task.username }</strong>: { this.props.task.text } </span> </li> ); } }
ブラウザで、まずは自分のアカウントを作成してください。 その上でログインすると、タスク入力欄が表示されると思います。 その状態でタスクを追加すると、自分のユーザーネームと一緒にタスクが表示されるようになっているでしょうか。
以前までに追加したタスクにはユーザーネームがついていませんね。
さて、ユーザーはログインできるようになり、各タスクがどのユーザーに紐付いているのか分かるようになりました。
本ステップで初めて出てきたMeteorの特徴について、もう少し詳しく見ておきましょう。
自動化されたアカウントUI
Meteorで作成中のアプリにaccounts-ui
パッケージが含まれているなら、ログインメニューを作成するのに必要なのはUIコンポーネントをレンダリングすることだけです。
このログイン機能は、どのログインメソッドがアプリに追加されているかを自動で検知し、最適なUIを表示します。
今回のケースでは、利用可能になっているメソッドはaccounts-password
のみですので、ドロップダウンメニューにはパスワード入力欄しかありません。
もし他の機能も試してみたければ、accounts-facebook
パッケージを追加して、Facebookログインボタンを有効化することもできます。
ログイン中ユーザーの情報取得について
データコンテナでは、Meteor.user()
を使ってユーザーがログイン中かどうかを判定し、彼らの情報を取得することができます。
例えば、Meteor.user().username
はログインユーザーのユーザーネームを持っています。
同様に、Meteor.userId()
ではログインユーザーのユーザーIDを取得できます。
次のステップでは、サーバーでデータの検証を行うことで作成中のアプリをセキュアにする方法を学んでいきます。
非常に簡単にユーザーアカウント機能を追加することができましたね。
めちゃくちゃ簡単なのは良い点も悪い点もあり、良い点としては単純に実装が早くなること、悪い点は最悪何も理解してなくても実装できてしまうこと、既存の実装をうまいこと改変することができない or 難しいと想定されることです。
でも、とりあえず作りたいものがある、という場合にはやっぱり非常にありがたい用意ですよね。
ついでにですが、Facebookログイン機能は少なくともローカルでアプリを作成中の段階では有効化できなさそうです。 これはMeteorの問題というより、Facebook側のバリデーションの関係で無理な気がしています。
抜け道があるのかどうかまでは調べていないので、どうしてもローカルホストで試したいんだ、という人はググってみてくださいね。
次の更新は明日、もしくは週明けくらいになると思います。