Translate

Monday, October 21, 2024

Golang - Create Azure User

Function to ccreate a new user account in Azure using msgraph-sdk-go:


// creates a user in Azure with a minimal number of properties set
func CreateBaseAzureUser(strDisplayName, strMailNickName, strUserPrincipleName, strPassword, strEmployeeId string)(error){
	logger.NLog.Info().Msg("CreateBaseAzureUser Started: dn: " + strDisplayName + " mnn: " + strMailNickName + " upn: " + strUserPrincipleName + " eid: " + strEmployeeId)
	//employee id check: check if there is already a current user with the same employee id 
	//get the base azure user properties by employeeId
	user, err := AzureGetBaseUsersByPropertyFilter("employeeId", strEmployeeId)
	if user != nil {
		if len(user.GetValue()) != 0 {
			logger.NLog.Error().Err(err).Msg("CreateBaseAzureUser Error: " + strEmployeeId)
			strM := "An Azure user with the employeeID " + strEmployeeId + " already exits."
			utils.PostMessageT("it-help@internews.org", "Azure Account Creation Error for Emp. ID: " + strEmployeeId, strM)
			return errors.New(strM)
		}
	} 	
	requestBody := graphmodels.NewUser()
	accountEnabled := true
	// Enable the account
	requestBody.SetAccountEnabled(&accountEnabled) 
	// Display Name
	requestBody.SetDisplayName(&strDisplayName) 
	// Mail Nick Name
	requestBody.SetMailNickname(&strMailNickName) 
	// User Principal Name
	requestBody.SetUserPrincipalName(&strUserPrincipleName)
	// Employee ID
	requestBody.SetEmployeeId(&strEmployeeId)
	// Password
	passwordProfile := graphmodels.NewPasswordProfile()
	forceChangePasswordNextSignIn := true
	passwordProfile.SetForceChangePasswordNextSignIn(&forceChangePasswordNextSignIn) 
	passwordProfile.SetPassword(&strPassword) 
	requestBody.SetPasswordProfile(passwordProfile)

	if azureGgraphConnector == nil{
		err := InitializeAzureGraph()
		if err != nil{
			logger.NLog.Error().Err(err).Msg("CreateBaseAzureUser InitializeAzureGraph Error")
			utils.PostMessageT("it-help@internews.org", "CreateBaseAzureUser InitializeAzureGraph Error for Emp. ID: " + strEmployeeId, err.Error())
			return err
		}
	}
	
	users, err := azureGgraphConnector.AppClient.Users().Post(context.Background(), requestBody, nil)

	if err != nil {
        logger.NLog.Error().Err(err).Msg("CreateBaseAzureUser error: " + strEmployeeId + " " + strDisplayName)
		utils.PostMessageT("it-help@internews.org", "Azure Account Creation Error: " + strEmployeeId + " " + strDisplayName, err.Error())
        return err
    } else {
		logger.NLog.Info().Msg("CreateBaseAzureUser user created: " + *users.GetDisplayName())
	}
	return nil
}

No comments:

Post a Comment

Thank you for commenting!