In VueJS, how to access object returned by external api - express

I have added the hcaptcha widget to my login component using this package: https://github.com/hCaptcha/vue-hcaptcha. The challenge works as expected on the front end.
The response object as viewed in the network tab includes a token and looks like this:
expiration: 120
generated_pass_UUID: "P0_eyJ0eXAiOiJKV1QiLCJhbG...O9U"
pass: true
My question is how to pass that token with my email and password when I submit the login form.
Normally, I am using axios to make an explicit api call and I can define a variable like:
let response = axios.get('/whater_api')
and then use response.data to access whatever comes back. But I can't see how to do that here.

Have you tried the #verify="onVerify" event? it seems the result is emitted on that event, try to add methods onVerify on your vue instance like below:
methods: {
onVerify: function(e) {
console.log(e);
}
}
if it does return the response, you can make an object for the token, your email and password and the rest is just as usual.

Related

Facebook Oauth2 cannot manually open the consent dialog Vuejs

I am trying to "Manually Build a Login Flow" according to these docs here: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
The idea is that i want to generate an one time authorization code, then send it to my back end so it can generate there the access token and then get the user data.
The docs above nicely have sections like "Invoking the Login Dialog and Setting the Redirect URL" and "Exchanging Code for an Access Token" along with the respective endpoints to hit, which is exactly what i want. So I started implementing the dialog invocation on the front end which is a vuejs app, so i can generate the authorization code to send it to my server.
Here is the code:
<script>
import axios from "axios";
export default {
methods: {
facebookAuth(){
axios.get('https://www.facebook.com/v4.0/dialog/oauth?client_id=MY_CLIENT_ID&redirect_uri=http://localhost:3000&state="I AM A STRING"', {
headers:{
'Access-Control-Allow-Origin': '*',
}
})
.then(res=>{
console.log(res);
})
}
}
};
</script>
The first issue here is that i get CORS error, even with my anticors chrome extension open. So i pass it to this proxy https://cors-anywhere.herokuapp.com/
and I manage to make it work, but no consent dialog opens. I just get a http response with an html page code as a response body.

Reset token in vue resource - Vue2

In the main.js file i have set the vue resource to use auth headers with every requests:
Vue.use( VueResource )
let auth = validToken()
if( auth ) {
Vue.http.interceptors.push( ( request, next ) => {
request.headers.set( 'Authorization', auth.token )
request.headers.set( 'Accept', 'application/json' )
next()
} )
}
And in the logout, i am trying to delete the header this way,
resetVueRsr: () => {
this.$http.headers.common['Authorization'] = null
}
And when a user log in, then resetting the new token to the global Vue resource like this,
this.$http.headers.common['Authorization'] = res.body.token
But once a new user is logging in the site, the vue resource still sending previous token with each request. What i am missing here?
I checked the source, and it looks like all defined interceptors are added in some internal array, and then used for requests.
According to your code sample, you obtain an object with initial token somehow and then pass it inside your arrow function, so JS creates a closure for this to make this object available inside the function, and I think a lifetime of this closure is equal to a lifetime of your app. I assume that you have a sort of SPA.
Also from the source it looks like interceptors are not related to common headers, so your way of deleting and resetting won't change your interceptor.

How to return error from Auth0 hooks

If I want to return custom error from Rules I simply do callback(new UnauthorizedError('Custom error message here')) but how do I do the same thing with Hooks?
callback('error message');
callback(new Error('error message'));
Those didn't worked and "UnauthorizedError" is undefined in Hooks. Whatever I do, on front-end side I always get "WE'RE SORRY, SOMETHING WENT WRONG WHEN ATTEMPTING TO SIGN UP." and when I inspect result of requested I see that there is no difference, each time "InternalExtensibilityError" comes.
Why do I want to return error from Hooks? I run extra validation for sign-up there.
Now it is possible to send custom error messages in hooks.
I extracted below code snippet from Auth0's documentation on hooks.
module.exports = function (user, context, cb) {
const isUserDenied = ...; // determine if a user should be allowed to register
if (isUserDenied) {
const LOCALIZED_MESSAGES = {
en: 'You are not allowed to register.',
es: 'No tienes permitido registrarte.'
};
const localizedMessage = LOCALIZED_MESSAGES[context.renderLanguage] || LOCALIZED_MESSAGES['en'];
return cb(new PreUserRegistrationError('Denied user registration in Pre-User Registration Hook', localizedMessage));
}
};
Here is the original link (https://auth0.com/docs/hooks/extensibility-points/pre-user-registration)
At the moment, returning custom errors from hooks to the top-level API, /dbconnections/signup in this case is not possible in Auth0. This is documented in the bottom of this page.
Note that Hooks is still in Beta, and this enhancement request is one of the most asked for features and it is currently in our backlog. We cannot give an ETA for this yet. You can submit your feedback to the Product here.

Initial authentication check in ReactJS and Redux

Background: I have an app that is showing a list of movies, but what I want to do is to show the list only for users who are authorized (by checking token stored on the local-storage).
so the flow I want to achieve is:
user enters the app main page
check if has token in local storage
if yes check if it is authorized
if authorized = show list, else don't show
so what I do right now is in my main (wrapper) component right after I create my store:
const store = configureStore();
var token = localStorage.get(authConstants.LOCAL_STORAGE_TOKEN_KEY);
if(token){
store.dispatch(actions.checkInitialAuth(token));
}
checkInitialAuth actions is:
export function checkInitialAuth(token){
return dispatch => {
dispatch(requestLogin());
return fetch(authConstants.API_USER_DETAILS, {headers: { 'Authorization' : `Bearer ${token}`}})
.then(function(response){
if(!response.ok){
throw Error(response.statusText);
}
return response.json();
})
.then(function(user){
localStorage.set(authConstants.LOCAL_STORAGE_TOKEN_KEY, token);
dispatch(receiveLogin(user)); // <==========
dispatch(setTopMovies()); // <==========
})
.catch(function(err){
// TODO: handle errors
console.log(err);
});
}
}
so the question is, is it the right place to invoke the initial auth check right after the creating store and right before the element creation?
and now if I have to invoke more actions only if the user is authorized do I have to invoke them in the then inside the checkInitialAuth action? is it the right place to make all the action dispatch calls?
and last one, when the auth is wrong (I changed manually the token to be wrong on the local storage) the console.log(err) is logging as expected but I have also this annoying 401 error in the console, can I somehow avoid it?
thanks a lot!
is it the right place to invoke the initial auth check right after the creating store and right before the element creation?
Yes. Usually this is where all the initialization happens before store is passed to Provider.
is it the right place to make all the action dispatch calls?
This depends a lot on your application logic. You component can check if a user is authenticated itself to display the correct content for 'topMovies'. But nothing stops you from dispatch more actions here.
but I have also this annoying 401 error in the console, can I somehow avoid it?
It is the network request error. It is the response from the server your fecth is contacting. You can hide the error by change your Chrome Dev console filter if you really want to hide them (but why?).

How to stop page content load until authenticated using Firebase and Polymer

I am starting with Polymer and Firebase and have implemented the Google OAuth authentication.
I have notice the page loads before authentication and if you click back you can get to the page without authorization, albeit that you are not able to use the firebase api and therefore the page is not usable.
My issue is that I do not want my javascript loaded until authenticated.
How could this be done.
Many thanks
It depends if your using firebase or their polymer wrapper, polymerfire.
Create a document for all the imports that you want to be conditionally loaded
// user-scripts-lazy.html
<link rel="import" href="user-script-one.html">
<script src="script.js"></script>
// etc
Using Polymerfire
In the element that hosts <firebase-auth> create a observer and you'll expose some variables from firebase-auth.
<firebase-auth
user="{{user}}"
status-known="{{statusKnown}}"></firebase-auth>
In the observer, watch the user element and the status known
statusKnown: When true, login status can be determined by checking user property
user: The currently-authenticated user with user-related metadata. See the firebase.User documentation for the spec.
observers:[
'_userStateKnown(user, statusKnown)'
]
_userStateKnown: function(user, status) {
if(status && user) {
// The status is known and the user has logged in
// so load the files here - using the lazy load method
var resolvedPageUrl = this.resolveUrl('user-scripts-lazy.html.html');
this.importHref(resolvedPageUrl, null, this.onError, true);
}
}
To get the state without using polymerfire you can use onAuthStateChange
properties: {
user: {
type: Object,
value: null // important to initialise to null
}
}
..
ready: function() {
firebase.auth().onAuthStateChagned(function(user) {
if(user)
this.set('user', user); // when a user is logged in set their firebase user variable to ser
else
this.set('user', false); // when no user is logged in set user to false
}.bind(this)); // bind the Polymer scope to the onAuthStateChanged function
}
// set an observer in the element
observers: [
'_userChanged(user)'
],
_userChanged: function(user) {
if(user === null) {
// authStatus is false, the authStateChagned function hasn't returned yet. Do nothing
return;
}
if(user) {
// user has been signed in
// lazy load the same as before
} else {
// no user is signed in
}
}
I haven't tested the code while writing it here, but i've implemented the same thing various times.
There are a couple of options.
Put content you don't want loaded behind a dom-if template with "[[user]]" as its driver. This could include your firebase element, so the database isn't even considered until after log on.
Put a modal dialog box up if the user is not logged on. I do this with a custom session element . Whilst the overlay is showing then the rest of the page is unresponsive to anything.
If it is simply an aesthetic issue of removing the non-logged-in page from view, could you either hide the page (or display some kind of overlay) while the user isn't authenticated?
I currently have this in an current project for some elements: hidden$="{{!user}}"
I have identified the solution for my purpose ...
Add storage role based authorization (see is there a way to authenticate user role in firebase storage rules?)
This does have a limitation currently of hard coded uid's
In the page, request storage resource and if successful include it in the dom (i.e. add script element with src pointing to storage url)
Call javascript as normal