2022-09-07 08:58:00 -07:00
import { Accounts } from 'meteor/accounts-base'
import { Roles } from 'meteor/alanning:roles'
import { Meteor } from "meteor/meteor" ;
console . log ( "Setting up accounts-config..." )
if ( Meteor . isClient ) {
Accounts . ui . config ( {
passwordSignupFields : 'USERNAME_ONLY'
} ) ;
}
Accounts . config ( {
// Allow only certain email domains.
restrictCreationByEmailDomain : function ( address ) {
let pattern = process . env . EMAIL _REGEX ;
return new RegExp ( pattern , 'i' ) . test ( address )
}
} ) ;
if ( Meteor . isServer ) {
let adminEmail = process . env . ADMIN _EMAIL ;
let watchForAdmin = false ;
//Setup the roles.
2025-09-25 09:31:02 -07:00
await Roles . createRoleAsync ( 'admin' , { unlessExists : true } ) ;
await Roles . createRoleAsync ( 'laptop-management' , { unlessExists : true } ) ;
await Roles . addRolesToParentAsync ( 'laptop-management' , 'admin' , { unlessExists : true } ) ;
2022-09-07 08:58:00 -07:00
//Roles.addUsersToRoles("zwbMiaSKHix4bWQ8d", 'admin', 'global', {unlessExists: true});
// If we are passed an email address that should be admin by default, then ensure that user is admin, or mark it as needing to be admin if the user ever logs in.
// Given that this app requires Google OAuth2, and we expect logins to be restricted to district email addresses, this should be very secure.
if ( adminEmail ) {
2025-09-25 09:31:02 -07:00
let user = await Meteor . users . findOneAsync ( { "services.google.email" : adminEmail } ) ;
2022-09-07 08:58:00 -07:00
if ( user ) {
2025-09-25 09:31:02 -07:00
let assignment = await Meteor . roleAssignment . findOneAsync ( { 'user._id' : user . _id , "role._id" : "admin" } ) ;
2022-09-07 08:58:00 -07:00
// console.log("Admin Role Assignment: " + JSON.stringify(assignment));
if ( ! assignment ) {
2025-09-25 09:31:02 -07:00
await Roles . addUsersToRolesAsync ( user . _id , [ 'admin' ] ) ;
2022-09-07 08:58:00 -07:00
}
}
else {
watchForAdmin = true ;
}
}
// Listen for users logging in so we can setup the admin user automatically once they log in the first time.
if ( watchForAdmin ) {
// TODO: It would be nice to remove this handler after the admin user is found, but the docs are pretty ambiguous about how to do that. Not a big deal, just annoying.
2025-09-25 09:31:02 -07:00
Accounts . onLogin ( async function ( data ) {
2022-09-07 08:58:00 -07:00
// console.log("User logged in:");
// console.log(data.user.services.google.email);
// data.user == Meteor.user()
//console.log(JSON.stringify(Meteor.user()));
if ( watchForAdmin ) {
try {
if ( data . user . services . google . email === adminEmail ) {
2025-09-25 09:31:02 -07:00
await Roles . addUsersToRolesAsync ( data . user . _id , [ 'admin' ] ) ;
2022-09-07 08:58:00 -07:00
watchForAdmin = false ;
}
} catch ( err ) {
console . log ( err ) ;
}
}
} ) ;
}
}
console . log ( "Finished setting up accounts-config." )