Do notifications currently in beta work in testing? - actions-on-google

I'm trying to push a notification to an unpublished Action in testing. I'm using a snippet I found here
https://developers.google.com/actions/assistant/updates
In particular
function send(err, tokens) {
var notif, payload;
notif = { userNotification: { title: 'Commuter Alert' },
target: { userId: userId, intent: intent } };
console.log( JSON.stringify(notif) );
payload = { 'auth': { 'bearer': tokens.access_token },
'json': true,
'body': { 'customPushMessage': notif, 'isInSandbox': false } };
request.post('https://actions.googleapis.com/v2/conversations:send',
payload,
responseComplete);
}
I get a 400/Bad Request response with a message of
Invalid user id for target.
The notification stringified looks like this:
{"userNotification":{"title":"Commuter Alert"},"target":{"userId":"APhe68Has7QXmEFRmxhe9MGcLK2t","intent":"www.whereismybus.xyz.intent.NOTIFY_QUERY"}}
and the userId that it shows is the same as the one that shows on the request tab in the simulator
"user": {
"userId": "APhe68Has7QXmEFRmxhe9MGcLK2t",
"permissions": [
"UPDATE"
], ...
To my nearsighted eyes, it looks like the userId is OK. Anyone?
EDIT: It turns out that the error message is correct and so is the code. When I try testing the Action under a different identity the POST completes with a 200/OK status. What is slightly weird is that the user id that works is about twice as long as the one that does not. The one that does not has 2FA turned on but I don't know if that is significant.

Related

How to update me endpoint in Strapi?

Im working with Strapi v3.4.0 for a project. I want to allow the authenticated user to update his personal informations when hitting the following endpoint:
PUT /users/me
for now I'm just trying to console.log a message when i hit the endpoint, I have followed the step from this video: https://www.youtube.com/watch?v=ITk-pYtOCnQ but I keep getting 403 error "Forbidden". Am I doing something wrong?
I understand this update me problem in Strapi is really painful. I have also followed the tutorial on the link you put above to no avail since Strapi just updated to the new version. I tried a workaround for this solution. So basically, I tried to create an additional method on the model that shows on the api folder (Previously, I am trying to add a new method on user controller but again I got this 403 error as well). As for my approach, I created a model called User Profile and then add the custom method for updating the current user data shown below.
api/user-profile/config/routes.json
...
{
"method": "PUT",
"path": "/updateMe",
"handler": "user-profile.updateMe",
"config": {
"policies": []
}
},
{
"method": "PUT",
"path": "/user-profiles/:id",
"handler": "user-profile.update",
"config": {
"policies": []
}
}
...
and on the controller, I added the following snippets
api/user-profile/controllers/user-profile.js
'use strict';
const _ = require('lodash');
const { sanitizeEntity } = require('strapi-utils');
const sanitizeUser = user =>
sanitizeEntity(user, {
model: strapi.query('user', 'users-permissions').model,
});
const formatError = error => [
{ messages: [{ id: error.id, message: error.message, field: error.field }] },
];
module.exports = {
async updateMe(ctx) {
const { id } = ctx.state.user;
let updateData = {
...ctx.request.body,
};
const data = await strapi.plugins['users-permissions'].services.user.edit({ id }, updateData);
ctx.send(sanitizeUser(data));
},
};
After that, enable the updateMe for the public use (for now, you do not have to worry since the ctx.state.user line will check if the token is valid or not, { at least until the developer officially create this updateMe function })
That is all. You just have to pass the attributes to the body and the auth header and you are good to go. You can pretty much put the function anywhere you want
PS: Take a note that you have to put the updateMe route above the update route. Else, it will give you the same 403 error
PPS: This is just a workaround until the developer officially includes the updateMe function, which we cannot expect in short time

AWS Amplify AppSync Subscription not working correctly

I wrote a small application that subscribes to DB changes using AWS Amplify CLI / AppSync. All amplify api calls work perfectly (mutations, queries) but unfortunately the observer does not receive events. I can see that the MQTT socket receives periodically binaries but I can't obtain changed objects.
I configured Amplify for amplify use. I can see in the debugger that the AppSyncProvider has been initisalised. Also tried API and PubSub but makes no difference.
const awsmobile = {
"aws_appsync_graphqlEndpoint": "https://[...].appsync-api.[...]/graphql",
"aws_appsync_region": "[...]",
"aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
};
Amplify.configure(awsmobile);
ngOnInit()
{
try {
this.apiService.OnUpdateA.subscribe(
{
next: (x) => {[...]},
error: (e) => {[...]},
complete: () => {[...]}
});
}
catch (error) {[...] }
}
***Schema***
type A
#model
#auth(rules: [
{allow: owner},
{allow: groups, groups: ["A"], operations: [create, update, read]},
{allow: groups, groups: ["B"], operations: [read]},
])
{
id: ID!
entry: AnotherType! #connection(name: "AnotherConnection")
[...]
}
OnUpdateAListener: Observable<
OnUpdateASubscription
> = API.graphql(
graphqlOperation(
`subscription OnUpdateA($owner: String) {
onUpdateA(owner: $owner) {
__typename
id
owner
[...]
}
}`
)
) as Observable<OnUpdateASubscription>;
Anyone for any ideas?
**Logs:**
{mqttConnections: Array(1), newSubscriptions: {…}, provider: Symbol(INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER)}
mqttConnections: Array(1)
0: {url: "wss://[...]-ats.iot.[...].amazonaws…[...]%3D%3D", topics: Array(2), client: "[...]"}
length: 1
__proto__: Array(0)
newSubscriptions:
onUpdate:
expireTime: 1573313050000
topic: "[....]/22tmaezjv5555h4o7yreu24f7u/onUpdate/1cd033bad555ba55555a20690d3e04e901145776d3b8d8ac95a0aea447b273c3"
__proto__: Object
__proto__: Object
provider: Symbol(INTERNAL_AWS_APPSYNC_PUBSUB_PROVIDER)
__proto__: Object
However, not sure whether it is suspicious that the subscription Object has no queue?
Subscription {_observer: {…}, _queue: undefined, _state: "ready", _cleanup: ƒ}
_cleanup: ƒ ()
_observer:
next: (x) => {…}
__proto__: Object
_queue: ***undefined***
_state: "ready"
closed: (...)
__proto__: Object
Many thanks in advance.
For those who are experiencing the same behaviour. It was due to the fact that I had the owner in the auth section of the schema. Deleted the {allow: owner}, part and the subscriptions started to work immediately.
here is a working example of AWS Amplify Subscriptions:
import Amplify from 'aws-amplify';
import API from '#aws-amplify/api';
import PubSub from '#aws-amplify/pubsub';
import awsconfig from './aws-exports';
Amplify.configure(awsconfig);
API.configure(awsconfig);
PubSub.configure(awsconfig);
// put above in root
// below is example
import { API, graphqlOperation } from 'aws-amplify';
var onAddNote = `subscription OnCreateNote {
onCreateNote {
id
patient {
id
organization {
id
}
}
}
}
`;
listenForNoteAdd() {
return API.graphql(graphqlOperation(onAddNote) ).subscribe({next: (noteData) => {
console.log("new note so reload consider reload")
let note = noteData.value.data.onCreateNote
console.log(JSON.stringify(note))
// now that you have indication of something happening
// do what you must next
}})
}
I had the same problem with GraphQL. Thing is: we have to return Owner in mutation response in order to let Subscription know to whom to send this event.
removing {allow: owner} did worked for me but thats not the right way since we require it in order to have owner based access to data.
so the correct way i found is:
if subscription is:
subscription MySubscription {
onCreateuser(owner: "$userName") {
id
name
number
}
}
mutation should be:
mutation MyMutation {
createUser(input: {name: "xyz", id: "user123", number: "1234567890"}) {
id
name
number
owner
}
}
we must return owner in mutation's response in order to get the subscription to that event and all other properties as same as mutation response.
For those coming here experiencing this error, do not delete {allow: owner}. Allow owner ensures only a user authenticated with Cognito User Pool can run queries, mutations, etc.
It looks like the OP is using amplify codegen to generate his API service, and if you look the listener has param for owner. It's optional, but if your #auth is {allow: owner} it is required.
Additional note: Not sure if he is using the correct owner field stored in his datastore or not. If there is not already an owner field created (or a different field specified), it will create one with a unique uuid. So he could be passing the incorrect owner or none at all.
Run a simple call to get the owner...
export const GetOwner = async (id: string): Promise<GetOwnerQuery> => {
const statement = `query GetAppData($id: ID!) {
getAppData(id: $id) {
owner
}
}`;
const gqlAPIServiceArguments: any = {
id,
};
const response = (await API.graphql(graphqlOperation(statement, gqlAPIServiceArguments))) as any;
return <GetOwnerQuery>response.data.getAppData;
};
...and pass that in your subscription.
const { owner } = await GetOwner(id);
if (owner) {
this.apiUpdateListener$ = this.api.OnUpdateAppDataListener(owner).subscribe((data) => {
console.log('api update listener ===> ', data);
});
}

How to identify unique users with Diagflow

I am trying to make an assistant app and was using the cloud firestore service of firebase to send the response back to my app using webhook as fulfilment. I have used 'session' parameter in request JSON according to this documentation and sending fulfilmentText as response to the user. But whenever user launches the app, a new session is created which I don't want. I simply want, just a single entry for each user in my database so how to achieve that using dialogflow.
In Alexa Skill, we have deviceId as parameter by which we can uniquely identify the user irrespective of the session id but is there any parameter in the dialogflow request JSON. If not, then how to achieve this task without it.
The request JSON I am getting from Dialogflow has a userID in it, so can I use the userId or should I go with userStorage provided the userStorage parameter is not available in the request JSON.
request.body.originalDetectIntentRequest { source: 'google', version: '2', payload: { surface: { capabilities: [Object] },
inputs: [ [Object] ],
user:
{ locale: 'en-US',
userId: 'ABwppHG5OfRf2qquWWjI-Uy-MwfiE1DQlCCeoDrGhG8b0fHVg7GsPmaKehtxAcP-_ycf_9IQVtUISgfKhZzawL7spA' },
conversation:
{ conversationId: '1528790005269',
type: 'ACTIVE',
conversationToken: '["generate-number-followup"]' },
availableSurfaces: [ [Object] ] } }
EDIT : Thank You #Prisoner for the answer but I am unable to send the random ID generated in the response and set in in the payload. Below is the code where I am generating the uuid and storing it in firestore. What I am doing wrong in the below code due to which new uuid is generated for returning user and therefore response is shown as No document found in the database. I suppose I am not sending uuid appropriately. Please help.
exports.webhook = functions.https.onRequest((request, response) => {
console.log("request.body.queryResult.parameters", request.body.queryResult.parameters);
console.log("request.body.originalDetectIntentRequest.payload", request.body.originalDetectIntentRequest.payload);
let userStorage = request.body.originalDetectIntentRequest.payload.user.userStorage || {};
let userId;
console.log("userStorage", userStorage);
if (userId in userStorage) {
userId = userStorage.userId;
} else {
var uuid = require('uuid/v4');
userId = uuid();
userStorage.userId = userId
}
console.log("userID", userId);
switch (request.body.queryResult.action) {
case 'FeedbackAction': {
let params = request.body.queryResult.parameters;
firestore.collection('users').doc(userId).set(params)
.then(() => {
response.send({
'fulfillmentText' : `Thank You for visiting our ${params.resortLocation} hotel branch and giving us ${params.rating} and your comment as ${params.comments}.` ,
'payload': {
'google': {
'userStorage': userStorage
}
}
});
return console.log("resort location", params.resortLocation);
})
.catch((e => {
console.log('error: ', e);
response.send({
'fulfillmentText' : `something went wrong when writing to database`,
'payload': {
'google': {
'userStorage': userStorage
}
}
});
}))
break;
}
case 'countFeedbacks':{
var docRef = firestore.collection('users').doc(userId);
docRef.get().then(doc => {
if (doc.exists) {
// console.log("Document data:", doc.data());
var dat = doc.data();
response.send({
'fulfillmentText' : `You have given feedback for ${dat.resortLocation} and rating as ${dat.rating}`,
'payload': {
'google': {
'userStorage': userStorage
}
}
});
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
response.send({
'fulfillmentText' : `No feedback found in our database`,
'payload': {
'google': {
'userStorage': userStorage
}
}
});
}
return console.log("userStorage_then_wala", userStorage);
}).catch((e => {
console.log("Error getting document:", error);
response.send({
'fulfillmentText' : `something went wrong while reading from the database`,
'payload': {
'google': {
'userStorage': userStorage
}
}
})
}));
break;
}
You have a couple of options, depending on your exact needs.
Simple: userStorage
Google provides a userStorage object which is persisted across conversations when it can identify a user. This lets you store your own identifier when you need to track when a user returns.
The easiest way to do this is to check the userStorage object for the identifier when your webhook is called. If it doesn't exist, create one using something like a v4 UUID and save it in the userStorage object.
If you are using the actions-on-google library, the code might look something like this:
let userId;
// if a value for userID exists un user storage, it's a returning user so we can
// just read the value and use it. If a value for userId does not exist in user storage,
// it's a new user, so we need to generate a new ID and save it in user storage.
if (userId in conv.user.storage) {
userId = conv.user.storage.userId;
} else {
// Uses the "uuid" package. You can get this with "npm install --save uuid"
var uuid = require('uuid/v4');
userId = uuid();
conv.user.storage.userId = userId
}
If you are using the dialogflow library, you can use the above, but you'll need this line first:
let conv = agent.conv();
If you're using the multivocal library, it does all of the above for you and will provide a UserID in the environment under the path User/Id.
If you're handling the JSON directly, and you are using the Dialogflow v2 protocol, you can get the userStorage object by examining originalDetectIntentRequest.payload.user.userStorage in the JSON request object. You'll set the payload.google.userStorage object in the JSON response. The code is similar to the above and might look something like this:
let userStorage = body.originalDetectIntentRequest.payload.user.userStorage || {};
let userId;
// if a value for userID exists un user storage, it's a returning user so we can
// just read the value and use it. If a value for userId does not exist in user storage,
// it's a new user, so we need to generate a new ID and save it in user storage.
if (userId in userStorage) {
userId = userStorage.userId;
} else {
// Uses the "uuid" package. You can get this with "npm install --save uuid"
var uuid = require('uuid/v4');
userId = uuid();
userStorage.userId = userId
}
// ... Do stuff with the userID
// Make sure you include the userStorage as part of the response
var responseBody = {
payload: {
google: {
userStorage: JSON.stringify(userStorage),
// ...
}
}
};
Note the first line of the code - if userStorage doesn't exist, use an empty object. It won't exist until you send a response that includes storing something in it for the first time, which will happen in the last few lines of this code.
Advanced: Account Linking
You can request users to sign in to your Action using Google Sign In. This can be done just using voice for the simplest of cases and would only interrupt the flow the first time.
After this, your Action is given a JWT which contains their Google ID which you can use as their identifier.
If you're using the actions-on-google library, you can get the ID from the decoded JWT with a line such as:
const userId = conv.user.profile.payload.sub;
In the multivocal library, the ID from the decoded JWT is available in the environment under the path User/Profile/sub
Deprecated: Anonymous User ID
You'll see some answers here on StackOverflow that reference an Anonymous User ID. Google has deprecated this identifier, which was not always a reliable way to verify returning users, and will be removing it 1 Jun 2019.
This code is currently still being sent, but this will be removed starting 1 Jun 2019.

Updating current user's email address in Meteor

I'm having a problem updating the current user's email address in Meteor. The problem code is here (it's all client code):
var id = Meteor.userId();
if (firstName) {
Meteor.users.update(
{ _id: id },
{ $set: { "profile.firstName": firstName }}
)};
if (lastName) {
Meteor.users.update(
{ _id: id },
{ $set: { "profile.lastName": lastName }}
)};
var oldEmail = Meteor.user().emails[0].address;
if (newEmail) {
Meteor.users.update(
{ _id: id, 'emails.0.address': oldEmail },
{ $set: { 'emails.0.address': newEmail }}
)};
The first two lines work fine (user can update their first and last names), but the last update fails with the following error showing in the console:
"errorClass {isClientSafe: true, error: 403, reason: "Not permitted. Untrusted code may only update documents by ID."
I don't understand the error, because I AM updating by ID--or at least I think I am.
Also: if I remove the reference to the old email, I get a simple "Update failed. Access denied" error in the console instead of the above-mentioned error.
Is there a way to fix this with client-side code only?
(I realize I'll also need to reset the "verified" key back to false, but that's a different issue I guess)
Do not edit the emails array directly. The Accounts package has utility functions for this use case, see Accounts.addEmail and Accounts.removeEmail.
First you will need to invoke a Method since these functions must be performed on the server.
Client js:
if (newEmail) {
Meteor.call('updateEmail', newEmail, err => {
if (err) console.log(`Error updating email address: {err}`);
});
}
server:
Meteor.methods({
updateEmail(newAddress) {
const userId = this.userId;
if (userId) {
const currentEmail = Meteor.users.findOne(userId).emails[0].address;
Accounts.addEmail(userId, newAddress);
Accounts.removeEmail(userId, currentEmail)
}
return;
}
});
You should also validate in your method that the new email address is a string that has an email address pattern.

YouTrack email notification using custom fields

I've added a custom field for 'interested parties' (users) in a particular issue, not project specific, and it works fine.
I would like YouTrack to generate emails to their email address on update or change of the issue, like they do to the person who it is assigned to, is this possible?
Let's say you want to send notifications by e-mail when a ticket is ready to be reviewed. People responsible for the review are set via a Reviewer custom field (which can contain multiple values). Then you can send notifications as follows:
var entities = require('#jetbrains/youtrack-scripting-api/entities');
exports.rule = entities.Issue.stateMachine({
title: 'Workflow',
fieldName: 'State',
states: {
'To Be Reviewed': {
onEnter: function(ctx) {
var issue = ctx.issue;
issue.fields.Reviewer.forEach(function(user) {
user.notify("Reminder", "This is a reminder", true);
});
},
transitions: {}
},
},
requirements: {
Reviewer: {
type: entities.User.fieldType,
multi: true
}
}
});
You can create a custom workflow like the following one:
when {
if (Interested Parties.isNotEmpty) {
for each user in Interested Parties {
user.notify("subj", "body");
}
}
}
Another point is that you probably do not need this field since you can 'star' an issue on behalf of a user and the user thus will be notified about any changes. Just type star user_name in the command window.