Creating users in Google Apps from Apps Script - javascript

I am using Google Apps Script to create users in Google Apps in bulk via spreadsheet
my spreadsheet has 4 columns where i have firstname, lastname, emailId, and password, as these are required to create users.
My following script works fine and create users without issue, however it stops at a point if any user already exists, and does not move forward to attempt other ones in spreadsheet.
I want it to loop through the whole spreadsheet, skip the ones that already exists, and create the ones who don't
Any help is appreciated.
function createUsers() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Create Users")
var values = sheet.getDataRange().getValues()
for(i=1; i <values.length; i++)
{
var fName = values[i][0]
var lName = values[i][1]
var email = values[i][2]
var password = values[i][3]
var status = values[i][4]
var user = AdminDirectory.Users.insert({
"primaryEmail": email,
"password": password,
"orgUnitPath": "/MDM Testing",
"name": {
"familyName": lName,
"givenName": fName
}
})
Logger.log(user);
}}

You can add If condition to check duplicate user as follows.
function createUsers() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName("Create Users")
var values = sheet.getDataRange().getValues()
for(i=1; i <values.length; i++)
{
var fName = values[i][0]
var lName = values[i][1]
var email = values[i][2]
var password = values[i][3]
var status = values[i][4]
// Check user exist or not by email address.
var userFromDirectory = AdminDirectory.Users.get(email);
if(email != userFromDirectory.primaryEmail){
var user = AdminDirectory.Users.insert({
"primaryEmail": email,
"password": password,
"orgUnitPath": "/MDM Testing",
"name": {
"familyName": lName,
"givenName": fName
}
})
Logger.log(user);
} // end of if
}}

Use
var userFromDirectory = AdminDirectory.Users.list.name
instead of
var userFromDirectory = AdminDirectory.Users.get(email);

Related

Apps Script: Get user input from HTML form and save them as global variables

The server side script below receives user input from an HTML form and adds these user data/input to the last available row of my Google Sheet. It´s been working pretty fine. But now I want to store some elements of the array that is in this script as global variables, so that I can re-use them later on in other server side functions bound to the same Google Sheet. I am specifically interested in the values inside lastName, email and phone. Any idea how this can be done?
Thank you so much in advance for your hints and help.
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
}
You can use Properties Service of Apps Script.
This service allows scripts to store strings as key-value pairs scoped
to one script, one user of a script, or one document in which an
editor add-on is used.
In your case, there are 2 options you can choose. Script Properties and User Properties.
The difference between the two is the content of Script Properties are shared to all users while User Properties is only available to the current user of a script, add-on, or web app.
Here I created an example of how to use Properties.
function setProperties(lastName = "Test Last Name", email = "Test Email", phone = "Test Phone"){
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function readProperties(){
var scriptProperties = PropertiesService.getScriptProperties();
Logger.log(scriptProperties.getProperties());
}
Here I run the readProperties() function first and the result is
Then I run the 'setProperties()' and rerun the readProperties() function again:
I reload the script page and ran the readProperties() function:
To add it in your script, you can set the properties in AddUserInputToSheet() and call it anywhere in your script.
Example:
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function someFunction(){
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var lastName = data["lastName"];
var email = data["email"];
var phone = data["phone"];
//some operations here
}
Here's an example:
function myfunk1() {
PropertiesService.getScriptProperties().setProperty('Global1',JSON.stringify(SpreadsheetApp.getActive().getSheetByName('Sheet0').getDataRange().getDisplayValues()));
}
function myfunk2() {
const vs = JSON.parse(PropertiesService.getScriptProperties().getProperty('Global1'))
SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(1,1,vs.length,vs[0].length).setValues(vs);
}

Duplication check of Email id and Phone number in Firebase database using JavaScript

I'm completely new to firebase. I'm creating a basic contact form for my application and connected that to the firebase database. I don't have any authentication for my application. . I have set all the rules to True . I want to prevent duplication, if there exists phone number and email in database I want to display an error message.
Below is my code which I have tried
firebase.initializeApp(firebaseConfig);
// Reference messages collection
// Listen for form submit
document.getElementById('contactform1').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var fname = getInputVal('fname');
var lname = getInputVal('lname');
var email = getInputVal('email');
var phone = getInputVal('phone');
var skills = getInputVal('skills');
var jobId = getInputVal('jid');
var linkedin = getInputVal('linkedin');
var github = getInputVal('github');
var location = getInputVal('location');
// Save message
saveMessage(fname, lname, email, skills, phone, jobId, linkedin, github, location, );
// file upload
var fileButton = document.getElementById("fileButton");
var file = fileButton.files[0];
firebase.storage().ref('self/' + file.name).put(file);
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(fname, lname, email, skills, phone, jobId, linkedin, github, location) {
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
//snapshot to check the values in database
firebase.database().ref().child('self/data/' ).on('child_added', snap => {
var name = snap.child('name').val();
var email = snap.child('email').val();
var phone = snap.child('phone').val();
var skills = snap.child('skills').val();
var jobId = snap.child('jobId').val();
var linkedin = snap.child('linkedin').val();
var github = snap.child('github').val();
var location = snap.child('location').val();
$('#table_bdy').append('<tr><td>' + name + '</td><td>' + email + '</td><td>' + phone + '</td><td>' + skills + '</td><td>' + jobId + '</td><td>' + location + '</td><td>' + github + '</td><td>' + linkedin + '</td></tr>')
})
Before saving the new values to the database, retrieve the data from the database and check if the email written in the form is the same as an email retrieved from the database. For example:
var newEmail = getInputVal('email');
firebase.database().ref().child('self/data/' ).on('child_added', snap => {
var name = snap.child('name').val();
var email = snap.child('email').val();
if(newEmail.trim() === email.trim())
{
console.log("email already exists in the database");
}
else
{
saveMessage(fname, lname, newEmail, skills, phone, jobId, linkedin, github, location);
}
});
Try the following:
firebase.initializeApp(firebaseConfig);
// Reference messages collection
// Listen for form submit
document.getElementById('contactform1').addEventListener('submit', submitForm);
// Submit form
function submitForm(e) {
e.preventDefault();
// Get values
var fname = getInputVal('fname');
var lname = getInputVal('lname');
var newEmail = getInputVal('email');
var newPhone = getInputVal('phone');
var newskills = getInputVal('skills');
var newjobId = getInputVal('jid');
var newlinkedin = getInputVal('linkedin');
var newgithub = getInputVal('github');
var newlocation = getInputVal('location');
saveMessage(fname, lname, newEmail, newskills, newPhone, newjobId, newlinkedin, newgithub, newlocation);
}
function saveMessage(fname, lname, newEmail, skills, phone, jobId, linkedin, github, location) {
let ref = firebase.database().ref().child('self/data/');
ref.on('value', snap => {
if(snap.exists())
{
snap.forEach(childSnapshot => {
var name = childSnapshot.child('name').val();
var email = childSnapshot.child('email').val();
var phone = childSnapshot.child('phone').val();
var skills = childSnapshot.child('skills').val();
var jobId = childSnapshot.child('jobId').val();
var linkedin = childSnapshot.child('linkedin').val();
var github = childSnapshot.child('github').val();
var location = childSnapshot.child('location').val();
var status = childSnapshot.child('status').val();
console.log(status);
if (newEmail.trim() === email.trim())
{ //check if email exists
console.log("email already exists in the database");
}
else
{
console.log('hello');
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
else
{
firebase.database().ref().child('self/data/' + phone).set({
name: fname + " " + lname,
email: email,
phone: phone,
skills: skills,
jobId: jobId,
linkedin: linkedin,
github: github,
location: location
});
}
});
}
// Function to get get form values
function getInputVal(id) {
return document.getElementById(id).value;
}
First you need to retrieve the values from the form, and then call the method saveMessage in the method check if node self/data exists, then retrieve the data and check if email already exists in the database.

How to update data without deleting anything else?

I need to set a value on my Firebase realtime-database.
Here is my database organization:
Users:
U20180422:
ID: U20180422
Name: "Jason"
Surname: "Smith"
Address: "4198 Norma Avenue"
Age: "30"
creation date: "04/22/2018"
U20180311: ...
U20180304: ...
U20180215: ...
...
I make this snippet for write and it works:
<script language="javascript">
//this retrieves from the form of registration the ID of the user
var userId = document.getElementById("searchfield").value;
// Initialize Firebase
var config = {
//my configurations
};
firebase.initializeApp(config);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('Users/' + userId);
var data = {
Account_validated = "OK"
}
ref.set(data)
</script>
But in this way the data that were present are deleted and only account_validated state is present in the path. So I thought I had to first retrieve all the data already in possession and then send them to the database along with the new data.
This is what is not working in my code:
//Retrieve from database
ref.on('value', gotData, errData);
function gotData(data) {
var value = data.val();
var getvalue = Object.value(value);
for (var i=0; i < value.lenght; i++) {
var k = value[i];
var name= value[k].Name;
var surname= value[k].Surname;
var address= value[k].Address;
var age= value[k].Age;
var creation_account_date= value[k].creation date;
console.log(name, surname, address, age, creation date);
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
{
snapshot.forEach(function(child) {
var childData = child.val();
var name=child.val().Name;
var surname=child.val().Surname;
var address=child.val().Address;
var age=child.val().Age;
var creation_account_date=child.val().creation date
});
});
//Write
var data = {
ID: userId,
Name: name,
Surname: surname,
Address: address,
Age: age,
creation date: creation_account_date
}
ref.set(data)
To update only the keys that you specify in your data, use update:
var data = {
Account_validated: "OK"
}
ref.update(data)
This will update only the Account_validated key under ref, and leave other child properties unmodified.
What errors are you seeing?
At first glance you've got a typo in your for loop:
for (var i=0; i < value.lenght; i++)
You've misspelt length so value.lenght will resolve to undefined and execution will just skip over the loop.

I want to check the value of fields of two forms

I have an application, in the app there two forms which are about contact info, each form in different tab; users need to fill. What I want to do is check if the value of the first form values equal the second form. The below is what I did.
What do you think about this way is efficient? If not or have a better way, please share with me.
// form 1
var fName = $("#FirstName").val();
var lName = $("#LastName").val();
var street = $("#Street").val();
var city = $("#City").val();
var cellPhone = $("#cellPhone").val();
var email = $('#Email').val();
// form2 of the main contact
var fName2 = $("#FirstName2").val();
var lName2 = $("#LastName2").val();
var street2 = $("#Street2").val();
var city2 = $("#City2").val();
var cellPhone2 = $("#cellPhone2").val();
var email2 = $('#Email2').val();
//actually i have along "if"
if(fName==fName2 && lName == lName2 && street==street2 && city==city2 && cellPhone==cellPhone2 && email==email2){
}
else {
}
var form1 = {
firstName: $("#FirstName").val(),
lastName: $("#LastName").val(),
street: $("#Street").val(),
city: $("#City").val(),
cellPhone: $("#cellPhone").val(),
email: $('#Email').val()
}
var form2 = {
firstName: $("#FirstName2").val(),
lastName: $("#LastName2").val(),
street: $("#Street2").val(),
city: $("#City2").val(),
cellPhone: $("#cellPhone2").val(),
email: $('#Email2').val()
}
for (var k in form1) {
if (form1[k] === form2[k]) return false
}
// your code
Doing so makes it easier for you to add fields.
And I think collecting these data can also be done with a loop.
You can use Jquery form validation plugin. Its simple to use and offers lot of validation methods. You can also code your custom methods
https://jqueryvalidation.org/
Since your are using jquery you can use the $.submit() method. This allows you to run additional functions before the form is submitted. you can simply:
$('#someForm1').submit(function (e) {
var val1 = $(this).find('.inputval1').val();
var val2 = $('#someForm2').find('.inputval1').val();
if (val1 === val2) {
return;
} else {
e.preventDefault();
}
});

Retrieve objectId in Parse

In simple, I am trying to retrieve the objectId for a particular user in parse (using Javascript). I can retrieve any other query in the database, such as username, phone, mailing address but not the objectId, here is how I retrieve the rest of the query:
var objectId = userInfo.get("objectId");
Any assistance would be greatly appreciated.
Below is more lines of the code (everything is retrieved beside objectId)
query.find({ success: function(array) {
// this means the query was a success, but we're not yet certain that we found anything
// the param to find's success is an array of PFObjects, possibly empty
if (array.length > 0) {
var userInfo = array[0];
var address = userInfo.get("address");
$scope.address = address;
var email = userInfo.get("username");
$scope.email = email;
var fullName = userInfo.get("fullName");
$scope.fullName= fullName;
var number = userInfo.get("phoneNumber");
$scope.number= number;
var objectId = userInfo.get("objectId");
$scope.objectId= objectId;
var mailingAddress = userInfo.get("mailingAddress");
$scope.mailingAddress = mailingAddress;
var plan = userInfo.get("plan");
$scope.plan = plan;
Thanks in advance
The js sdk provides an id member, so ...
$scope.objectId = userInfo.id;
As an aside, check out the JS guide on their site. It's a very well written doc. Pay particular attention to the code snippets in the objects and query sections.

Categories

Resources