- 流星教程
- 流星 - 主页
- 流星 - 概述
- Meteor - 环境设置
- Meteor - 首次应用
- 流星 - 模板
- 流星 - 收藏
- 流星 - 形式
- 流星 - 活动
- 流星 - 会话
- 流星 - 追踪器
- 流星 - 套餐
- Meteor - 核心 API
- 流星 - 检查
- 流星 - 烈焰
- Meteor - 计时器
- 流星-EJSON
- 流星 - HTTP
- 流星 - 电子邮件
- 流星 - 资产
- 流星 - 安全
- 流星 - 排序
- 流星 - 账户
- Meteor - 方法
- 流星-Package.js
- Meteor - 发布和订阅
- 流星 - 结构
- 流星 - 部署
- Meteor - 在移动设备上运行
- 流星 - 待办事项应用程序
- Meteor - 最佳实践
- 流星有用资源
- 流星 - 快速指南
- 流星 - 有用的资源
- 流星 - 讨论
流星 - 账户
该软件包允许完整的用户身份验证功能。您可以通过在命令提示符窗口中运行以下代码来添加它。
C:\Users\username\Desktop\meteorApp>meteor add accounts-password
认证示例
此示例将显示基本身份验证。我们将创建注册、登录和主页模板。如果存在当前用户(如果用户已成功注册或登录),则会显示主页模板。如果没有currentUser,则注册和登录模板将可见。
流星App.html
<head>
<title>meteorApp</title>
</head>
<body>
{{#if currentUser}}
{{> home}}
{{else}}
{{> register}}
{{> login}}
{{/if}}
</body>
<template name = "register">
<h2>REGISTER:</h2>
<form>
<input type = "email" name = "registerEmail"><br>
<input type = "password" name = "registerPassword"><br>
<input type = "submit" value = "Register"><br>
</form>
</template>
<template name = "login">
<h2>LOGIN:</h2>
<form>
<input type = "email" name = "loginEmail"><br>
<input type = "password" name="loginPassword"><br>
<input type = "submit" value = "Login"><br>
</form>
</template>
<template name = "home">
<p>You're logged in.</p>
<button class = "logout">Logout</button>
</template>
首先,我们需要创建一个注册事件。该函数将读取寄存器输入,创建一个新用户,并将其存储到数据库中。
第二个事件是登录。这次,该函数将从登录模板中读取输入,如果电子邮件和密码有效则登录用户,如果无效则返回错误。
最后,一旦单击按钮,注销事件将用于注销用户。
流星App.js
if (Meteor.isClient) {
Template.register.events({
'submit form': function(event) {
event.preventDefault();
var registerData = {
email: event.target.registerEmail.value,
password: event.target.registerPassword.value
}
Accounts.createUser(registerData, function(error) {
if (Meteor.user()) {
console.log(Meteor.userId());
} else {
console.log("ERROR: " + error.reason);
}
});
}
});
Template.login.events({
'submit form': function(event) {
event.preventDefault();
var myEmail = event.target.loginEmail.value;
var myPassword = event.target.loginPassword.value;
Meteor.loginWithPassword(myEmail, myPassword, function(error) {
if (Meteor.user()) {
console.log(Meteor.userId());
} else {
console.log("ERROR: " + error.reason);
}
});
}
});
Template.home.events({
'click .logout': function(event) {
event.preventDefault();
Meteor.logout(function(error) {
if(error) {
console.log("ERROR: " + error.reason);
}
});
}
});
}
应用程序启动后,我们将看到以下页面。
在注册表中输入电子邮件和密码后,我们可以注册并登录新用户。我们将看到控制台记录了用户ID并且呈现了主页模板。
登录事件将检查数据库并登录用户,如果电子邮件和密码正确。如果没有,控制台将记录错误。
如果用户单击“注销”按钮,应用程序将注销用户并显示注册和登录模板。