How do i handle oauth in Nuxt with a separate API server? - go

Currently I have two separate apps
Frontend (Nuxt)
Backend (Golang)
On the backend I'm using a third party library called Goth and I'm using Facebook as the provider. Everything works fine on the backend but I'm confused on how to do on the frontend which is on the Nuxt side
So technically on the backend there will be two urls
/auth/facebook
/auth/facebook/callback
Once everything is correct then I will get the object from facebook on the backend side which is the API written in Golang
data: {
RawData: {
email: "john#gmail.com",
first_name: "John",
id: "123123",
last_name: "Grave",
name: "John Grave",
picture: {
data: {
height: 50,
is_silhouette: true,
url: "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=13123123&height=50&width=50&ext=1553079619&hash=AeTX5RW5K_avWLbI",
width: 50
}
}
},
Provider: "facebook",
Email: "john#gmail.com",
Name: "John Grave",
FirstName: "John",
LastName: "Grave",
NickName: "John Grave",
Description: "",
UserID: "123123",
AvatarURL: "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=2312802522337124&height=50&width=50&ext=1553079619&hash=AeTX5RW5K_avWLbI",
Location: "",
AccessToken: "EAAIuR3NSCPwBAEcp2jskHuUCzdWLB97Aq99nCV5HuieVVz8xGfJ6exAZDZD",
AccessTokenSecret: "",
RefreshToken: "",
ExpiresAt: "2019-04-19T15:52:59.895655+08:00"
},
status: 200
}
Assume that everything is working fine on the backend.
The only thing that I could think of is calling it on the method (Nuxt side)
export default {
methods: {
facebookLogin() {
window.location.href = `http://localhost:8080/auth/facebook`
}
}
}
This will just redirect to the
http://localhost:8080/auth/facebook/callback?code=AQAaq9GYcGAnQ9wUCDAd5BFRHxMRjqGFR0J6zjGtYpD-
What are the correct steps should I do to communicate with the backend OAuth API?
Thanks!

Hi #sinusGob you can use this the auth plugin of nuxt
See the docs.
https://auth.nuxtjs.org/reference/providers/facebook
Thanks.

Related

Set Cookies in apollo server azure functions

I am using apollo server in the azure function. I want to set cookies from apollo server azure functions. But it's not working. It doesn't throw any kind of errors.
How do I set cookies in apollo server azure functions? I tried this way but it's not working.
Here is my code
import { ApolloServer, gql } from "apollo-server-azure-functions";
import { ApolloServerPluginLandingPageLocalDefault } from "apollo-server-core";
import { serialize, parse } from "cookie";
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
user: User
}
type User {
id: ID!
name: String!
email: String!
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
user: (parents, args, { request, context }, info) => {
const cookie = serialize("token", "123", {
expires: new Date(Date.now() + 900000),
httpOnly: true,
});
context.res.setHeader("Set-Cookie", cookie);
return {
id: "1",
name: "John Doe",
email: "john#example.com",
};
},
},
};
// #ts-ignore
const server = new ApolloServer({
typeDefs,
resolvers,
debug: true,
plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })],
context: (context) => {
return context;
},
});
export default server.createHandler({
cors: {
origin: ["*", "https://studio.apollographql.com"],
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: [
"access-control-allow-header",
"access-control-allow-credentials",
"access-control-allow-origin",
"content-type",
],
},
});
There is no documentation available for apollo server azure functions.
Official repository from apollo server azure functions: https://github.com/Azure-Samples/js-e2e-azure-function-graphql-hello.git
Sharing the discussion with the team internal and posting the update as updated here.
After looking at the issue, the infrastructure, and the announcement from Apollo for this package, I believe Apollo is the correct organization to post this issue because Apollo is providing the server in this sample. It just happens to be running on an Azure Function. Additionally, when I look for a solution on Apollo, it looks like the ApolloServer dependency needs to be swapped out for an Apollo server for express dependency in order to successfully set the cookie.
None of this is great news. I apologize for this.
I believe the sample works in this repo without cookes and doesn't currently include cookies in the code. Moving forward with the Apollo dependency, we will re-evaluate its use based on this feedback.

Close MS Teams StageView programmatically

I'm displaying a third party web page (client page) in a StageView, opened from an AdaptiveCard tabInfoAction:
{
type: "invoke",
title: "open in stageView",
value: {
type: "tab/tabInfoAction",
tabInfo: {
contentUrl: "example.com",
websiteUrl: "example.com",
name: "View",
entityId: "entityId",
},
},
}
I'd like to close the stage view based on a user interaction via #microsoft/teams-js. I can do that if displayed in a task module by calling teamsjs.dialog.submit() in the client code. Is there a similar way to do it in this context?

createPaymentMethod of Vue stripe element not working in Laravel, TypeError: Object(...) is not a function error occured

createPaymentMethod of Stripe not working in Laravel and Vue stripe element. Here is my code
import { Card, createToken, createPaymentMethod } from 'vue-stripe-elements-plus';
components : {
stripeCard : Card
},
methods : {
pay() {
createToken({
name : this.name,
street_line1 : this.street,
street_country : this.selectedCountry,
street_zip : this.postalCode
})
.then((data) => {
createPaymentMethod('card', {
card: data.token.card.id, // token from createToken (without any params)
billing_details: {
name: this.name, // cardholder name
email: this.email,
address: { // address fetched from algolia places
line1: this.street,
country: this.selectedCountry,
city: this.city,
postal_code: this.postalCode,
},
}
})
})
}
}
But it shows error TypeError: Object(...) is not a function
I don't get where my problem is. Any help would be appreciable. Thanks in advance.
I am using this package
https://www.npmjs.com/package/vue-stripe-elements-plus
There is no need to create both a payment method and a token. The PaymentMethods API can be thought of as a newer version of the Tokens API (1). So you can simplify your code to:
methods : {
pay() {
createPaymentMethod('card', {
billing_details: {
name: this.name, // cardholder name
email: this.email,
address: { // address fetched from algolia places
line1: this.street,
country: this.selectedCountry,
city: this.city,
postal_code: this.postalCode,
},
}
})
}
}
*Note, I removed the card: data.token.card.id line entirely. This should be unnecessary since the library you're using adds a reference to the Card element for you automatically as you can see here:
https://github.com/fromAtoB/vue-stripe-elements/blob/ede16058193e2440dfd5a7cb7af17450d52e234b/src/stripeElements.js#L68
(1) https://stripe.com/docs/payments/payment-methods

How to handle user leaving conversation

We have welcome examples using OnMembersAddedAsync method but no examples showing how to handle user leaving conversation. I tried to override OnMembersRemovedAsync but it does not seem to be invoked (at least when I use bot framework emulator).
I need to do some cleanup at the event of user leaving/left conversation.
An example or any tips would be appreciated.
Update: I'm using C# and Bot framework v4
This is going to be channel specific as it is dependent on the channel providing a feature that sends an update when the user leaves a conversation. Any other channels, you will need to research.
For Facebook, I was unable to find a scope that covers such an action. These are the available scopes which you can reference more closely here:
messages
message_deliveries
message_echoes
message_reads
messaging_account_linking
messaging_checkout_updates (beta)
messaging_game_plays
messaging_handovers
messaging_optins
messaging_payments(beta)
messaging_policy_enforcement
messaging_postbacks
messaging_pre_checkouts (beta)
messaging_referrals
standby
Web Chat, as a feature, also does not include this. However, given this is a web page, you can utilize the onbeforeunload() window function to dispatch an event. The event listener will make use of Web Chat's store to dispatch either a message or event to the bot. For the sake of clarity, I'm sending different types of data via SEND_MESSAGE and SEND_EVENT.
const store = window.WebChat.createStore( {}, ( { dispatch } ) => next => async action => {
return next( action );
};
window.addEventListener( 'sendEventActivity', ( { data } ) => {
store.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: {
text: data
}
} )
,
store.dispatch( {
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'user_event',
value: {
name: 'end_conversation',
value: 'user ended conversation'
},
text: 'The user has left the conversation.'
}
} )
} );
window.onbeforeunload = function() {
const eventSendActivity = new Event( 'sendEventActivity' );
eventSendActivity.data = 'User left conversation';
window.dispatchEvent( eventSendActivity );
}
{ type: 'message',
id: '4uPdpZhlTFfBMziBE7EmEI-f|0000004',
timestamp: 2020-01-10T18:21:26.767Z,
serviceUrl: 'https://directline.botframework.com/',
channelId: 'directline',
from: { id: 'dl_123', name: 'johndoe', role: 'user' },
conversation: { id: '4uPdpZhlTFfBMziBE7EmEI-f' },
recipient: { id: 'botberg#QaeuoeEamLg', name: 'Dungeon Runner' },
textFormat: 'plain',
locale: 'en-US',
text: 'User left conversation',
channelData:
{ clientActivityID: '15786804807910gegwkp2kai',
clientTimestamp: '2020-01-10T18:21:20.792Z' }
}
{ type: 'event',
id: '4uPdpZhlTFfBMziBE7EmEI-f|0000005',
timestamp: 2020-01-10T18:21:26.780Z,
serviceUrl: 'https://directline.botframework.com/',
channelId: 'directline',
from: { id: 'dl_123', name: 'johndoe', role: 'user' },
conversation: { id: '4uPdpZhlTFfBMziBE7EmEI-f' },
recipient: { id: 'botberg#QaeuoeEamLg', name: 'Dungeon Runner' },
locale: 'en-US',
channelData:
{ clientActivityID: '1578680480821h7kgfm9cyz',
clientTimestamp: '2020-01-10T18:21:20.821Z' },
value:
{ name: 'end_conversation', value: 'user ended conversation' },
name: 'user_event'
}
Hope of help!
Update (Aug. 6th, 2021):
As Chrome, and other browsers, disallow blocking / delaying the closing of a window during onbeforeunload(), sending an event using an event handler or listener is usually unreliable, at best. At worst, it just doesn't work.
However, there is another method that does appear work by using 'window.navigator.sendBeacon()' (providing it's supported).
sendBeacon is a low-level, simplified version of fetch that “asynchronously sends a small amount of data over HTTP to a web server”. It only sends as a POST, only takes the URL or URL + data as properties, and doesn’t wait for a response. As the docs state:
The data is sent reliably
It's sent asynchronously
It doesn't impact the loading of the next page
In testing, I have coupled it with a proactive messaging endpoint in my bot and it appears to work perfectly. (My code sample below is in JS, pulled from a project - for reference, here is the proactive messaging C# sample, available in other languages, as well).
When I navigate to another page or close the browser, sendBeacon posts the message to the endpoint creating the proactive message, which, in turn, sends an activity to the bot. When I return to the Web Chat page, the message is now visible in the chat window. Keep in mind, I also have persistence set up in Web Chat allowing me to return to a conversation previously started.
In the below image, I demo loading Web Chat, navigating to my browser’s home page, and then return – the proactive message is now visible in the chat.
(Web Chat) hosting page:
window.onbeforeunload = () => {
let body = { user: { userName: 'McUser', userId: 'abc123' } };
const headers = { type: 'application/json', 'Access-Control-Allow-Origin': '*' };
const blob = new Blob( [ JSON.stringify( body ) ], headers )
navigator.sendBeacon( 'http://localhost:3978/api/notify', blob )
}
Bot's proactive messaging endpoint:
server.post('/api/notify', async (req, res) => {
const userName = req.body.user.userName;
const userId = req.body.user.userId;
for (const conversationReference of Object.values(conversationReferences)) {
await adapter.continueConversation(conversationReference, async (turnContext) => {
await turnContext.sendActivity(`${ userName } (userId: ${ userId }) exited chat.`);
});
}
});

Get URL Referer [BotFramework-WebChat]

I'm using a directline inside my website and I was wondering if there is anyway to get the URL of the website inside my bot code. Previously, in v3, I was initializing the chat with:
BotChat.App({
directLine: { secret: "{directline_secret}" },
user: { id: 'You', referrer: window.location.href},
bot: { id: '{bot_id}' },
resize: 'detect'
}, document.getElementById("bot"));
and I was able to get the referrer with this line of code activity.From.Properties["referrer"].ToString(), but in v4 I can't find a way to get the referrer inside the bot.
Can someone help me?
Thanks in advance.
In v4 the value is part of the turnContext.activity (in Node) or turnContext.Activity (in C#) object. Passing the url value as you have done in your question (i.e., as part of the user object) you would access it like so (Node example):
async onTurn(turnContext) {
if (
turnContext.activity.type === "event" && turnContext.activity.name === "eventName"
) {
this.userProfile.location = turnContext.activity.from.referrer;
await console.log(this.userProfile.location);
}
I included a name as well as specified a type in my BotChat.App post to match this event to in the turnContext.activity:
function testMethod(someValue) {
botConnection
.postActivity({
from: { id: 'me', referrer: window.location.href },
name: 'eventName',
type: 'event',
value: someValue
})
.subscribe(function (id) {
console.log('"eventName" sent');
});
};
In this example, the method is tied to a button being pressed on the page.
Hope of help!

Resources