SAPUI5 get username/userid from OData request - odata

I am currently focussing a problem which I thought it would be easy to solve. but I didnt. There are controls which allow us to show the username or logged in user, such as the lovely shell-headitems:
var oShell = new sap.ui.ux3.Shell("myShell", {
headerItems: [
new sap.ui.commons.TextView({
text: oController.getUserName() }),
],
});
It looks like this:
In here we define headerItems, which are in my opinion foreseen to show a username / or the currently logged in user. but how can I receive it? my idea is to get it from the odata request, which was made earlier. It requires me to enter username and password -> thus I want to read this username in my controller-method, but how?
getUserName : function() {
// return navigator.userAgent;
var model = sap.ui.getCore().getModel();
return model.getProperty('sUser'); // doesnt work :(
},
I also tried to get it from navigator.userAgent() but this information does not belong to the user.
Anybody knows how to receive it?
And yes: I searched in google and found some threads discussing about users/login but none of these threads solved my issue. Otherwise I thought about transferring sy-uname from SAP to the frontend, but how could you send a single Text? I don't want to build a complete service for this single transaction.
If you do not provide sUser and sPassword during oData-Model-Initialization it will be empty during runtime. You cannot access it from the model, though I realized an own service for this.

The username is in the sap.ui.model.odata.ODataMetadata of ODataModel.
var getUserName = function() {
var model = sap.ui.getCore().getModel();
var sUser = model.oMetadata.sUser;
// Display user logic here.
};
oModel.attachMetadataLoaded(null,getUserName);
Update answer for comment question from zyrex:
var user = new sap.ui.commons.TextView();
var getUserNameCallBack = function(userName) {
user.setText(userName);
}
oController.getUserName(getUserNameCallBack);
Controller method:
getUserName: function(callback) {
var userName = '';
$.getJSON(sServiceUrl).done(function(data) {
userName = data.d.Name;
callback(userName);
});
}

Related

How to use SimpleProvider with my own MSAL C# code

I'm trying to use my own MSAL code to work together. Developed with .NET Core 5 MVC.
I have similar problem as I found in below link. But I just don't know how to make it work with the proposed answer. Or in other words, I'm still confuse how this integration is done.
[It is mandatory to use the login component in order to use the other components]It is mandatory to use the login component in order to use the other components
[Quickstart for MSAL JS]https://github.com/microsoftgraph/microsoft-graph-toolkit/blob/main/samples/examples/simple-provider.html
I also have read following article too:
[Simple Provider Example]https://github.com/microsoftgraph/microsoft-graph-toolkit/blob/main/samples/examples/simple-provider.html
[A lap around microsoft graph toolkit day 7]https://developer.microsoft.com/en-us/office/blogs/a-lap-around-microsoft-graph-toolkit-day-7-microsoft-graph-toolkit-providers/
is there someone can pointing to me more details explanation about how to archive this.
Can someone explains further below response further. How to do it. Where should I place the code and how to return AccessToken to SimpleProvider?
Edited:
Update my question to be more precise to what I want besides on top of the question. Below is the code I used in Startup.cs to automatically trigger pop up screen when user using the web app. When using the sample provided, it is always cannot get access token received or userid data. Question 2: How to save or store token received in memory or cache or cookies for later use by ProxyController and its classes.
//Sign in link under _layouts.aspx
<a class="nav-link" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
// Use OpenId authentication in Startup.cs
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
// Specify this is a web app and needs auth code flow
.AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAd", options);
options.Prompt = "select_account";
options.Events.OnTokenValidated = async context =>
{
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) =>
{
var token = await tokenAcquisition
.GetAccessTokenForUserAsync(GraphConstants.Scopes, user: context.Principal);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);
// Get user information from Graph
try
{
var user = await graphClient.Me.Request()
.Select(u => new
{
u.DisplayName,
u.Mail,
u.UserPrincipalName,
u.MailboxSettings
})
.GetAsync();
context.Principal.AddUserGraphInfo(user);
}
catch (ServiceException)
{
}
// Get the user's photo
// If the user doesn't have a photo, this throws
try
{
var photo = await graphClient.Me
.Photos["48x48"]
.Content
.Request()
.GetAsync();
context.Principal.AddUserGraphPhoto(photo);
}
catch (ServiceException ex)
{
if (ex.IsMatch("ErrorItemNotFound") ||
ex.IsMatch("ConsumerPhotoIsNotSupported"))
{
context.Principal.AddUserGraphPhoto(null);
}
}
};
options.Events.OnAuthenticationFailed = context =>
{
var error = WebUtility.UrlEncode(context.Exception.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
context.HandleResponse();
return Task.FromResult(0);
};
options.Events.OnRemoteFailure = context =>
{
if (context.Failure is OpenIdConnectProtocolException)
{
var error = WebUtility.UrlEncode(context.Failure.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
context.HandleResponse();
}
return Task.FromResult(0);
};
})
// Add ability to call web API (Graph)
// and get access tokens
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, GraphConstants.Scopes)
// Add a GraphServiceClient via dependency injection
.AddMicrosoftGraph(options =>
{
options.Scopes = string.Join(' ', GraphConstants.Scopes);
})
// Use in-memory token cache
// See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
.AddInMemoryTokenCaches();
Since you are using MVC, I recommend using the ProxyProvider over the Simple Provider.
SimpleProvider - useful when you have existing authentication on the client side (such as Msal.js)
ProxyProvider - useful when you are authenticating on the backend and all graph calls are proxied from the client to your backend.
This .NET core MVC sample might help - it is using the ProxyProvider with the components
Finally, I have discovered how to do my last mile bridging for these two technology.
Following are the lines of the code that I have made the changes. Since I'm using new development method as oppose by MSAL.NET, a lot of implementation has been simplified, so many of examples or article out there, may not really able to use it directly.
Besides using links shared by #Nikola and me above, you also can try to use below
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/
to consolidate to become your very own solution. Below are the changes I have made to make it worked.
Change in Startup.cs class
// Add application services. services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>(); //services.AddSingleton<IGraphServiceClientFactory, GraphServiceClientFactory>();
Change in ProxyController.cs class
private readonly GraphServiceClient _graphClient;
public ProxyController(IWebHostEnvironment hostingEnvironment, GraphServiceClient graphclient)
{
_env = hostingEnvironment;
//_graphServiceClientFactory = graphServiceClientFactory;
_graphClient = graphclient;
}
Change in ProcessRequestAsync method under ProxyController.cs
//var graphClient = _graphServiceClientFactory.GetAuthenticatedGraphClient((ClaimsIdentity)User.Identity);
var qs = HttpContext.Request.QueryString;
var url = $"{GetBaseUrlWithoutVersion(_graphClient)}/{all}{qs.ToUriComponent()}";
var request = new BaseRequest(url, _graphClient, null)
{
Method = method,
ContentType = HttpContext.Request.ContentType,
};

Using Google Assistant Change Firebase Database Value

I Created a android app in which if a press a button and value changes in Firebase database (0/1) , i want to do this using google assistant, please help me out, i searched out but didn't found any relevant guide please help me out
The code to do this is fairly straightforward - in your webhook fulfillment you'll need a Firebase database object, which I call fbdb below. In your Intent handler, you'll get a reference to the location you want to change and make the change.
In Javascript, this might look something like this:
app.intent('value.update', conv => {
var newValue = conv.prameters.value;
var ref = fbdb.ref('path/to/value');
return ref.set(newValue)
.then(result => {
return conv.ask(`Ok, I've set it to ${newValue}, what do you want to do now?`);
})
.catch(err => {
console.error( err );
return conv.close('I had a problem with the database. Try again later.');
});
return
});
The real problem you have is what user you want to use to do the update. You can do this with an admin-level connection, which can give you broad access beyond what your security rules allow. Consult the authentication guides and be careful.
I am actually working on a project using Dialogflow webhook and integrated Firebase database. To make this posible you have to use the fulfilment on JSON format ( you cant call firebasedatabase in the way you are doing)
Here is an example to call firebase database and display a simple text on a function.
First you have to take the variable from the json.. its something loike this (on my case, it depends on your Entity Name, in my case it was "tema")
var concepto = request.body.queryResult.parameters.tema;
and then in your function:
'Sample': () => {
db.child(variable).child("DESCRIP").once('value', snap => {
var descript = snap.val(); //firebasedata
let responseToUser = {
"fulfillmentMessages": [
{ //RESPONSE FOR WEB PLATFORM===================================
'platform': 'PLATFORM_UNSPECIFIED',
"text": {
"text": [
"Esta es una respuesta por escritura de PLATFORM_UNSPECIFIED" + descript;
]
},
}
]
}
sendResponse(responseToUser); // Send simple response to user
});
},
these are links to format your json:
Para formatear JSON:
A) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Platform
B) https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/Shared.Types/Message#Text
And finally this is a sample that helped a lot!!
https://www.youtube.com/watch?v=FuKPQJoHJ_g
Nice day!
after searching out i find guide which can help on this :
we need to first create chat bot on dialogflow/ api.pi
Then need to train our bot and need to use webhook as fullfillment in
response.
Now we need to setup firebase-tools for sending reply and doing
changes in firebase database.
At last we need to integrate dialogflow with google assistant using google-actions
Here is my sample code i used :
`var admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
var database = admin.database();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.hello = functions.https.onRequest((request, response) => {
let params = request.body.result.parameters;
database.ref().set(params);
response.send({
speech: "Light controlled successfully"
});
});`

Titanium Appcelerator API call error - HTTP ERROR

I am having a website which contains login page. When user tries to log in using username and password. Data is being passed in Form Data. Please have a look as following image to get idea.
Now I want to use the same api in my Titanium application and get all details or logged in user which i am performing using below mentioned code.
var url= "http://www.randomwebsite.com/login/";
var jsonData = {
username: "admin",
password: "password1"
};
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function(e) {
var obj = JSON.parse(this.responseText);
alert("DATA IS " + JSON.stringify(obj));
};
xhr.onerror = function(e) {
Ti.API.info("ERROR " + e.error);
};
xhr.onsendstream = function(e){
Ti.API.info("onsendstream");
};
xhr.ondatastream = function(e){
Ti.API.info("ondatastream");
};
xhr.open('POST',url);
xhr.send(JSON.stringify(jsonData));
I am getting HTTP error. I even tried setting xhr.setHeader('Content-Type','application/json') as well as verified url its same as that is being used by website. Can any one help me out with this ? Or is there any way in order to make sure that titanium code passes data in form-data ? Or any suggestion regarding this would be of great help.
Its working fine now. Mistake that I was doing is that i was stringifying text when data was being send. So changing xhr.send(JSON.stringify(jsonData)) to xhr.send(jsonData) works for me. Hope so this would help some one.

Let user turn off different notification types using parse.com's cloud code

First time posting on here so bear with me. I am taking a dive into parse.com's cloud code without any knowledge of javascript so I could use a little help.
I got an afterSave push notification working with Cloud Code but I need a way to allow users to subscribe/unsubscribe from different types of notifications. The way I am currently attempting to do this is by storing bool values in the parse user table for the different types of notifications but I'm having trouble getting that value in cloud code. Here is my cloud code:
Parse.Cloud.afterSave("Comment", function(request){
var comment = request.object;
var fromUser = request.user;
var onIdea = comment.get("ideaPointer");
var ideaOwner = onIdea.get("owner");
var getNotification = ideaOwner.get("getCommentNotifications");
var message = fromUser.getUsername() + " commented on your idea.";
if (getNotification){
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", ideaOwner);
Parse.Push.send({
where: pushQuery,
data: {
alert: message,
ideaId: onIdea.id
}
});
}
});
Here is the error that gets printed to the logs when a comment is saved:
Result: TypeError: Cannot call method 'get' of undefined at main.js:6:34
Here is the line it is having a problem with because it was working before I added it along with the if statement:
var getNotification = ideaOwner.get("getCommentNotifications");
getCommentNotifications is the bool value in the user table.
I'm also not sure if my if statement is written correctly or not:
if (getNotification){}
I have also verified that getCommentNotifications value for the ideaOwner I'm testing on isn't empty.
Any help with this issue or ideas on a better way to allow users to subscribe/unsubscribe from different notifications types would be much appreciated.
The other ends of the those pointers must be fetched. If they really are pointers, then you can treat them as incompletely initialized objects, so...
Parse.Cloud.afterSave("Comment", function(request){
var comment = request.object;
var fromUser = request.user;
var onIdea = comment.get("ideaPointer");
onIdea.fetch().then(function(onIdeaObject) {
var ideaOwner = onIdea.get("owner");
return ideaOwner.fetch();
}).then(function(ideaOwnerObject) {
var getNotification = ideaOwnerObject.get("getCommentNotifications");
if (getNotification) {
var message = fromUser.getUsername() + " commented on your idea.";
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", ideaOwnerObject);
return Parse.Push.send({ where: pushQuery, data: { alert: message, ideaId: onIdea.id } });
}
});
});

logging in with different user / resource owner

i am trying to write a tool that creates entries in the google calendar.
after following the google docs and creating an client-identifier/secret in the api console, i managed to put together a client that authenticates correctly and shows my registered google calendars. right now for me it looks like my google-account is somehow tied to my client-identifier/secret. what i want to know is: how can i change the auth process so that it is possible for an other user of this tool to enter his google-id and get access to his calendars?
EDIT: in other words (used in the RFC): I want make the resource owner-part editable while leaving the client-part unchanged. but my example, although working, ties together client and resource owner.
here is my app that works fine so far:
public void Connect()
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "123456123456.apps.googleusercontent.com";
provider.ClientSecret = "nASdjKlhnaxEkasDhhdfLklr";
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new CalendarService(auth);
//Events instances = service.Events.Instances("primary", "recurringEventId").Fetch();
var list = service.CalendarList.List().Fetch();
foreach (var itm in list.Items)
Console.WriteLine(itm.Summary);
}
private static readonly byte[] AditionalEntropy = { 1, 2, 3, 4, 5 };
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
var state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
var refreshToken = LoadRefreshToken();
if (!String.IsNullOrWhiteSpace(refreshToken))
{
state.RefreshToken = refreshToken;
if (arg.RefreshToken(state))
return state;
}
var authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
var frm = new FormAuthCodeInput();
frm.ShowDialog();
// Retrieve the access token by using the authorization code:
var auth = arg.ProcessUserAuthorization(frm.txtAuthCode.Text, state);
StoreRefreshToken(state);
return auth;
}
private static string LoadRefreshToken()
{
try
{
return Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(Properties.Settings.Default.RefreshToken), AditionalEntropy, DataProtectionScope.CurrentUser));
}
catch
{
return null;
}
}
private static void StoreRefreshToken(IAuthorizationState state)
{
Properties.Settings.Default.RefreshToken = Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(state.RefreshToken), AditionalEntropy, DataProtectionScope.CurrentUser));
Properties.Settings.Default.Save();
}
Prompt the user to enter their ClientIdentifier and ClientSecret, then pass these values to your Connect method.
i solved the problem myself.
the problem was, that i'm usually always connected to google and because i did't log out from google before my app redirected to google to get the access-token, google automatically generated the access-token for my account - skipping the part where an input-form appears where anyone could enter his/her user-credentials to let google generate an access-token for his/her account.

Resources