I am working on a small system, where the users should be created by an Admin.
So I was trying to use the functions to do that.
Looking in the forum, I found out that it would be better to call the Admin API from the functions.
It just worked, with the following logic.
I just forgot to update here.
exports = async function(arg){
var isAdmin = context.user.custom_data.profile== 'admin' ? true : false;
if (!isAdmin) {
return {
"message" : "You have no permission to access this data!",
"data" : []
};
} else {
// Get Atlas Parameters and application id
const AtlasPrivateKey = context.values.get("AtlasPrivateKey");
const AtlasPublicKey = context.values.get("AtlasPublicKey");
const AtlasGroupId = context.values.get("AtlasGroupId");
const AppId = context.values.get("AppId");
// Authenticate to Realm API
const respone_cloud_auth = await context.http.post({
url : "https://realm.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login",
headers: {
"Content-Type" : ["application/json"],
"Accept" : ["application/json"]
},
body: {"username": AtlasPublicKey, "apiKey": AtlasPrivateKey},
encodeBodyAsJSON: true
});
const cloud_auth_body = JSON.parse(respone_cloud_auth.body.text());
// Get all realm users
const response_create_user = await context.http.post({
url: `https://realm.mongodb.com/api/admin/v3.0/groups/${AtlasGroupId}/apps/${AppId}/users`,
headers: {
"Content-Type" : ["application/json"],
"Accept" : ["application/json"],
"Authorization": ["Bearer " + cloud_auth_body.access_token]
},
body: {
"email": arg.userEmail,
"password": arg.password
},
encodeBodyAsJSON: true
});
const response = JSON.parse(response_create_user.body.text());
if (response_create_user.statusCode === 201) {
const createdUser = {
_id: response._id,
creationDate: new Date(response.creation_date * 1000), // I had a hard time on this part, double value to date
username: arg.username,
userEmail: arg.userEmail,
sex: arg.sex,
name: arg.name,
surname: arg.surname,
status: "confirmed",
churchId: arg.churchId,
parentId: arg.parentId,
imgUser: (arg.sex === 'male') ? context.values.get("ImgMale") : context.values.get("ImgFemale"),
imgBanner: (arg.sex === 'male') ? context.values.get("BannerMale") : context.values.get("BannerFemale"),
userQutoe: "This is a user quote.",
active: true,
profile: arg.profile
};
var collection = context.services.get("mongodb-atlas").db("system").collection("users");
var doc = collection.insertOne(createdUser);
return {
"message" : "sucess!",
"data" : doc,
"response": response_create_user
};
}
}
};
After the user creation, it also fills it’s CustomData, with the rest of the payload received and with the newly assigned ID and Creation_Date (I wonder if there is a better way to save the creation date to the users’ collection).
Since this is working, maybe I could just get some insight to improve the logic?
PS.: Since I achieved what I wanted, I tried to remove this post, but couldn’t. So I’m updating it, to maybe help someone.