我正在构建一个不支持公共注册的应用程序。新用户将由现有用户创建,注册电子邮件将发送到新用户的电子邮件地址。我已经完成了这一切,但我的实施感觉很乱。
到目前为止,这是代码。
模板:
<template name="addUser">
<form role="form">
<div class="form-group">
<label for="firstName">First Name</label>
<input name="firstName" class="form-control" placeholder="First Name" />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input name="lastName" class="form-control" placeholder="Last Name" />
</div>
<div class="form-group">
<label for="email">Email</label>
<input name="email" class="form-control" placeholder="Email" />
</div>
<button type="submit" class="btn btn-primary">{{faIcon 'plus'}} Add User</button>
</form>
</template>
模板的Javascript:
Template.addUser.events({
'submit form': function (e, t) {
e.preventDefault();
var attrs = {
email: t.find('[name="email"]').value,
profile: {
firstName: t.find('[name="firstName"]').value,
lastName: t.find('[name="lastName"]').value,
}
};
Meteor.call('addUser', attrs, function (err) {
if (err) {
Errors.throw(err.reason);
} else {
Router.go('home');
}
});
}
});
我的addUser
方法
Meteor.methods({
addUser: function (attrs) {
var user = Meteor.user();
if (!user) throw new Meteor.Error(401, 'Please login.');
if (!attrs.profile.firstName) throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.profile.lastName) throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.email) throw new Meteor.Error(422, 'Please include an email.');
var user = _.pick(attrs, ['firstName', 'lastName', 'email']);
if (Meteor.isServer) {
var newUserId = Accounts.createUser(attrs);
Accounts.sendEnrollmentEmail(newUserId);
}
}
});
由于Accounts.createUser
需要客户端的密码,我无法弄清楚如何通过Session
通知客户成功或失败。做这样事情的好方法是什么?
答案 0 :(得分:2)
首先,仅将addUser
方法放在服务器上(即在server
目录中):
Meteor.methods({
addUser: function (attrs) {
var user = Meteor.user();
if (!user) // you can also check this.userId here
throw new Meteor.Error(401, 'Please login.');
if (!attrs.profile.firstName)
throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.profile.lastName)
throw new Meteor.Error(422, 'Please include a first name.');
if (!attrs.email)
throw new Meteor.Error(422, 'Please include an email.');
var user = _.pick(attrs, ['firstName', 'lastName', 'email']);
var newUserId = Accounts.createUser(attrs);
Accounts.sendEnrollmentEmail(newUserId);
}
});
然后,在客户端上,您可以执行以下操作:
Meteor.call('addUser', attrs, function (err) {
if (err) {
console.log('something went wrong :(');
}
});
答案 1 :(得分:-3)
为用户提供默认密码。
(我建议您使用check()
方法中的addUser
功能 - 替换部分if
语句。此外,只要您不需要Meteor.isServer
将js文件放在/server
文件夹中。)