2017-01-15 11:33:37 -08:00
import { Random } from 'meteor/random' ;
if ( Meteor . isServer ) {
Meteor . publish ( 'users' , function ( ) {
if ( Roles . userIsInRole ( this . userId , [ 'manage' ] ) ) {
return Meteor . users . find ( { } , { fields : { username : 1 , emails : 1 , roles : 1 } } ) ;
}
else throw new Meteor . Error ( 403 , "Not authorized to view users." ) ;
} ) ;
Meteor . methods ( {
2017-10-20 14:54:58 -07:00
"insertUser" : function ( user ) {
2017-01-15 11:33:37 -08:00
check ( user , {
username : String ,
2020-01-16 09:31:12 -08:00
emails : [ { address : String , verified : Match . Maybe ( Boolean ) } ] ,
2017-10-20 14:54:58 -07:00
roles : [ String ]
2017-01-15 11:33:37 -08:00
} ) ;
//Verify the currently logged in user has authority to manage users.
if ( Roles . userIsInRole ( this . userId , [ Meteor . UserRoles . ROLE _MANAGE ] ) ) {
//Verify the user name isn't already used.
2017-10-20 14:54:58 -07:00
if ( Meteor . collections . Users . findOne ( { username : user . username } ) === undefined ) {
2017-01-15 11:33:37 -08:00
let pwd = Random . secret ( 20 ) ;
2020-01-16 09:31:12 -08:00
console . log ( "Email: " + user . emails [ 0 ] ) ;
let id = Accounts . createUser ( { password : pwd , username : user . username , email : user . emails [ 0 ] . address } ) ;
2017-01-15 11:33:37 -08:00
//Requires the alanning:roles package.
2017-10-20 14:54:58 -07:00
Roles . addUsersToRoles ( id , user . roles ) ;
2017-01-15 11:33:37 -08:00
}
else {
throw new Meteor . Error ( 400 , "User already exists." ) ;
}
}
else throw new Meteor . Error ( 403 , "Not authorized to add users." ) ;
} ,
"updateUser" : function ( user ) {
check ( user , {
_id : String ,
username : String ,
emails : [ {
address : String ,
verified : Boolean
} ] ,
roles : [ String ]
} ) ;
//Verify the currently logged in user has authority to manage users.
if ( Roles . userIsInRole ( this . userId , [ Meteor . UserRoles . ROLE _MANAGE ] ) ) {
//Verify the user name isn't already used with a different ID.
if ( Meteor . collections . Users . findOne ( { username : user . username , _id : { $ne : user . _id } } ) == undefined ) {
//Update the user. Note: I am using direct mongo modification, versus attempting to go through the Accounts and Roles objects. This could cause problems in the future if these packages change their data structures.
Meteor . collections . Users . update ( user . _id , { $set : { username : user . username , emails : user . emails , roles : user . roles } } ) ;
}
else {
throw new Meteor . Error ( 400 , "User name already exists." ) ;
}
}
else throw new Meteor . Error ( 403 , "Not authorized to update users." ) ;
} ,
"deleteUser" : function ( id ) {
check ( id , String ) ;
if ( Roles . userIsInRole ( this . userId , [ Meteor . UserRoles . ROLE _MANAGE ] ) ) {
Meteor . collections . Users . remove ( id ) ;
}
else throw new Meteor . Error ( 403 , "Not authorized to remove users." ) ;
}
} ) ;
}
export default Meteor . users ;