How to send specific user ID from bot framework emulator v4? - botframework

I need to send a specific user ID from the bot emulator (https://github.com/microsoft/BotFramework-Emulator). I use this textbox (see on a picture below)
But nothing sent. There is absolutely another guid in activity.From.Id.
Is it possible to sent message from emulator with a specific user ID?

The short answer is, if you are using Direct Line to generate a token from a secret and you specify user Id there (see attached code), then Emulator should favor that value over any value you pass in thru the Emulator settings.
In my personal testing, the User ID setting seems to be overriding any other pre-existing value.
It should be noted, however, that if you specify a User ID value in settings, you will need to close the tabbed conversation and start it anew by re-entering the messaging endpoint and AppId/AppPassword (or reconnecting to your .bot file, if used). Simply pressing "Restart conversation" will not cause Emulator to pickup the User ID setting.
Hope of help!
// Listen for incoming requests.
server.post('/directline/token', (req, res) => {
// userId must start with `dl_` for Direct Line enhanced authentication
const userId = (req.body && req.body.id) ? req.body.id : `dl_${ Date.now() + Math.random().toString(36) }`;
const options = {
method: 'POST',
uri: 'https://directline.botframework.com/v3/directline/tokens/generate',
headers: {
'Authorization': `Bearer ${ process.env.directLineSecret }`
},
json: {
user: {
Id: `${ userId }`
}
}
};
request.post(options, (error, response, body) => {
if (!error && response.statusCode < 300) {
res.send(body);
console.log('Someone requested a token...');
} else {
res.status(500).send('Call to retrieve token from DirectLine failed');
}
});
});

Related

Window object is undefined after deploy to netlify

I want to build an email verification. After the user registers, the user gets an email and clicks on it for verification purposes. The email-link invokes a netlify lambda function (api end point). Inside the link is a jwt token, which I decode on the backend. I used
window.location.href
for it and sliced the part I needed and decoded it. On localhost, it works fine, however, if I deploy it to netlify, I get an
window is undefined
error. I read that you have to check for
typeof window !== 'undefined'
However, if I add that to my lambda function I don't get any console.log statements.
exports.handler = async (event, context, callback) => {
if (typeof window !== 'undefined') {
let url = window.location.href
let index = url.indexOf("=");
let token = url.slice(index+1)
console.log(token, 'token here')
const decoded = jwt.verify(token, process.env.SECRET);
console.log('confirm registration route triggered',decoded)
if (decoded) {
const { email } = decoded;
console.log(decoded, 'decoded here')
User.findOneAndUpdate({email: email}, {verified: true },(...e)=>{
console.log(e)
});
} else {
console.log('could not update user')
//redirect user to page with message about email confirmation link expiration
//and proposal to register again
}
console.log('confirm registration got invoked')
}
return {
statusCode: 400,
body: "Oops"
}
};
I read that the function first runs on the server when deployed and afterwards on the client. Seems like it does not run on my client, as I invoke the api-endpoint directly? I'm quite a beginner when it comes to API-Endpoints, thanks for reading!
In case you have the same issue when deploying to netlify, you have to run
event.queryStringParameters
which gives you access to the query parts of your url.

Get current mailbox from Outlook web addin

I just found this: https://learn.microsoft.com/en-us/office/dev/add-ins/reference/manifest/supportssharedfolders . Which tells me there is a way to load an addin into a postbox from another user. I have activated the feature via manifest, which is working fine.
To let the server know where to find the mail, I am currently working with, I need the postbox name, that I am currently in. So I went through the properties I get within Office.context. There seems to be no reference to the current mailbox. Just Office.context.mailbox.userProfile.emailAddress which is referring to my signed in user.
Since I need the current postbox to access the mail via Graph / EWS, there has to be a way to read it, else the SupportsSharedFolders would be senseless. How would I get the current postbox name/ID?
You can get an item's shared properties in Compose or Read mode by calling the item.getSharedPropertiesAsync method. This returns a SharedProperties object that currently provides the user's permissions, the owner's email address, the REST API's base URL, and the target mailbox.
The following example shows how to get the shared properties of a message or appointment, check if the delegate or shared mailbox user has Write permission, and make a REST call.
function performOperation() {
Office.context.mailbox.getCallbackTokenAsync({
isRest: true
},
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded && asyncResult.value !== "") {
Office.context.mailbox.item.getSharedPropertiesAsync({
// Pass auth token along.
asyncContext: asyncResult.value
},
function (asyncResult1) {
let sharedProperties = asyncResult1.value;
let delegatePermissions = sharedProperties.delegatePermissions;
// Determine if user can do the expected operation.
// E.g., do they have Write permission?
if ((delegatePermissions & Office.MailboxEnums.DelegatePermissions.Write) != 0) {
// Construct REST URL for your operation.
// Update <version> placeholder with actual Outlook REST API version e.g. "v2.0".
// Update <operation> placeholder with actual operation.
let rest_url = sharedProperties.targetRestUrl + "/<version>/users/" + sharedProperties.targetMailbox + "/<operation>";
$.ajax({
url: rest_url,
dataType: 'json',
headers:
{
"Authorization": "Bearer " + asyncResult1.asyncContext
}
}
).done(
function (response) {
console.log("success");
}
).fail(
function (error) {
console.log("error message");
}
);
}
}
);
}
}
);
}

Keystone.JS API User Authentication (not Admin-UI)

I would like to restrict my GraphQL API with User Authentication and Authorization.
All Keystone.JS documentation is talking about AdminUI authentication, which I'm not interested in at the moment.
Facts:
I want to have some social logins (no basic email/password)
I want to use JWT Bearer Tokens
Other than that you can suggest any possible way to achieve this.
My thoughts were:
I could have Firebase Authentication (which can use Google Sign-in, Apple Sign-in etc.) be done on the client-side (frontend) which would then upon successful authentication somehow connect this to my API and register user (?).
Firebase client SDK would also fetch tokens which I could validate on the server-side (?)
What is troubling is that I can't figure out how to do this in a GraphQL environment, and much less in a Keystone-wrapped GraphQL environment.
How does anyone do basic social authentication for their API made in Keystone?
Keystone authentication is independent of the Admin-UI. If you are not restricting your list with proper access control the authentication is useless. Default access is that it is open to all.
you can set default authentication at keystone level which is merged with the access control at list level.
Admin Ui Authentication
Admin UI only supports password authentication, meaning you can not go to /admin/signin page and authenticate there using other authentication mechanism. The Admin Ui is using cookie authentication. cookies are also set when you login using any other login method outside of admin-ui. This means that you can use any means of authentication outside of admin-ui and come back to admin ui and you will find yourself signed in.
Social Authentication:
Social authentication is done using passportjs and auth-passport package. there is documentation to make this work. Single Step Account Creation example is when you create user from social auth automatically without needing extra information (default is name and email). Multi Step Account Creation is when you want to capture more information like preferred username, have them accept the EULA or prompt for birthdate or gender etc.
JWT
I dont believe Keystone does pure JWT, all they do is set keystone object id in the cookie or the token is a signed version of item id (user item id) which can be decrypted only by the internal session manager using cookie secret.
Using Firebase to authenticate user
this is the flow of authentication after you create a custom mutation in keystone graphql.
client -> authenticate with Firebase -> get token -> send token to server -> server verifies the token with firebase using admin sdk -> authenticate existing user by finding the firebase id -> or create (single step) a user or reject auth call (multi step) and let client send more data like age, gender etc. and then create the user -> send token
here is the example of phone auth I did, you can also use passport based firebase package and implement your own solution.
keystone.extendGraphQLSchema({
mutations: [
{
schema: 'authenticateWithFirebase(token: String!): authenticateUserOutput',
resolver: async (obj, { token: fireToken }, context) => {
const now = Date.now();
const firebaseToken = await firebase.auth().verifyIdToken(fireToken);
const { uid, phone_number: phone } = firebaseToken;
const { errors, data } = await context.executeGraphQL({
context: context.createContext({ skipAccessControl: true }),
query: `
query findUserFromId($phone: String!, $uid: String!) {
firebaseUser: allUsers(where: { phone: $phone, firebaseId:$uid }) {
id
name
phone
firebaseId
}
}`,
variables: { phone, uid },
});
if (errors || !data.firebaseUser || !data.firebaseUser.length) {
console.error(errors, `Unable to find user-authenticate`);
throw errors || new Error('unknown_user');
}
const item = data.firebaseUser[0];
const token = await context.startAuthedSession({ item, list: { key: 'User' } });
return { item, token };
},
},
{
schema: 'signupWithFirebase(token: String!, name: String!, email: String): authenticateUserOutput',
resolver: async (obj, { token: fireToken, name, email }, context) => {
const firebaseToken = await firebase.auth().verifyIdToken(fireToken);
const { uid, phone_number: phone } = firebaseToken;
const { errors, data } = await context.executeGraphQL({
context: context.createContext({ skipAccessControl: true }),
query: `
query findUserFromId($phone: String!, $uid: String!) {
firebaseUser: allUsers(where: { phone: $phone, firebaseId:$uid }) {
id
name
phone
firebaseId
}
}`,
variables: { phone, uid },
});
if (errors) {
throw errors;
}
if (data.firebaseUser && data.firebaseUser.length) {
throw new Error('User already exist');
}
const { errors: signupErrors, data: signupData } = await context.executeGraphQL({
context: context.createContext({ skipAccessControl: true }),
query: `
mutation createUser($data: UserCreateInput){
user: createUser(data: $data) {
id
name
firebaseId
email
phone
}
}`,
variables: { data: { name, phone: phone, firebaseId: uid, email, wallet: { create: { walletId: generateWalletId() } }, cart: { create: { lineItems: { disconnectAll: true } } } } },
});
if (signupErrors || !signupData.user) {
throw signupErrors ? signupErrors.message : 'error creating user';
}
const item = signupData.user;
const token = await context.startAuthedSession({ item, list: { key: 'User' } });
return { item, token };
},
},
],
})

Cannot get the getCallbackTokenAsync to function correctly

I am a newbie to outlook js. I am developing a very simple add-in. The add-in simply will forward a selected email to a defined email address. So we click a button and forward the message. My command handler gets called, but that is about all I have gotten to work. The first problem is the authorization does not appear to work. I have followed the example on https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api.
The permission in my manifest is set to ReadWriteMailbox.
var accessToken;
Office.onReady(info => {
// If needed, Office.js is ready to be called
Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function(result) {
if (result.status === "succeeded") {
accessToken = result.value;
} else {
accessToken = "error";
}
});
});
function MyButtonClick(event) {
const message = {
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Performed action. Access token: " + accessToken,
icon: "Icon.80x80",
persistent: true
}
Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);
event.completed();
}
I have tried moving the getCallbackTokenAsync all around, but it seems not to work properly. The accessToken is always undefined.
I have been messing with this for the past day. So I am assuming I am missing something.
We are primarily targeting Outlook 2016 on the mac and windows 10.
Any thoughts?
Tom

How to get space Id of users who have not added Google Chat Bot to their coversation

We are implementing a Google hangout Chat Bot , Which will send proactive notification to the user in domain. To do this Google chat Bot API requires the space Id to send proactive notification to user.
Reference document: https://developers.google.com/hangouts/chat/reference/rest/v1/spaces/list
code :
jwtClient.authorize(function (err) {
if (err) {
console.log(err);
return;
}
else {
chat.spaces.list({
auth: jwtClient
}, function (err, resp) {
if (err)
console.log(err);
else {
chat.spaces.list({
auth: jwtClient
}, function (err, resp) {
if (err)
console.log(err);
else {
var spaceList = resp.data.spaces;
spaceList.forEach(element => {
var spaceUrl = `https://chat.googleapis.com/v1/${element.name}/messages?key=${apiKey}`;
request({
url: spaceUrl,
method: "POST",
headers: {
'Content-Type': 'application/json'
},
json: customMessage
},
function (error, response, body) {
callback(error, body)
}
);
})
};
});
}
});
}
});
}
}
But This API returns space list of only those user , who has added the Bot to their coversation.
Is their any work around to get/create space of/to every user in google domain?
Unfortunately there is no way to extract the Space ID without the user ever interacting with the bot. Allowing this would give the bot ability to spam any user whenever without consent.
I would suggest storing space IDs to a database. So once a user has started a conversation with a bot, you can later message them whenever you want. Adding the bot or interacting with it in a room is the "consent" that is needed for a bot to message a user.

Resources