Web Apple sign in with nuxt js - javascript

I am using sign-in with apple using the following link in Nuxt app:
https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js
So the problem is if I don't use usePopup flag and use the server link with redirectURI then apple does makes a post request to redirectURI then request completes successfully but I can't get the data from the server.
and If I use the usePopup: true then I have to do the post request to the server then it fails (apple response: invalid request) I am using expressjs as a server.
AppleID.auth.init({
clientId: "my-client-id", // This is the service ID we created.
scope: "name email", // To tell apple we want the user name and emails fields in the response it sends us.
redirectURI: "https://9b29-103-213-105-122.in.ngrok.io/login", // As registered along with our service ID
state: "origin:web", // Any string of your choice that you may use for some logic. It's optional and you may omit it.
usePopup: true, // Important if we want to capture the data apple sends on the client side.
});
then after the response from the following code I make the post request:
this.appleResponse = await AppleID.auth.signIn();

Related

How to Resend HTTP Request With 2FA Code?

I'm following Coinbase's guide on sending bitcoin to someone via the API. Coinbase requires user to enter 2FA code when sendMoney() is called. Then I somehow need to put this code in the HTTP header for sendMoney() to successfully execute. But I'm not sure how to make this work with Coinbase's API (sendMoney() has no parameter for setting the HTTP header). I think I could manually POST to URL instead of calling sendMoney(), but I'm not sure what parameters to pass.
function getBalance(client, res){
client.getAccount('BTC', function(err,account){
// SENDING MONEY REQUIRES 2FA
account.sendMoney({
'to': '3MLCRpMDXC3AFBsaSLNimWfJFvsMVBq4Ac',
'amount': '0.0000018',
'currency': 'BTC'
}, function(err, txt){
res.render('authPurchase'); // RENDER INPUT FIELD FOR USER TO ENTER 2FA CODE
});
});
} // how do I 'replay' the above sendMoney request with the 2FA code in the http header?
Coinbase Docs provide this walkthrough, but sadly no example pertaining to making a POST request with 2FA authorization.
1. User is sending funds and the app calls POST api.coinbase.com/v2/accounts/primary/transactions
2. Server responds with 402 and sends the user a 2FA token via SMS if he doesn’t have Authy installed
3. App re-plays the request from step 1 with exactly same parameters and the 2FA token in the CB-2FA-TOKEN header (HOW????)
4. Transaction is sent and 201 CREATED status code is returned
I figured it out!
module.exports.replaySendMoney = function replaySendMoney(smsCode){
// in the future access token will be stored and retrieved from database
var Client = require('coinbase').Client;
let accessToken = '2aac7a723eb58bfaf13a9073ac7b6982dca072f14fa0abbc766e9ed9f60be596';
let refreshToken = '17a609e13c7608ecd499a1be502da19a7095ccf2d5fe9f40fca2b87501f7c233';
var client = new Client({'accessToken': accessToken, 'refreshToken': refreshToken});
client.getAccount('BTC', function(err,acct){
// REQUIRES 2FA
acct.sendMoney({
'to': '3MLCRpMDoC3AFBsbSLNimWfJFvsMVBq4Ac',
'amount': '0.0000018',
'currency': 'BTC',
'two_factor_token' : smsCode
}, function(err, txt){
console.log(err);
console.log(txt);
res.render('authPurchase', {});
});
});
}

Stripe API Pass Dynamic Data

Is there a way to pass dynamic data to the Stripe API? I'm using the example found here: https://stripe.com/docs/payments/checkout/client
I'd like to be able to pass a token along with the purchase in order to link an account with that payment. After the client side sends the payment to the API, my backend would receive the details of the payment, including the token to link it to an account created before this. I would add it as a param to to the successful redirect, but if they close the window early then the accounts will not be linked. I set up my product using the dashboard.
I tried using metadata and description as a part of the line item, but it keeps saying "Invalid stripe.redirectToCheckout parameter: lineItems.0.description is not an accepted parameter."
let token;
stripe.redirectToCheckout({
lineItems: [{
price: 'boop', // Replace with the ID of your price
quantity: 1,
description: token
}],
mode: 'payment',
successUrl: 'http://boop.com',
cancelUrl: 'http://boop.com',
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
Thank you!
In order to pass metadata and other fields in Checkout, you need to use the Server + Client integration path instead of the client-only integration.
You can achieve what I wanted through the Server + Client integration by using the client_reference_id when creating a session.

Auth0 email confirmation, how to handle registration gracefuly

I am using auth0.
My app requires users to confirm their email.
When a user registers, he receives this alert:
Error: unauthorized. Check the console for further details.
This is because the user has not yet verified his email.
How do I "catch" this event / alert in order to redirect the user to a view of my choice?
Thank you for your help
There is a couple of different parts to this.
1). have you enabled the email verified rule? (it is a template available from Auth0 dashboard -
function forceEmailVerification(user, context, callback) {
console.log("force-email-verification");
if(context.connection !== "MyDB") {
return callback(null, user, context);
}
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
That effectively raises an exception in the Rules pipeline if email not verified. It will return the error to your application on the callbackUrl you provide as two query params - error and error_description. It is then up to you how you handle this - Here is a sample Node.js application I wrote specifically to illustrate how this works - In the sample, i am using some express middleware to check for the error and error_description and forward to a Custom controller / view if detected.
2). Only if needed, you can also explicitly trigger an email verification email. It is a POST request to https://{{tenant}}.auth0.com/api/users/{{user_id}}/send_verification_email
endpoint, passing an Authorization Bearer header with an Auth0 APIv1 token (and empty body). The token can be obtained by making a POST request to https://{{tenant}}.auth0.com/oauth/token endpoint passing body of the form:
{
"client_id": "{GLOBAL CLIENT ID}",
"client_secret": "{GLOBAL CLIENT SECRET}",
"grant_type": "client_credentials"
}
You can get the global client id and client secret under account settings -> advanced from Auth0 dashboard. Please do NOT store any secrets on SPA apps etc - using this endpoint should only be done from Client Confidential / Trusted applications (e.g traditional MVC webapp you own).
Hope this helps. Please leave comments if anything unclear.

Skype Web SDK - Maintain a user session

I am using Skype Web SDK to get a user's contact list in the following manner.
Skype.initialize({
apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255',
}, function (api) {
var Application = api.application;
var client = new Application();
client.signInManager.signIn({
username: sip,
password: pwd
})
This works fine when I provide the username(sip) and password. However, when I reload the page, I have to provide the credentials again because the app re-initializes. Is there a way to maintain the user's sessions for a while after the initial login so that the page refreshes wouldn't need ask for credentials again?
I have looked through the samples and docuementation that Microsoft has and couldn't find a way. I've also tried to store the client object in the localStorage after the initialization and sign in, but when I tried to reuse the object from localStorage to get the contact list, it did not work.
http://officedev.github.io/skype-docs/Skype/WebSDK/model/api/interfaces/jcafe.signinmanager.html#signin last example explains that you can store oauth token and use it as unexpired token.
To connect to an existing app's event channel, specify id of that app:
sm.signIn({
username: "user1#company.com",
password: "password1",
id: "273867-234235-45346345634-345"
});
To sign in to Skype for Business Online using OAuth while handling the
logic of retrieving OAuth tokens yourself:
sm.signIn({
client_id: '123-456',
origins: [ 'https://webdir.online.lync.com/AutoDiscover/AutoDiscoverservice.svc/root' ],
cors: true,
get_oauth_token: function(resource) {
// Return a valid unexpired token for the specified resource if you already have one.
// Else, return a promise and resolve it once you have obtained a token.
return 'Bearer eyJ0e...';
}
});

Unable to query Google Search Console API using a Service Account

I need to retrieve some data from Google Search Console (Webmaster Tools) using a service account.
So far I've been able to retrieve an access_token for the service account which I need to append to the url of the request. The problem is that I can't find a way to do so, this is the code i'm using:
function retrieveSearchesByQuery(token)
{
gapi.client.webmasters.searchanalytics.query(
{
'access_token': token,
'siteUrl': 'http://www.WEBSITE.com',
'fields': 'responseAggregationType,rows',
'resource': {
'startDate': formatDate(cSDate),
'endDate': formatDate(cEDate),
'dimensions': [
'date'
]
}
})
.then(function(response) {
console.log(response);
})
.then(null, function(err) {
console.log(err);
});
}
This is the url called by the function:
https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json"
Instead it should be something like this:
https://content.googleapis.com/webmasters/v3/sites/http%3A%2F%2Fwww.WEBSITE.com/searchAnalytics/query?fields=responseAggregationType%2Crows&alt=json&access_token=XXX"
The gapi.client.webmasters.searchanalytics.query doesn't recognize 'access_token' as a valid key thus it doesn't append it to the url and that's why I get a 401 Unauthorized as response.
If I use 'key' instead of 'access_token' the parameter gets appended to the url but 'key' is used for OAuth2 authentication so the service account token I pass is not valid.
Does anyone have a solution or a workaround for this?
If your application requests private data, the request must be authorized by an authenticated user who has access to that data. As specified in the documentation of the Search Console API, your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported.
If you application is correctly configured, when using the Google API, an authenticated request looks exactly like an unauthenticated request. As stated in the documentation, if the application has received an OAuth 2.0 token, the JavaScript client library includes it in the request automatically.
You're mentioning that you have retrieved an access_token, if correctly received, the API client will automatically send this token for you, you don't have to append it yourself.
A very basic workflow to authenticate and once authenticated, send a request would looks like the following code. The Search Console API can use the following scopes: https://www.googleapis.com/auth/webmasters and https://www.googleapis.com/auth/webmasters.readonly.
var clientId = 'YOUR CLIENT ID';
var apiKey = 'YOUR API KEY';
var scopes = 'https://www.googleapis.com/auth/webmasters';
function auth() {
// Set the API key.
gapi.client.setApiKey(apiKey);
// Start the auth process using our client ID & the required scopes.
gapi.auth2.init({
client_id: clientId,
scope: scopes
})
.then(function () {
// We're authenticated, let's go...
// Load the webmasters API, then query the API
gapi.client.load('webmasters', 'v3')
.then(retrieveSearchesByQuery);
});
}
// Load the API client and auth library
gapi.load('client:auth2', auth);
At this point, your retrieveSearchesByQuery function will need to be modified since it doesn't need to get a token by argument anymore in order to pass it in the query. The JavaScript client library should include it in the request automatically.
You can also use the API Explorer to check what parameters are supported for a specific query and check the associated request.
If you need to use an externally generated access token, which should be the case with a Service Account, you need to use the gapi.auth.setToken method to sets the OAuth 2.0 token object yourself for the application:
gapi.auth.setToken(token_Object);

Categories