Vue.js 2 and auth0 authentication resulting with 'nonce' - callback

I am trying to implement auth0 in my Vue.js 2 application.
I followed this link to implement the auth0 lock:
https://github.com/auth0-samples/auth0-vue-samples/tree/master/01-Login
This is my application in Login.vue:
HTML:
<div v-show="authenticated">
<button #click="logout()">Logout</button>
</div>
<div v-show="!authenticated">
<button #click="login()">Login</button>
</div>
Javascript:
function checkAuth() {
return !!localStorage.getItem('id_token');
}
export default {
name: 'login',
data() {
return {
localStorage,
authenticated: false,
secretThing: '',
lock: new Auth0Lock('clientId', 'domain')
}
},
events: {
'logout': function() {
this.logout();
}
},
mounted() {
console.log('mounted');
var self = this;
Vue.nextTick(function() {
self.authenticated = checkAuth();
self.lock.on('authenticated', (authResult) => {
console.log(authResult);
console.log('authenticated');
localStorage.setItem('id_token', authResult.idToken);
self.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
console.log(error);
return;
} else {
console.log('no error');
}
localStorage.setItem('profile', JSON.stringify(profile));
self.authenticated = true;
});
});
self.lock.on('authorization_error', (error) => {
console.log(error);
});
});
},
methods: {
login() {
this.lock.show();
},
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.authenticated = false;
}
}
}
I am pretty sure that it already worked, but suddenly it doesnt work anymore.
My callbacks defined in auth0: http://127.0.0.1:8080/#/backend/login
That is also how I open the login in my browser.
When I login it I only get this in my localStorage:
Key: com.auth0.auth.14BK0_jsJtUZMxjiy~3HBYNg27H4Xyp
Value: {"nonce":"eKGLcD14uEduBS-3MUIQdupDrRWLkKuv"}
I also get redirected to http://127.0.0.1:8080/#/ so I do not see any network requests.
Does someone know where the problem is?
I ran the demo from auth0 with my Domain/Client and it worked without any problem.
Obviously I do not get any errors back in my console.

Atfer research I finally found the answer to my problem.
The reason, why it is not working is because my vue-router does not use the HTML5 History Mode (http://router.vuejs.org/en/essentials/history-mode.html).
To have it working without the history mode, I had to disable the redirect in my lock options and to disable auto parsing the hash:
lock: new Auth0Lock(
'clientId',
'domain', {
auth: {
autoParseHash: false,
redirect: false
}
}
)
Reference: https://github.com/auth0/lock

Related

Braintree PCI compliance issue

I have been continuously getting an email by brain tree on PCI Compliance regards and need confirmation on following two things which have been asked.
What is the Braintree payment integration method on our website? (Hint: It’s one of these)
Drop in UI or hosted field
Braintree SDK Custom integration
Following is the javascript code we've used . I went through the Braintree site on this regards but couldn't conclude upon this.
Additional Notes : We've made some changes on braintree vendor file.
var subscribed_user = "1";
$('#cc').on('click', function (e) {
$('#cc-info').show().attr('aria-hidden', true).css('visibility', 'visible');
});
var button = document.querySelector('#paypal-button');
var button1 = document.querySelector('#card-button');
var form = document.querySelector('#checkout-form');
var authorization = 'AuthHeaderxxxxxxxx=';
// Create a client.
braintree.client.create({
authorization: authorization
}, function (clientErr, clientInstance) {
// Stop if there was a problem creating the client.
// This could happen if there is a network error or if the authorization
// is invalid.
if (clientErr) {
console.error('Error creating client:', clientErr);
return;
}
/* Braintree - Hosted Fields component */
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '10pt',
'color': '#e3e3e3 !important; ',
'border-radius': '0px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111',
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) { /*Handle error in Hosted Fields creation*/
return;
}
button1.addEventListener('click', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) { /* Handle error in Hosted Fields tokenization*/
document.getElementById('invalid-field-error').style.display = 'inline';
return;
}
/* Put `payload.nonce` into the `payment-method-nonce` input, and thensubmit the form. Alternatively, you could send the nonce to your serverwith AJAX.*/
/* document.querySelector('form#bt-hsf-checkout-form input[name="payment_method_nonce"]').value = payload.nonce;*/
document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
form.submit();
button1.setAttribute('disabled', 'disabled');
});
}, false);
});
// Create a PayPal component.
braintree.paypal.create({
client: clientInstance,
paypal: true
}, function (paypalErr, paypalInstance) {
// Stop if there was a problem creating PayPal.
// This could happen if there was a network error or if it's incorrectly
// configured.
if (paypalErr) {
console.error('Error creating PayPal:', paypalErr);
return;
}
if ($('select#paypal-subs-selector option:selected').val() == '') {
button.setAttribute('disabled', 'disabled');
}
$('select#paypal-subs-selector').change(function () {
if ($('select#paypal-subs-selector option:selected').val() == '') {
button.setAttribute('disabled', 'disabled');
} else {
// Enable the button.
button.removeAttribute('disabled');
}
});
button.addEventListener('click', function () {
if(subscribed_user) {
// Popup Error for changing subscription.
swal({
html: true,
title: "",
text: "You are cancelling in the middle of subscription.<br/>If you do so you will not be refunded remaining days of your subscription.",
confirmButtonColor: '#605ca8',
confirmButtonText: 'Yes',
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Proceed !",
closeOnConfirm: true
}, function (isConfirm) {
if (isConfirm) {
show_payment_methods(paypalInstance);
}
});
} else{
show_payment_methods(paypalInstance);
}
}, false);
});
});
Any help would be highly appreciated.
Your code says Braintree - Hosted Field component And you don’t use anything like this which I found by searching “Braintree api”. I think you’re safe to say you use hosted fields.

Redirect to requested page after login using vue-router

In my application some routes are just accessible for authenticated users.When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redirected to the login component.
If the user logs in successfully, I would like to redirect him to the URL he requested before he had to log in. However, there also should be a default route, in case the user did not request another URL before he logged in.
How can I achieve this using vue-router?
My code without redirect after login
router.beforeEach(
(to, from, next) => {
if(to.matched.some(record => record.meta.forVisitors)) {
next()
} else if(to.matched.some(record => record.meta.forAuth)) {
if(!Vue.auth.isAuthenticated()) {
next({
path: '/login'
// Redirect to original path if specified
})
} else {
next()
}
} else {
next()
}
}
)
My login function in my login component
login() {
var data = {
client_id: 2,
client_secret: '**************',
grant_type: 'password',
username: this.email,
password: this.password
}
// send data
this.$http.post('oauth/token', data)
.then(response => {
// authenticate the user
this.$auth.setToken(response.body.access_token,
response.body.expires_in + Date.now())
// redirect to route after successful login
this.$router.push('/')
})
}
This can be achieved by adding the redirect path in the route as a query parameter.
Then when you login, you have to check if the redirect parameter is set:
if IS set redirect to the path found in param
if is NOT set you can fallback on root.
Put an action to your link for example:
onLinkClicked() {
if(!isAuthenticated) {
// If not authenticated, add a path where to redirect after login.
this.$router.push({ name: 'login', query: { redirect: '/path' } });
}
}
The login submit action:
submitForm() {
AuthService.login(this.credentials)
.then(() => this.$router.push(this.$route.query.redirect || '/'))
.catch(error => { /*handle errors*/ })
}
I know this is old but it's the first result in google and for those of you that just want it given to you this is what you add to your two files. In my case I am using firebase for auth.
Router
The key line here is const loginpath = window.location.pathname; where I get the relative path of their first visit and then the next line next({ name: 'Login', query: { from: loginpath } }); I pass as a query in the redirect.
router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
const loginpath = window.location.pathname;
next({ name: 'Login', query: { from: loginpath } });
} else if (!requiresAuth && currentUser) next('menu');
else next();
});
Login Page
No magic here you'll just notice my action upon the user being authenticated this.$router.replace(this.$route.query.from); it sends them to the query url we generated earlier.
signIn() {
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
(user) => {
this.$router.replace(this.$route.query.from);
},
(err) => {
this.loginerr = err.message;
},
);
},
I am going to be fleshing out this logic in more detail but it works as is. I hope this helps those that come across this page.
Following on from Matt C's answer, this is probably the simplest solution but there were a few issues with that post, so I thought it best to write a complete solution.
The destination route can be stored in the browser's session storage and retrieved after authentication. The benefit of using session storage over using local storage in this case is that the data doesn't linger after a broswer session is ended.
In the router's beforeEach hook set the destination path in session storage so that it can be retrieved after authentication. This works also if you are redirected via a third party auth provider (Google, Facebook etc).
router.js
// If user is not authenticated, before redirecting to login in beforeEach
sessionStorage.setItem('redirectPath', to.path)
So a fuller example might look something like this. I'm using Firebase here but if you're not you can modify it for your purposes:
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(x => x.meta.requiresAuth);
const currentUser = firebase.auth().currentUser;
if (requiresAuth && !currentUser) {
sessionStorage.setItem('redirectPath', to.path);
next('/login');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
login.vue
In your login method, after authetication you will have a line of code that will send the user to a different route. This line will now read the value from session storage. Afterwards we will delete the item from session storage so that it is not accidently used in future (if you the user went directly to the login page on next auth for instance).
this.$router.replace(sessionStorage.getItem('redirectPath') || '/defaultpath');
sessionStorage.removeItem('redirectPath');
A fuller example might look like this:
export default Vue.extend({
name: 'Login',
data() {
return {
loginForm: {
email: '',
password: ''
}
}
},
methods: {
login() {
auth.signInWithEmailAndPassword(this.loginForm.email, this.loginForm.password).then(user => {
//Go to '/defaultpath' if no redirectPath value is set
this.$router.replace(sessionStorage.getItem('redirectPath') || '/defaultpath');
//Cleanup redirectPath
sessionStorage.removeItem('redirectPath');
}).catch(err => {
console.log(err);
});
},
},
});
If route guard is setup as below
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!loggedIn) {
next({
path: "/login",
query: { redirect: to.fullPath }
});
} else {
next();
}
} else {
next();
}
});
The redirect query can be extracted and used upon successful login
let searchParams = new URLSearchParams(window.location.search);
if (searchParams.has("redirect")) {
this.$router.push({ path: `${searchParams.get("redirect")}` });
} else this.$router.push({ path: "/dashboard" });
Another quick and dirty option would be to use local storage like the following:
In your beforeEach, before you redirect to login place the following line of code to save the initial requested path to local storage:
router.js
// If user is not authenticated, before redirecting to login
localStorage.setItem('pathToLoadAfterLogin', to.path)
Then in your login component, upon succesful login, you can redirect to the localStorage variable that you previously created:
login.vue
// If user login is successful, route them to what they previously requested or some default route this.$router.push(localStorage.getItem('pathToLoadAfterLogin') || 'somedefaultroute');
Much easier with this library
and login function is
let redirect = this.$auth.redirect();
this.$auth
.login({
data: this.model,
rememberMe: true,
redirect: { name: redirect ? redirect.from.name : "homepage", query: redirect.from.query },
fetchUser: true
})
This will help you #Schwesi .
Router.beforeEach(
(to, from, next) => {
if (to.matched.some(record => record.meta.forVisitors)) {
if (Vue.auth.isAuthenticated()) {
next({
path: '/feed'
})
} else
next()
}
else if (to.matched.some(record => record.meta.forAuth)) {
if (!Vue.auth.isAuthenticated()) {
next({
path: '/login'
})
} else
next()
} else
next()
}
);
This worked for me.
this.axios.post('your api link', {
token: this.token,
})
.then(() => this.$router.push(this.$route.query.redirect || '/dashboard'))
In Vue2 if someone has a routing and guarded some groups of routes. I solved this way.
function webGuard(to, from, next) {
if (!store.getters["auth/authenticated"]) {
sessionStorage.setItem("redirect", to); // hear I save the to
next("/login");
} else {
next();
}
}
Vue.use(VueRouter);
export default new VueRouter({
mode: "history",
hash: false,
routes: [
{
path: "/",
component: Home,
children: [
{ path: "", redirect: "home" },
...
...
],
beforeEnter: webGuard
},]
when you login
this.signIn({ email: test#gmail.com, password: 123 })
.then((res) => {
var redirectPath = sessionStorage.getItem('redirect');
sessionStorage.removeItem('redirect');
this.$router.push(redirectPath?redirectPath:"/dashboard");
})

Facebook and Firebase Authentication in Angular2

I found some troubles with firebase and facebook authentication using Angular2. I´ve created this method to verify with the console if the user is logged in but I think this isn´t the correct way to do this because the console is not reporting me the correct values.
So here is my code:
export class AppComponent {
user: Observable<firebase.User>;
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
}
ngOnInit() {
this.user = this.afAuth.authState;
if (this.user)
console.log('NOT LOGGED');
else
console.log('LOGGED IN', this.afAuth.authState);
}
login() {
this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then((res) => console.log(res));
}
logout() {
this.afAuth.auth.signOut();
}
}
How can I use the user observable in a better way?
Since authState returns an observable you need to subscribe to get the value:
ngOnInit() {
this.afAuth.authState.subscribe(auth => {
if (auth) {
console.log('LOGGED IN', auth);
} else {
console.log('NOT LOGGED');
}
}

How to always check if the Location service is enabled in Ionic 2?

I am trying to figure out how to always check if the location service is enabled. By always I mean like a real-time checker. What I have now is only in one view. I am checking when the user signs in - if the location service is enabled, he signs in. However, if it's unenabled then an Alert dialog appears:
This is my function that checks if it's enabled:
checkLocation() {
this.diagnostic.isLocationEnabled().then(
(isAvailable) => {
console.log('Is available? ' + isAvailable);
if (isAvailable) {
this.navCtrl.setRoot(UserTypePage);
} else {
alert('Please turn on the location service');
if (this.autoLogin) {
this.autoLogin();
}
}
}).catch((e) => {
console.log(e);
alert(JSON.stringify(e));
});
}
I call this function when a user tries to sign in.
Example with Facebook sign in:
facebookLogin(): void {
this.global = ShareService.getInstance();
this.subscriptions.push(this.authProvider.loginWithFacebook().subscribe((user) => {
this.loading.dismiss().then(() => {
this.global.setUserName(user.displayName);
this.global.setProfilePicture(user.photoURL);
this.global.setUserId(this.authProvider.currentUserId);
this.tokenstore();
this.checkLocation(); //HERE
})
}, error => {
this.loading.dismiss().then(() => {
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: "Ok",
role: 'cancel'
}
]
});
alert.present();
});
}, (err) => {
console.error("error: " + JSON.stringify(err));
}));
this.loading = this.loadingCtrl.create({
content: 'Signing in...'
});
this.loading.present();
}
I want this function to work in the whole application not just in the login view. How do I do that?
This is a classic scenario where Angular Dependency Injection will help you to reuse an existing method across components/views.
You can create a LocationCommonService in your application and define the method to check if Location service is enabled.
Now inject LocationCommonService in all the components where there is a need to call the required function.

Page need to be refresh before Facebook Login works

I am facing this issue in my application where facebook login is used.
ISSUE
Users need to press F5/refresh the page before facebook login prompt comes up. otherwise it doesn't come up and nothing happens on button click.
Here is the button tag for Facebook Login, which calls "Login()" method {angularJS is used}.
<a href="#" class="btn btn-default btn-lg" ng-click="login()"
ng-disabled="loginStatus.status == 'connected'"> <i class="fa fa-facebook fa-fw"></i> <span
class="network-name">Login Using Facebook</span></a>
AngularJS Code which gets called:
app.controller('DemoCtrl', ['$scope', 'ezfb', '$window', 'PFactory', '$location', function ($scope, ezfb, $window, PFactory, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function () {
ezfb.login(function (res) {
/**
* no manual $scope.$apply, I got that handled
*/
if (res.authResponse) {
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes,user_status,user_about_me,user_birthday,user_hometown,user_location,user_relationships,user_relationship_details,user_work_history'});
$location.path('/view9');
};
$scope.logout = function () {
ezfb.logout(function () {
updateLoginStatus(updateApiMe);
});
};
$scope.share = function () {
ezfb.ui(
{
method: 'feed',
name: 'angular-easyfb API demo',
picture: 'http://plnkr.co/img/plunker.png',
link: 'http://plnkr.co/edit/qclqht?p=preview',
description: 'angular-easyfb is an AngularJS module wrapping Facebook SDK.' +
' Facebook integration in AngularJS made easy!' +
' Please try it and feel free to give feedbacks.'
},
null
);
};
var autoToJSON = ['loginStatus', 'apiMe'];
angular.forEach(autoToJSON, function (varName) {
$scope.$watch(varName, function (val) {
$scope[varName + 'JSON'] = JSON.stringify(val, null, 2);
}, true);
});
function updateLoginStatus(more) {
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
});
}
function updateApiMe() {
ezfb.api('/me', function (res) {
$scope.apiMe = res;
});
}
}]);
Please help resolving it!
Thanks in Advance
Add true parameter after getLoginStatus callback function to force refreshing cache.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
}, true);