export function setupAccount(appSecret, password, callback) { // remove any existing super users const superUsers = Roles.getUsersInRole('super-admin'); if (superUsers.count() > 0) { superUsers.forEach((superUser) => Meteor.users.remove(superUser._id)); } const options = { username: appSecret, password, }; const superUserId = Accounts.createUser(options); Roles.addUsersToRoles(superUserId, 'super-admin'); const result = { superUserId, }; // add a hook to store last logged in time for each user Accounts.onLogin(() => { const id = Meteor.userId(); Meteor.users.update({ _id: id, }, { $set: { lastLogin: new Date() }, } ); }); callback(null, result); }
users.forEach(({ email, password, profile, roles }) => { const userExists = Meteor.users.findOne({ 'emails.address': email }); if (!userExists) { const userId = Accounts.createUser({ email, password, profile }); Roles.addUsersToRoles(userId, roles[0]); Roles.addUsersToRoles(userId, roles[1]); } });
Meteor.publish("Packages", function (shopCursor) { check(shopCursor, Match.Optional(Object)); const self = this; const shop = shopCursor || Reaction.getCurrentShop(); // user is required. if (self.userId) { // default options, we're limiting fields here that we don't want to publish unless admin user. in particular, settings // should not be published but we need to use settings in the transform everything except settings.public and // settings.*.enabled are removed in transform let options = { fields: { shopId: 1, name: 1, enabled: 1, registry: 1, layout: 1, icon: 1, settings: 1, audience: 1 } }; // we should always have a shop if (shop) { // if admin user, return all shop properties if (Roles.userIsInRole(self.userId, [ "dashboard", "owner", "admin" ], Reaction.getShopId() || Roles.userIsInRole(self.userId, [ "owner", "admin" ], Roles.GLOBAL_GROUP))) { options = {}; } // observe and transform Package registry adds i18n and other meta data const observer = Packages.find({ shopId: shop._id }, options).observe({ added: function (doc) { self.added("Packages", doc._id, transform(doc, self.userId)); }, changed: function (newDoc, origDoc) { self.changed("Packages", origDoc._id, transform(newDoc, self.userId)); }, removed: function (origDoc) { self.removed("Packages", origDoc._id); } }); self.onStop(function () { observer.stop(); }); } return self.ready(); } });
disapproveAccount: function(userId) { let currentUserId = Meteor.userId(); if(currentUserId == userId) { throw new Meteor.Error(400, "You can not disapprove your own account."); } if(Roles.userIsInRole(currentUserId, "admin")) { Roles.removeUsersFromRoles(userId, "approved"); } else { throw new Meteor.Error(401, "Unauthorized"); } },
updateRoles: function (targetUserId, roles, group) { var loggedInUser = Meteor.user() if (!loggedInUser || !Roles.userIsInRole(loggedInUser, ['manage-users', 'support-staff'], group)) { throw new Meteor.Error(403, "Access denied") } Roles.setUserRoles(targetUserId, roles, group); },
myAgencies:() => { let agencies = Roles.getGroupsForUser(Meteor.userId()); let administratorAgencies = agencies.filter(function (agency) { return Roles.userIsInRole(Meteor.userId(), 'administrator', agency) && agency != 'noagency'; }); if ( !Roles.userIsInRole(Meteor.userId(), 'administrator', 'allAgencies')) { this.agencies = Agency.find({_id: {$in: administratorAgencies}, activeUntil: {$gt: new Date()}}); } else { //superUser with allAgencies gets to see everything this.agencies = Agency.find(); } return this.agencies; }
Meteor.publish("UserProfile", function (profileUserId) { check(profileUserId, Match.OneOf(String, null)); if (this.userId === null) { return this.ready(); } const shopId = Reaction.getShopId(); if (!shopId) { return this.ready(); } const permissions = ["dashboard/orders", "owner", "admin", "dashboard/customers"]; // no need to normal user so see his password hash const fields = { "emails": 1, "name": 1, "profile.lang": 1, "profile.firstName": 1, "profile.lastName": 1, "profile.familyName": 1, "profile.secondName": 1, "profile.name": 1, "services.twitter.profile_image_url_https": 1, "services.facebook.id": 1, "services.google.picture": 1, "services.github.username": 1, "services.instagram.profile_picture": 1 }; // TODO: this part currently not working as expected. // we could have three situation here: // 1 - registered user log in. // 2 - admin log in // 3 - admin want to get user data // I'm not sure about the 3rd case, but we do not cover 2nd case here, because // we can see a situation when anonymous user still represented by // `profileUserId`, but admin user already could be found by `this.userId` // In that case what we should do here? if (profileUserId !== this.userId && Roles.userIsInRole(this.userId, permissions, shopId || Roles.userIsInRole(this.userId, permissions, Roles.GLOBAL_GROUP))) { return Meteor.users.find({ _id: profileUserId }, { fields: fields }); } return Meteor.users.find({ _id: this.userId }, { fields: fields }); });
deleteUser: function (targetUserId, group) { var loggedInUser = Meteor.user() if (!loggedInUser || !Roles.userIsInRole(loggedInUser, ['manage-users', 'support-staff'], group)) { throw new Meteor.Error(403, "Access denied") } // remove permissions for target group Roles.setUserRoles(targetUserId, [], group) // do other actions required when a user is removed... },
Template.registerHelper("currentUser", () => { if (typeof Reaction === "object") { const shopId = Reaction.getShopId(); const user = Accounts.user(); if (!shopId || typeof user !== "object") return null; // shoppers should always be guests const isGuest = Roles.userIsInRole(user, "guest", shopId); // but if a user has never logged in then they are anonymous const isAnonymous = Roles.userIsInRole(user, "anonymous", shopId); return isGuest && !isAnonymous ? user : null; } return null; });
disableAdmin: function(userId) { let currentUserId = Meteor.userId(); if(currentUserId == userId) { throw new Meteor.Error(400, "You can not remove yourself from the admin role."); } if(Roles.userIsInRole(currentUserId, "admin")) { let admins = Roles.getUsersInRole('admin'); if(admins.count() < 2) { throw new Meteor.Error(400, "System must have at least one admin."); } Roles.removeUsersFromRoles(userId, "admin"); } else { throw new Meteor.Error(401, "Unauthorized"); } },
export function assignOwnerRoles(shopId, pkgName, registry) { const defaultRoles = ["owner", "admin", "createProduct", "guest", pkgName]; const globalRoles = defaultRoles; if (registry) { // for each registry item define and push roles for (const registryItem of registry) { // packages don't need to define specific permission routes., // the routeName will be used as default roleName for each route. // todo: check dependency on this. const roleName = getRouteName(pkgName, registryItem); if (roleName) { defaultRoles.push(roleName); } // Get all defined permissions, add them to an array // define permissions if you need to check custom permission if (registryItem.permissions) { for (const permission of registryItem.permissions) { defaultRoles.push(permission.permission); } } } } else { Logger.debug(`No routes loaded for ${pkgName}`); } // only unique roles const defaultOwnerRoles = _.uniq(defaultRoles); // get existing shop owners to add new roles to const owners = []; const shopOwners = Roles.getUsersInRole(defaultOwnerRoles).fetch(); // just a nice warning. something is misconfigured. if (!shopOwners) { Logger.warn("Cannot assign roles without existing owner users."); return; } // assign this package permission to each existing owner. for (const account of shopOwners) { owners.push(account._id); } // we don't use accounts/addUserPermissions here because we may not yet have permissions Roles.addUsersToRoles(owners, defaultOwnerRoles, shopId); // the reaction owner has permissions to all sites by default Roles.addUsersToRoles(owners, globalRoles, Roles.GLOBAL_GROUP); Logger.debug(`Owner permissions added for ${pkgName}`); }
(user) => { //console.log('checkIsRootP()'); //console.log(user); if(!_.has(user, 'roles')){ //if roles is not defined in the user, then check in the server to //see if the given user has thoser permissions Meteor.call('misas.users.checkIsRoot', (error, result) => { if(!_.isNil(error)){ deferred.reject('AUTH_REQUIRED'); return; } if(!_.isBoolean(result) || !result){ deferred.reject('AUTH_REQUIRED'); console.log('AUTH_REQUIRED'); return; } deferred.resolve(user); }); } else { //check in the roles when it is available //console.log("checkIsRootP():"); let isRoot = Roles.userIsInRole(user._id, ['root'], Roles.GLOBAL_GROUP); if(!isRoot){ deferred.reject('AUTH_REQUIRED'); console.log('AUTH_REQUIRED'); return; } deferred.resolve(user); } },
var checkIsRoot = () => { let userId = Meteor.userId(); if(userId != null){ return Roles.userIsInRole(userId, ['root'], Roles.GLOBAL_GROUP); } return false; };
render() { let that = this; function createMarkup() { return {__html: that.props.event.description}; }; let canEdit; if(Meteor.user()) { if(Roles.userIsInRole(Meteor.user()._id, 'admin')) { canEdit = true; } else { canEdit = false; } } let pastEvent = this.props.event.date < new Date(); return ( <div className="ui container two column stackable grid"> <div className="five wide column"> <Card className="profileCard"> <Content> <Header>{this.props.event.title}</Header> <div className="speaker"> {this.props.event.speaker} </div> </Content> <Content> <Icon className="calendar outline"/> le <b>{moment(this.props.event.date).format('LL')}</b> à <b>{this.props.event.hour}</b> </Content> <Content> <AttendeeButton attends={this.state.attends} date={this.props.event.date} handleGoing={this.handleGoing.bind(this)} handleNotGoingAnymore={this.handleNotGoingAnymore.bind(this)} /> </Content> </Card> {pastEvent ? <h3>Ils y sont allés :</h3>: <h3>Ils y vont :</h3>} <div className="attendee-list"> {this.props.event.attendees.map((attendee) => { return <Attendee user={attendee} key={attendee._id}/>; })} </div> </div> <div className="eleven wide column"> {canEdit ? <EventButtons _id={this.props.event._id} delete={this.handleDelete.bind(this)}/>: ''} <p dangerouslySetInnerHTML={createMarkup()}></p> <p><b><Icon className="line chart"/> Niveau {this.props.event.level}</b></p> <p><b><Icon className="location arrow"/> {this.props.event.venue} - {this.props.event.address.formattedAddress}</b></p> <EventMap zoom={12} latLong={[this.props.event.address.latitude, this.props.event.address.longitude]} /> </div> </div> ); }
neuWoerterbuch: () => { let id = ''; if(Roles.userIsInRole(Meteor.userId(), 'admin', 'school')) { id = Woerter.insert({name: '', path: '', data: ''}); return id; } },
Meteor.publish('apisCount', function () { // Get CurrentUser const userId = Meteor.userId(); let query = {}; // Check if currentUser is administrator const isAdmin = Roles.userIsInRole(userId, ['admin']); if (!isAdmin) { // Construct query for checking if API is public or current user is authorized for the API query = { $or: [ { isPublic: true, }, { authorizedUserIds: { $in: [userId], }, }, { managerIds: { $in: [userId], }, }, ], }; } Counts.publish(this, 'apisCount', Apis.find(query)); });
insert: function(userId, doc) { let antenna = Antennas.findOne({ name: doc.name }); if (antenna) { throw new Meteor.Error(403, 'This antenna already exists in the database.'); } return Roles.userIsInRole(userId, ['admin']); },
deleteHelpVideoAttachment: function (attachmentId) { check(attachmentId, String) if (this.userId && Roles.userIsInRole(this.userId, 'super-admin', Roles.GLOBAL_GROUP)) { let filterArgs = {_id: attachmentId, 'meta.parent.collection': 'helpvideos', 'meta.parent.uploadType': 'helpvideo', 'meta.parent.elementId': 'admin'} let fileUpload = Uploads.collection.findOne(filterArgs) if (fileUpload) { let writeResult = Uploads.collection.remove(filterArgs) if (!writeResult) { throw new Meteor.Error(500, 'Couldn\'t remove file attachment') } if (fileUpload.versions) { Object.keys(fileUpload.versions).forEach(versionName => { const _id = (fileUpload.versions[versionName].meta || {}).gridFsFileId if (_id) { gfs.remove({'_id': _id}, (err) => { if (err) { throw err } }) } }) } } else { throw new Meteor.Error(404) } } else { throw new Meteor.Error(401) } }
Meteor.publish("PaginatedOrders", function (query, options) { check(query, Match.Optional(Object)); check(options, Match.Optional(Object)); if (this.userId === null) { return this.ready(); } const shopId = Reaction.getUserShopId(this.userId) || Reaction.getShopId(); if (!shopId) { return this.ready(); } // return any order for which the shopId is attached to an item const aggregateOptions = { observeSelector: { "items.shopId": shopId } }; const limit = (options && options.limit) ? options.limit : 0; const skip = (options && options.skip) ? options.skip : 0; const aggregate = createAggregate(shopId, { createdAt: -1 }, limit, query, skip); if (Roles.userIsInRole(this.userId, ["admin", "owner", "orders"], shopId)) { Counts.publish(this, "orders-count", Orders.find(), { noReady: true }); ReactiveAggregate(this, Orders, aggregate, aggregateOptions); } else { return Orders.find({ shopId, userId: this.userId }); } });
Meteor.publish("Orders", function () { if (this.userId === null) { return this.ready(); } const shopId = Reaction.getShopId(); if (!shopId) { return this.ready(); } // return any order for which the shopId is attached to an item const aggregateOptions = { observeSelector: { "items.shopId": shopId } }; const aggregate = createAggregate(shopId); if (Roles.userIsInRole(this.userId, ["admin", "owner", "orders"], shopId)) { ReactiveAggregate(this, Orders, aggregate, aggregateOptions); } else { return Orders.find({ shopId, userId: this.userId }); } });
render () { return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <Link className="navbar-brand" to="/">Meteor React Shop</Link> </div> <div id="navbar" className="navbar-collapse collapse"> <ul className="nav navbar-nav navbar-right"> <li><Link to="/cartItems"><i className="fa fa-shopping-cart"></i> My Cart (2)</Link></li> <li> {Roles.userIsInRole(Meteor.userId(), 'admin') ? <Link to="/eFdeHqVzb9a2y4tA">Admin</Link> : ''} </li> <li><AccountsUIWrapper /></li> </ul> </div> </div> </nav> ); }
export function getGuestLoginState() { if (Meteor.userId() === "string" && this.getShopId() && this.allowGuestCheckout()) { const isGuestFlow = Session.equals("guestCheckoutFlow", true); const isGuest = Roles.userIsInRole(Meteor.userId(), "guest", this.getShopId()); const isAnonymous = Roles.userIsInRole(Meteor.userId(), "anonymous", this.getShopId()); if (!isGuestFlow && !isGuest && isAnonymous) { return false; } else if (!isGuestFlow && isGuest && !isAnonymous) { return true; } } else if (Session.equals("guestCheckoutFlow", true) && _.pluck(Meteor.user() .emails, "address")) { return true; } return false; }
render() { const { uniqueItems } = this.props; return ( <Components.Button tagName="div" className={{ "btn": false, "btn-default": false, "flat": false, "invoice": true, "invoice-line-items": true }} onClick={this.props.handlePopOverOpen} > {uniqueItems.map((uniqueItem) => ( <div key={uniqueItem._id}> {this.renderLineItem(uniqueItem)} </div> ))} { Roles.userIsInRole(Reaction.getUserId(), ["orders", "dashboard/orders"], Reaction.getShopId()) && this.renderPopOver() } </Components.Button> ); }
Meteor.publish('testData', function () { if (this.userId && Roles.userIsInRole(this.userId, ['admin'])) { return Tests.find() } else { throw new Meteor.Error(401) } })
Template.registerHelper('isAdmin', () => { let userId = Meteor.userId(); if(!userId) { return false; } return Roles.userIsInRole(userId, ['admin']); });
function composer(props, onData) { const audience = Roles.getRolesForUser(Meteor.userId(), Reaction.getShopId()); const settings = Reaction.Apps({ provides: "settings", enabled: true, audience }) || []; const dashboard = Reaction.Apps({ provides: "dashboard", enabled: true, audience }) .filter((d) => typeof Template[d.template] !== "undefined") || []; onData(null, { currentView: Reaction.getActionView(), groupedPackages: { actions: { title: "Actions", i18nKeyTitle: "admin.dashboard.packageGroupActionsLabel", packages: dashboard }, settings: { title: "Settings", i18nKeyTitle: "admin.dashboard.packageGroupSettingsLabel", packages: settings } }, // Callbacks handleShowPackage, handleShowDashboard, handleOpenShortcut }); }
Meteor.publish("Revisions", function (documentIds) { check(documentIds, Match.OneOf(String, Array)); // we could additionally make checks of useId defined, but this could lead to // situation when user will may not have time to get an account if (this.userId === null) { return this.ready(); } const shopId = Reaction.getShopId(); if (!shopId) { return this.ready(); } if (Roles.userIsInRole(this.userId, ["admin", "owner"])) { if (Array.isArray(documentIds)) { return Revisions.find({ // shopId, documentId: { $in: documentIds } }); } // global admin can get all accounts return Revisions.find({ // shopId, documentId: documentIds }); } // regular users should get just their account return this.ready(); });
insertNewTestItem: function (doc, notDirectlyCalled) { check(notDirectlyCalled, Match.OneOf(Boolean, undefined)) if (this.userId && Roles.userIsInRole(this.userId, ['admin'])) { if (notDirectlyCalled) { Tests.insert(doc) } } }
return $meteor.requireUser().then(function (user) { if (!Roles.getRolesForUser(user,$cookies.get('agencyId'))) { // fail the promise chain return $q.reject('FORBIDDEN'); } // keep the success promise chain return user; });
agency.save(function (err, agencyId) { if (err) { logger.error("failed to create agency. err: " + err); throw err; } // make the creator an administrator Roles.addUsersToRoles(userId,'administrator', agencyId); });