How to get userIdentity from inside javascript adapter? - javascript

I am on MobileFirst 7.1, and I am trying to do something similar to this: Get user id from inside a protected adapter but this time is in javascript.
I have followed the tutorial and the protected procedure triggers login, I have made sure that application-descriptor.xml contains <userIdentityRealms>MyRealm</userIdentityRealms> however user identity is null(again).
How can I get the user identity from inside the following procedure?
function myProcedure() {
// I want to get the userid this Java into Javascript,
// SecurityAPI security = serverAPI.getSecurityAPI();
// OAuthUserIdentity identity = security.getSecurityContext().getUserIdentity();
// String userid = identity.getId();
var userid = ???
var facade = new com.ibm.jp.facade.SomeFacade();
var list = facade.SomeMethod(userid);
return JSON.parse(list);
}
In the beginning I was trying to get the user identity from inside the Java facade but it is null. I suspect it is not in the same context? That is why I am trying to get it from the js adapter and pass it as a parameter of someMethod(). If there is a better way to get it I would like to know.

I found it!
var user = WL.Server.getActiveUser();
var userid = user.userId;
...

Related

Get an entityName by GUID, despite of what form is loaded at the moment for use in XrmServiceToolkit.Soap.setState()

I'm stuck on the XrmServiceToolkit.Soap.setState() function.
Prerequisites
I'm on studying MS CRM. One of my tasks is to activate and deactivate a record (this time it's a native "contact" record). I've decided to build my solution in a following way (according to other tasks):
On the OnLoad event of my custom entity's form I create a new contact using XrmServiceToolkit (task condition), then update one field in newly created contact. This actually doesn't make sense in production to create something on this event, but nevertheless, is done this way only for my convenience:
function Practice3()
{
let entityToUpdate = CreateRecordWithToolkit("VP_Created by","Xrm Service Toolkit","4F52999B-0E63-EA11-8125-00155D06F203");
alert("Switching to new record!");
Xrm.Utility.openEntityForm("contact", entityToUpdate);
UpdateFieldsWithXrmServiceToolkit(entityToUpdate);
DeactivateAndActivateContact(entityToUpdate);
}
// I don't post the CreateRecordWithToolkit(fname, lname, accountId) and UpdateFieldsWithXrmServiceToolkit(targetEntity) functions 'cos all is Ok there
// and entityToUpdate GUID is passed properly
Between creation and posting updates I send a command to load that newly created form. It does'n activated it at once, but updates are inserted correctly.
Then I pass the same GUID to my next function DeactivateAndActivateContact(targetEntity) and here I stuck.
Question
Can anyone explain or give a hint on how to use the XrmServiceToolkit.Soap.setState() function? I can't get the "entityName" parameter - what is this? How can I get it with having entity's GUID? I was trying to use it like this:
function DeactivateAndActivateContact(targetEntity)
{
let entityName = GetObjectAttribute(targetEntity, "contact", "name");
XrmServiceToolkit.Soap.setState(entityName,targetEntity, "0", "0",false);
Xrm.Page.data.refresh(true).then(null, null);
}
but getting an undefined error.
Is there any way to get an entityName by GUID? 'cos I'm getting the name of current form.
Error is raised when stepping in to this line:
XrmServiceToolkit.Soap.setState(entityName,targetEntity, "0", "0",false);
To Deactivate contact here is below code,
Note Rest API call is Asynchronous and You will have to use execution context and formcontext in Dynamics
Also you could change your other SOAP calls with Rest API. Refer to CRM Rest Builder, it's way easy to build calls with it.
var entity = {};
entity.statuscode = 2;
entity.statecode = 1;
Xrm.WebApi.online.updateRecord("contact", "4A342F12-D248-E211-8669-005056922461", entity).then(
function success(result) {
var updatedEntityId = result.id;
formContext.data.refresh(yes).then(successCallback, errorCallback);
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);

Appmaker: How can I get the ID of an item i just created, on client side?

So my latest problem is the following:
I store an id(a foreign key) in a custom property. I want to set the Foreign Key field of an item I just created, to the stored custom property.
I am trying to achieve this in a server script, which looks like this:
function setFKforCustomer(customerID, companyID)
{
var query = app.models.Customer.newQuery();
query.filters.Id._equals(customerID);
var records = query.run();
records[0].Company_fk=companyID;
}
I want to call this function from a client side script, which has to know the customer's ID, the id of the item I just created. I am not entirely sure I am approaching the problem from the right angle, so I am open to other ideas.
Thank you in advance (Markus)!
The question of how to manage relationships in App Maker is probably one of the most asked questions. The official documentation for your specific use case is located here https://developers.google.com/appmaker/models/relations#server_script. The answer would be as follows:
function setFKforCustomer(customerID, companyID)
{
var customerRecord = app.models.Customer.getRecord(customerID);
var companyRecord = app.models.Company.getRecord(companyID);
customerRecord.YourCompanyRelationName = companyRecord; //the field in this case is not Company_fk but whatever the name is of the relation you set up in AM
app.saveRecords([customerRecord]);
}

Set password of user created with Scripted API in Service now

I am new to the Service now and trying to build a Client Web-app with Service Now.
My requirement is to register a user in Service Now using my web app.
I have tried to do so with Table API and Scripted Rest API.
Though I am able to create the user (makes an entry in sys_user table) but the created user is not able to login on Service Now portal.
If I login as admin and change the password of created user the user is able to login.
Please tell me what am I doing wrong?
Below is my Scripted API -
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
// implement resource here
var requestBody = request.body.data;
var gr = new GlideRecord('sys_user');
gr.initialize();
gr.user_name = requestBody.user_name;
gr.first_name = requestBody.first_name;
gr.last_name = requestBody.last_name;
gr.title = requestBody.title;
gr.department = requestBody.department;
gr.user_password = requestBody.user_password;
gr.active = requestBody.active;
gr.email = requestBody.email;
gr.mobile_phone = requestBody.mobile_phone;
gr.insert();
//Create a body object. Add property value pairs to the body.
var body = {};
body.user_name = gr.user_name;
body.sys_id = gr.sys_id;
body.password = gr.user_password;
response.setBody(body);
})(request, response);
I found a hook for this question.
When you create the user instead of setting the password before gr.insert(), try updating the record for setting the password as per the following code.
gr.user_password.setDisplayValue(requestBody.user_password);
gr.update();
Looks like password in sys_user table is a one way encrypted field. So you need to set the display value.

JS: Node.js and Socket.io - globals and architecture

Dear all,
Im working with JS for some weeks and now I need a bit of clarification. I have read a lot of sources and a lot of Q&A also in here and this is what I learned so far.
Everything below is in connection with Node.js and Socket.io
Use of globals in Node.js "can" be done, but is not best practice, terms: DONT DO IT!
With Sockets, everything is treated per socket call, meaning there is hardly a memory of previous call. Call gets in, and gets served, so no "kept" variables.
Ok I build up some chat example, multiple users - all get served with broadcast but no private messages for example.
Fairly simple and fairly ok. But now I am stuck in my mind and cant wrap my head around.
Lets say:
I need to act on the request
Like a request: "To all users whose name is BRIAN"
In my head I imagined:
1.
Custom object USER - defined globally on Node.js
function User(socket) {
this.Name;
this.socket = socket; }
2.
Than hold an ARRAY of these globally
users = [];
and on newConnection, create a new User, pass on its socket and store in the array for further action with
users.push(new User(socket));
3.
And on a Socket.io request that wants to contact all BRIANs do something like
for (var i = 0; i < users.length; i++) {
if(user[i].Name == "BRIAN") {
// Emit to user[i].socket
}}
But after trying and erroring, debugging, googling and reading apparently this is NOT how something like this should be done and somehow I cant find the right way to do it, or at least see / understand it. can you please help me, point me into a good direction or propose a best practice here? That would be awesome :-)
Note:
I dont want to store the data in a DB (that is next step) I want to work on the fly.
Thank you very much for your inputs
Oliver
first of all, please don't put users in a global variable, better put it in a module and require it elsewhere whenever needed. you can do it like this:
users.js
var users = {
_list : {}
};
users.create = function(data){
this._list[data.id] = data;
}
users.get = function(user_id){
return this._list[user_id];
};
users.getAll = function(){
return this._list;
};
module.exports = users;
and somewhere where in your implementation
var users = require('users');
For your problem where you want to send to all users with name "BRIAN",
i can see that you can do this good in 2 ways.
First.
When user is connected to socketio server, let the user join a socketio room using his/her name.
so it will look like this:
var custom_namespace = io.of('/custom_namespace');
custom_namespace.on('connection', function(client_socket){
//assuming here is where you send data from frontend to server
client_socket.on('user_data', function(data){
//assuming you have sent a valid object with a parameter "name", let the client socket join the room
if(data != undefined){
client_socket.join(data.name); //here is the trick
}
});
});
now, if you want to send to all people with name "BRIAN", you can achieve it by doing this
io.of('/custom_namespace').broadcast.to('BRIAN').emit('some_event',some_data);
Second.
By saving the data on the module users and filter it using lodash library
sample code
var _lodash = require('lodash');
var Users = require('users');
var all_users = Users.getAll();
var socket_ids = [];
var users_with_name_brian = _lodash.filter(all_users, { name : "BRIAN" });
users_with_name_brian.forEach(function(user){
socket_ids.push(user.name);
});
now instead of emitting it one by one per iteration, you can do it like this in socketio
io.of('/custom_namespace').broadcast.to(socket_ids).emit('some_event',some_data);
Here is the link for lodash documentation
I hope this helps.

get method not working on Parse current User

I am making an express app with Parse. In my cloud code, I am trying to get an attribute of the current user, but it is returning me undefined. My code looks like following:
app.get('/home/subscriptions',function(req,res){
Parse.Cloud.useMasterKey();
var user = Parse.User.current();
var ifstud = user.get("isStudent");
console.log('student: ' + ifstud); // undefined
console.log('id: ' + user.id); // OK. works fine.
}
I am able to retrieve the id of the user as above but not able to call the get method on user. In their API reference, they have mentioned that Parse.User.current() returns a Parse.Object, so I think in user I have _User object and I should be able to call all methods supported by a Parse.Object.
What might be the issue here?
Thanks
I figured it out and putting this answer for future reference to users who visit this question.
The Parse.User.current() returns only a pointer to the user and not the complete user object. To get access to all fields of the user, fetch the entire object using the fetch method.
var fullUser;
Parse.User.current.fetch().then(user){
fullUser = user;
}).then(function(){
// Place your code here
});
I think it should be: var ifstud = Parse.User.get("isStudent");

Categories

Resources