Kanchan
Kanchan

Reputation: 1

How to reset user's password in Google Apps Script using admin SDK?

I have a list newly creates users in my domain. I want to reset all of their password. But I don't want to do it using admin console. How can I do this using admin SDK and Google App script?

My idea is get a list of user whose password I need to reset, and then assign some random strings to those email id's and update it as their password.

I this possible? If not, is there any better idea? (I have tried using GAM, But I don't want to do it through CSV files each time.)

Upvotes: 0

Views: 2925

Answers (2)

Jasper Cuvelier
Jasper Cuvelier

Reputation: 573

This is a sample function, using the Directory API (Admin-SDK-service) in Apps Script that you could use to update a users password.

function updatePassword(userId,newPassword){
  try {
    // Define the user's new password
    var newPasswordObject = {
      password: newPassword
    };
    
    // Update the user's password
    AdminDirectory.Users
    .update(newPasswordObject, userId);
    
    console.log("Password updated successfully for user: " + userId);
    
  } catch (e) {
    console.log("Error updating password: " + e.toString());
  }
}

If you want to loop over a spreadsheet containing useraccounts and passwords, a possible solution could look like this.

Add this function to an Apps Script Project within a Spreadsheet with data.

function loopOverSheetWithUsersAndPasswords(){
  var ss = SpreadsheetApp.getActive()
  // Assuming you have a sheet with the name 'LIST OF USERS AND PASSWORDS'
    var sheet = ss.getSheetByName('LIST OF USERS AND PASSWORDS')

  // We wont be using the headers, we only need the actual data.
  var [headers, ...data] = sheet.getDataRange().getValues()

  /* Assuming that the sheet looks like this:   
    |  Usernames      |  Password       |
    --------------------------------------
    |  [email protected]      |  p@$$w0rd123    |
    |  [email protected]      |  p@$$w0rd456    |
        ...                  ...
  */
  
  data.forEach((row)=>{
    var username = row[0]
    var newPassword = row[1]
    // if both username and newpassword are provided, change the password.
    if (username && newPassword) {
        updatePassword(username,newPassword)
    }
  })
}

Upvotes: 0

miketreacy
miketreacy

Reputation: 1120

Resetting a password is possible via the Directory API within the Admin SDK; therefore, you would be able to do this via Apps Script.

Depending how comfortable you are with coding, you might want to use Google Apps Manager to complete this and other tasks. The command to change a password can be found here. These types of commands can be run in bulk by either reading a CSV of all users (can also be created with GAM) or writing a small script to go through a group, OU, etc. and reset only those users.

Upvotes: 1

Related Questions