У меня возникли проблемы с настройкой ролей в моем проекте, который использует meteor-collection2. Я предполагаю, что это пакет ролей, отмеченный в документах collection2. Я использую account-password и ian: accounts-ui-bootstrap-3 как решение для своих учетных записей. Вот мой конфиг для него:Метеор, использующий роли аланинга и коллекцию альдемистов2 вместе
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
Я добавил поле ролей в моих пользователях схему:
Schemas.User = new SimpleSchema({
username: {
type: String,
// For accounts-password, either emails or username is required, but not both. It is OK to make this
// optional here because the accounts-password package does its own validation.
// Third-party login packages may not require either. Adjust this schema as necessary for your usage.
optional: true
},
emails: {
type: [Object],
optional: true
},
"emails.$.address": {
type: String,
regEx: SimpleSchema.RegEx.Email
},
"emails.$.verified": {
type: Boolean
},
createdAt: {
type: Date
},
services: {
type: Object,
optional: true,
blackbox: true
},
profile: {
type: Object,
optional: true,
blackbox: true
},
"first-name": {
type: String
},
"last-name": {
type: String
},
// Add `roles` to your schema if you use the meteor-roles package.
// Option 1: Object type
// If you specify that type as Object, you must also specify the
// `Roles.GLOBAL_GROUP` group whenever you add a user to a role.
// Example:
// Roles.addUsersToRoles(userId, ["admin"], Roles.GLOBAL_GROUP);
// You can't mix and match adding with and without a group since
// you will fail validation in some cases.
roles: {
type: Object,
optional: true,
blackbox: true
}
});
А теперь я хочу, чтобы сразу создать одного пользователя в первый раз, когда я запустить свой проект с администратором роль и прекращение создания каких-либо других лиц после этого:
/*----------------------------------------------- #2 Create admin user ----------------------------------------------*/
/*Notes: Create an admin-type user if no users exist yet.*/
if (Meteor.users.find().count() === 0) { /*------------------------------------ If there are no users created yet*/
var users = [{
username: "admin",
name: "admin",
email: "[email protected]",
roles: ['admin']
}];
_.each(users, function(user) {
var id = Accounts.createUser({
username: user.username,
email: user.email,
password: "mypassword123",
profile: {
name: user.name
},
first-name: Me,
last-name: MeName
});
if (user.roles.length > 0) {
// Need _id of existing user record so this call must come
// after `Accounts.createUser` or `Accounts.onCreate`
Roles.addUsersToRoles(id, user.roles);
}
});
}
/*-------------------------------------------------------------------------------------------------------------------*/
/*Prevent non-authorized users from creating new users*/
Accounts.validateNewUser(function(user) {
var loggedInUser = Meteor.user();
if (Roles.userIsInRole(loggedInUser, ['admin'])) {
return true;
}
throw new Meteor.Error(403, "Not authorized to create new users");
});
До сих пор, по-видимому, так хорошо: я получаю нового пользователя.
Проблема заключается в том, когда я использую spacebars, чтобы скрыть функции администратора в HTML созданный пользователь не признаваемых в качестве администратора, и они скрыты от меня ...
{{#if isInRole 'admin'}}
<p>Exclusive to admin stuff</p>
{{/if}}
Работает ли он, если вы создадите помощник шаблона, как показано ниже, и используете его вместо этого? Template.myTemplate.helpers ({ IsAdmin() { возврата Roles.userIsInRole (Meteor.userId(), 'администратор');} }); Извините за плохое форматирование, не уверен, что с ним происходит. –
№ Все еще скрывает его для пользователя admin. – mesosteros
Я просто выполнил следующие два теста на моей консоли: '' 'Meteor.roles.findOne ({}) Объект {_id:" yDn27e2z4GeHwpdRe ", имя:" admin "}' '' и '' 'Метеор.userId() «FQzPJE8Q68ZzwnBqh» '' 'ясно, что мой метеорист userId не назначен правильно для роли – mesosteros