How to check if user is logged from the middleware in Nuxt3 Auth0 - middleware

I built a simple login page in Nuxt3 using Auth0 and it works. Now I am trying to build a middleware which will redirect users who are not authenticated to the login page. I am able to use this.$auth0.isAuthenticated variable on the login.vue page but not in my middleware because I get error "Cannot read properties of undefined (reading '$auth0')". How can I access isAuthenticated variable from the middleware?
this is login page: pages/login.vue
<template>
<div>
<p v-if="isAuthenticated">hey {{ user }}</p>
<p v-else>you are not authenticated</p>
<button #click="login">Log in</button>
<button #click="logout">logout</button>
</div>
</template>
<script>
export default {
data() {
return {
user: this.$auth0.user,
isAuthenticated: this.$auth0.isAuthenticated
};
},
methods: {
login() {
this.$auth0.loginWithRedirect();
},
logout() {
this.$auth0.logout({ returnTo: 'http://localhost:3000' });
}
},
};
</script>
and this is middleware page (middleware/auth.global.ts)
export default defineNuxtRouteMiddleware(() => {
if (this.$auth0.isAuthenticated) {
console.log('authenticated')
}
else {
console.log('not authenticated')
}
})

I tried the middleware approach but I've been facing the same problem.
I ended up with this in the <script setup> section of my layout:
import { authGuard } from "#auth0/auth0-vue";
const thisRouter = useRouter();
thisRouter.beforeEach(authGuard);
I feel this is not 100% correct but it seems to work.

Related

Getting undefined parrameters i passed from another component

Okay, so, i have this Post component and i want to pass the id to the postView component, and then from there to the postPage, the problem is whatever i pass it gives me undefined, as im new to vue i have been bashing my head about this a whole day and have no idea how to go around it.
Thanks in forward!
Post component:
<template>
<div class="mb-3">
<ul v-for="post in posts" :key="post.id">
<div #click="goToPost(post.id)" class="byPost card">
<li class="card-tittle">{{ post.headline }}</li>
<li class="card-text">{{ post.description }}</li>
</div>
</ul>
</div>
</template>
<script>
import axios from "axios";
export default {
props: ["endpoint"],
data() {
return {
posts: [],
};
},
methods: {
goToPost(id){
this.$router.push({ name: 'post', params: { id } });
}
},
mounted() {
axios
.get(this.endpoint)
.then((response) => (this.posts = response.data))
.catch((error) => console.log(error));
},
};
</script>
PostView component:
<template>
<div class="home">
<PostPage
:headline="post.headline"
:description="post.description"
:likes="post.likes"
:topic="post.topic"
/>
</div>
</template>
<script>
import PostPage from "#/components/pages/post-page.vue";
import axios from "axios";
export default {
name: "Post",
data() {
return {
id: this.$route.params.id,
post: {}
};
},
components: {
PostPage,
},
mounted(){
axios.get(`http://localhost:3000/api/project_pages/${this.id}`)
.then(response => (this.post = response.data))
.catch(error => console.log(error));
}
};
</script>
First started by making the axios call in the post component, didn't go as it will do a good backend call and give me 200ok, but when passed to the postView i would get undefined, if anyone can help im open to hear it!

iOS 12+: Vue Mobile App - Crashes on Keyboard Enter Click

We have a cross-platform mobile app built using Quasar Framework, Vue & Cordova.
On the login page, when the user attempts to log in to the app on an iOS device with version 12+, the app crashes when the user uses the keyboard "enter" key to submit their credentials.
Here is a simple view of the login form:
Login Form
The crash only occurs when they use the iOS keyboard. When the user uses the "Login" button on the login page, the app doesn't crash and it pushes the user to the home screen.
We have tested this on a device with iOS version 11.4 and the crash doesn't occur.
Here is a sample of my login page & script.
import { required, email } from 'vuelidate/lib/validators';
import { filter } from 'quasar';
export default {
name: 'PageLogin',
data: function() {
return {
form: {
username: '',
password: ''
},
loggingIn: false
};
},
validations: {
form: {
username: { required, email },
password: { required }
}
},
methods: {
onSubmit() {
this.$v.form.$touch();
// Only submit if there are no errors
if (!this.$v.form.$error) {
this.loggingIn = true;
this.$store
.dispatch('account/verifyUsername', this.form)
.then(result => {
//account/verifyUsername
return this.$store.dispatch('account/login', this.form.password);
})
.then(result => { //account/login
this.$router.push({ name: 'home' });
})
.catch(error => {})
.finally(() => {
this.loggingIn = false;
});
}
}
}
};
<template>
<q-page>
<form class="ad-form" #submit.prevent="onSubmit">
<q-field :error="$v.form.username.$error" error-label="Please enter a valid email address">
<q-input type="email" v-model="form.username" float-label="Email" :error="$v.form.username.$error" #blur="$v.form.username.$touch">
<q-autocomplete #search="onSearch" #selected="onItemSelected" :min-characters="0" value-field="email"/>
</q-input>
</q-field>
<q-field :error="$v.form.password.$error" error-label="Please enter a password">
<q-input type="password" v-model="form.password" float-label="Password" :error="$v.form.password.$error" #blur="$v.form.password.$touch"/>
</q-field>
<q-btn class="standalone" type="submit" color="primary" :loading="loggingIn" :disabled="$v.form.$invalid">Login
<span slot="loading">
<q-spinner class="on-left"/>Logging In
</span>
</q-btn>
<q-btn class="standalone" type="button" flat color="secondary" :to="{ name: 'forgotPassword' }">Forgot your password?</q-btn>
</form>
</q-page>
</template>

Opentok error in rails app, "OT is not defined"

I am getting the error "OT is not defined" error in my ruby on rails app:
The API key, session_id and token has proper values.
I have included "gem 'opentox'" in my gemfile and ran 'bundle install'.
Not sure how else to initialize OT.
Show.html.erb:
<script type="text/javascript">
var apiKey = '<%= #api_key %>';
var sessionId = '<%= #room.session_id %>';
var token = '<%= #token %>';
</script>
<div id="videos">
<div id="publisher"></div>
<div id="subscribers"></div>
</div>
<script>
// Handling all of our errors here by alerting them
function handleError(error) {
if (error) {
alert(error.message);
}
}
initializeSession();
function initializeSession() {
var session = OT.initSession(apiKey, sessionId);
// Subscribe to a newly created stream
session.on('streamCreated', function(event) {
session.subscribe(event.stream, 'subscriber', {
insertMode: 'append',
width: '100%',
height: '100%'
}, handleError);
});
// Create a publisher
var publisher = OT.initPublisher('publisher', {
insertMode: 'append',
width: '100%',
height: '100%'
}, handleError);
// Connect to the session
session.connect(token, function(error) {
// If the connection is successful, publish to the session
if (error) {
handleError(error);
} else {
session.publish(publisher, handleError);
}
});
}
</script>
By adding the opentok script tag to show.html.erb, I am able to overcome this issue:
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
OT is an object of opentok which used for init session, destroy session or etc. If you have to use OT object than you must have to cdn in application.html.erb so that this OT object can be used in each page
You just have to put a cdn in head tag of application.html.erb
<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>

Does google one tap sign up works when user is not logged into his google account?

Below code works fine but when opened from an incognito windows console only shows
GoogleYolo loaded.
No credentials
<html>
<head><title>My Yolo Login example</title>
<script src="/common.js"></script>
<script defer src="https://smartlock.google.com/client"></script>
<script>
const PUBLIC_CLIENT_ID =
'*******-**********.apps.googleusercontent.com';
const CONFIG = {
supportedAuthMethods: [
'googleyolo://id-and-password',
'https://accounts.google.com'
],
supportedIdTokenProviders: [{
uri: 'https://accounts.google.com',
clientId: PUBLIC_CLIENT_ID
}],
context:"signUp"
};
window.onGoogleYoloLoad = (googleyolo) => {
console.log("GoogleYolo loaded.");
var retrievePromise = googleyolo.retrieve(CONFIG);
retrievePromise.then((credential) => {
console.log(credential);
},
(error)=>{
if(error.type == "noCredentialsAvailable"){
console.log("No credential");
googleyolo.hint(CONFIG).then((credentials)=>{console.log(credentials);});}
});
};
</script>
</head>
</html>
How can I know that user doesn't have a google account and redirect/take other action for him to login to his google account.
I'm the product manager at Google for this library. We are working on some better support for users who are not signed in, but in the interim, when no Google Accounts are active and no credentials are available, you can simply show the traditional Google Sign-In button and have the user click to proceed through the flow to activate their Google Account in the browser.
https://developers.google.com/identity/sign-in/web/
window.onGoogleLibraryLoad = () => {
// initialize one-tap here
google.accounts.id.initialize({
client_id: "YOUR_ID.apps.googleusercontent.com",
callback: handleCredentialResponse,
itp_support: true,
auto_selec: true,
prompt_parent_id: 'g_id_onload',
cancel_on_tap_outside: false,
ux_mode: 'popup',
});
google.accounts.id.prompt((notification) => {
// if one-tap is not displayed show the google sign-in button (in private mode for example)
if (notification.isNotDisplayed()) {
console.log('not displayed');
google.accounts.id.renderButton(document.getElementById('g_id_onload'), {
type: 'standard',
shape: 'rectangular',
theme: 'outline',
text: 'continue_with',
size: 'large',
logo_alignment: 'center',
width: 300
})
}
});
};
function handleCredentialResponse(googleResponse) {
// do something after callback from Google
}
<script defer async src='https://accounts.google.com/gsi/client'></script>
<div id='g_id_onload'></div>

Customizing Linkedin Login Button

I'm implementing LinkedIn Login into my web app..
I'm using following script as :
<script type="in/Login"> </script>
to load the LinkedIn Sign In button. This script automatically loads a LinkedIn Sign in button with fix design or image..
but I want to Customize a button with my custom Image of LinkedIn and this button should generate the LinkedIn login event after clicking on it.. that is it should serve above script's purpose
Plz Help
Other way to do this:
Place an image that you like:
<img onclick="liAuth()" src="./img/widget_signin.png">
Create JS function like this:
function liAuth(){
IN.User.authorize(function(){
callback();
});
}
Use LinkedIn user data:
IN.API.Profile("me")
.fields("firstName", "lastName", "headline")
.result(resultFunction);
Yes, it's possible. We're using jQuery, so here is our solution:
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: apikey
onLoad: onLinkedInLoad authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() { // Use a larger login icon.
$('a[id*=li_ui_li_gen_]').css({marginBottom:'20px'})
.html('<img src="/images/shared/linkedin-register-large.png" height="31" width="200" border="0" />');
}
</script>
Under the head tag
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: xxxxxxxxx
authorize: true
// onLoad: onLinkedInLoad
//scope: r_basicprofile r_emailaddress
</script>
<a href="javascript:void(0)" class="btn btn-default btn-linkedin" onclick='call_linkedin()'>
<i class="fa fa-linkedin-square" aria-hidden="true"></i> <span>Sign In With LinkedIn</span> </a>
<script type="text/javascript">
function call_linkedin() {
if(IN.User.authorize()){
getProfileData();
}else{ IN.Event.on(IN, "auth", function() {getProfileData();});}
}
// Use the API call wrapper to request the member's profile data
function getProfileData() {
IN.API.Profile( "me" ).fields( "id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address" ).result( displayProfileData ).error( onError );
}
// Handle the successful return from the API call
function displayProfileData( data ) {
console.log(data)
}
</script>
Please try this and let me know
You can use your own custom html code like this:
<html>
<head>
<title>LinkedIn JavaScript API</title>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: put_your_api_key_here
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.UI.Authorize().place();
IN.Event.on(IN, "auth", function () { onLogin(); });
IN.Event.on(IN, "logout", function () { onLogout(); });
}
function onLogin() {
IN.API.Profile("me").result(displayResult);
}
function displayResult(profiles) {
member = profiles.values[0];
alert(member.id + " Hello " + member.firstName + " " + member.lastName);
}
</script>
</head>
<body>
<input type="button" onclick="onLinkedInLoad()" value="Sign in using LinkedIn account" />
</body>
</html>
method for custom linkedin button
<div onclick="liAuth()">sign in with linkedin</div>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
function liAuth(){
IN.User.authorize(function(){
});
}
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
</script>
**LinkedIn Customize button onclick function you can call linked in login function**
<!-- language: lang-html -->
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: Your App Key //add your linkedIn aap key here
authorize: true
</script>
//create your customized linkedIn button with css
<div id="wLinkedIn">
// use onLinkedInLoad onclick function in customized button
<a href="#" onclick="onLinkedInLoad();">
<span id="icon-bg"><i class="fa fa-linkedin"></i></span>
<span id="icon-label-bg">Login with LinkedIn</span>
</a>
</div>
<!-- language: lang-js -->
// ----------------------------LinkedIn Sdk---------------------
function onLinkedInLoad() {
IN.UI.Authorize().place();
// call onLinkedInLogin on click of button
IN.Event.on(IN, "auth", function () { onLinkedInLogin(); });
//IN.Event.on(IN, "logout", function () { onLinkedInLogout(); });
}
function onLinkedInLogin() {
//alert('logged in');
//get all user data from linked in plugin
IN.API.Raw("/people/~:(id,firstName,lastName,emailAddress)format=json").result(function (data)
{
console.log(data);
var profileData = data;
LinkedInFName = profileData.firstName;
LinkedInLName = profileData.lastName;
LinkedInEmail = profileData.emailAddress;
LinkedInId = profileData.id;
//alert("LinkedInFName : " + LinkedInFName);
GetLinkedinLoginDetails(LinkedInEmail, LinkedInId)
}).error(function (error) {
console.log('Error : ' + error);
});
}
function onSuccess(data) {
}

Resources