0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

NCMBとMonaca、Framework7を使ってカレンダーアプリを作る(その2:認証の実行)

Last updated at Posted at 2022-11-21

NCMBとMonacaを使ってカレンダーアプリを作ります。予定を登録したり、Framework7のカレンダーコンポーネントを使って予定を表示できるというアプリです。

前回の記事では画面の説明とSDKの導入まで進めましたので、今回は認証を実行します。

コードについて

今回のコードはNCMBMania/monaca-calendar-appにアップロードしてあります。実装時の参考にしてください。

認証画面について

image.png

すでに紹介済みですが、認証画面は以下のようになります。ID/パスワード入力欄があって、ボタンを押すと login 関数が実行されます。

<form id="login">
	<div class="list no-hairlines-md">
		<ul>
			<li>
				<div class="item-content item-input">
					<div class="item-inner">
						<div class="item-title item-label">ユーザーID</div>
						<div class="item-input-wrap">
							<input type="text" name="userName" placeholder="お名前" required/>
						</div>
					</div>
				</div>
			</li>
			<li>
				<div class="item-content item-input">
					<div class="item-inner">
						<div class="item-title item-label">パスワード</div>
						<div class="item-input-wrap">
							<input type="password" name="password" placeholder="パスワード" required/>
						</div>
					</div>
				</div>
			</li>
		</ul>
	</div>
	<div class="block block-strong">
		<p class="row">
			<a href="#" @click=${login} class="col button">ログイン or ユーザー登録</a>
		</p>
	</div>
</form>

ログイン処理について

ログイン処理は、以下のような手順で行われます。

  • 入力値の取得
  • ユーザーの新規登録
  • ログイン処理

すでにユーザー登録を行っていた場合、ユーザーの新規登録はエラーになります。今回はユーザー登録とログインを兼ねているので、エラーが出たとしてもそのまま続けてログイン処理を行っていきます。

入力値の取得

入力値の取得は Framework7の機能を使って行います。

const params = app.form.convertToData($('#login'));

ユーザーの新規登録

取得した入力値を使ってユーザー登録処理を行います。エラーが出たとしても無視します。

const user = new ncmb.User();
// ユーザー名・パスワードを設定
user
	.set("userName", params.userName)
	.set("password", params.password);
try {
	// サインアップ処理
	await user.signUpByAccount();
} catch (e) {
	// エラーはすでにユーザーが存在する場合
}

ログイン処理

そのまま続けてログイン処理を実行します。ログインがうまくいったら、カレンダー画面に遷移します。ログイン失敗した場合は、アラートを出します。

try {
	// 続けてログインの実行
	await ncmb.User.login(params.userName, params.password);
	// ログインしたらカレンダー画面に移行
	$f7router.navigate('/home/');
} catch (e) {
	// 認証エラー
	app.dialog.alert('ユーザーIDまたはパスワードが違います');
}

ここまででNCMBを使った認証処理の完成です。

認証後のユーザー情報について

認証後にユーザー情報を取得する際には、下記のように記述します。

const currentUser = ncmb.User.getCurrentUser();

認証していない場合には null が返ってきます。これを使って認証状態の判別が可能です。

まとめ

今回はカレンダーアプリの認証処理について解説しました。次はカレンダー表示と予定の登録処理を実装します。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?