nuxt axios onError unathenticated logout then redirect - axios

my backend in laravel and i set if user login to another device then current device auth token is invalid
i also want if he get unathenticated error 401 in axios then instant logout and redirect to login page
i am doing like this
export default function({ $axios, redirect, $auth }) {
$axios.onError(error => {
if (error.response.status === 401) {
if ($auth.loggedIn) {
$auth.logout();
}
redirect("/login");
}
});
}
but nothing happen and when i check console.log($auth) its getting undefine
Help me thank you

If you need to access $auth from $axios plugin, you can use auth.plugins option.
https://auth.nuxtjs.org/recipes/extend.html
{
modules: [
'#nuxtjs/auth'
],
auth: {
plugins: [ { src: '~/plugins/axios', ssr: true }, '~/plugins/auth.js' ]
}
}

Related

Get token set on API on a SSR page Nextjs

I am using Spotify authentication and in the callback I set the cookie and redirect to another page:
export default async (req, res) => {
const token = await getToken(req.query.code);
res.setHeader('Set-Cookie', cookie.serialize('token', JSON.stringify(token), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: token.expires_in,
sameSite: 'strict',
path: '/',
}));
res.redirect(token ? '/cloner' : '/');
}
On '/cloner' page I do SSR where '/' is the path to the login page:
export async function getServerSideProps(ctx) {
const cookies = nookies.get(ctx);
if (!cookies.token) { // <-- is undefined
return {
redirect: {
destination: '/',
permanent: false,
}
}
}
return {
props: {}
}
}
In the getServerSideProps the token is undefined so is returning me to the login page ('/').
BUUUUUUT, if I check in the site I can see the cookie, and if I write the /cloner manually that page load just right.
If you check in the link below you will see that if you login redirect to login again. But, if you refresh the login page it sends you to the cloner page (in login I have also SSR to redirect to cloner if already login)
https://playlist-cloner.vercel.app/

How to redirect if succes login with Google in Nuxt js

here I try to log in using google at nuxt.js, but when I log in with my Google account, the page doesn't move
has anyone experienced the same thing?
I hope someone provides an example of the code. thank you
this.my code login.vue
async loginGoogle() {
try {
let response = await this.$auth.loginWith('google', {})
console.log(response)
} catch (err) {
console.log(err)
}
}
this my code nuxt.config.js
google: {
client_id: 'xxxxxxxxx.apps.googleusercontent.com',
redirect_uri: 'http://localhost:3000',
},
I have take a look at https://auth.nuxtjs.org/api/options.html#redirect
It looks different they use auth in ther nuxt.config.js
auth: {
redirect: {
login: '/login',
logout: '/',
callback: '/login',
home: '/'
}
}

X-XSRF-TOKEN header with axios

Do I have to set anything to send X-XSRF-TOKEN header if I set a XSRF-TOKEN cookie server side?
https://github.com/axios/axios/blob/master/lib/defaults.js#L74
https://github.com/axios/axios/blob/master/dist/axios.js#L1072
It reads like I don't, but I'm not seeing one go out.
I'll add that I have set withCredentials to true, so I do meet the first check in the OR:
var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
so if config.xsrfCookieName is a default.....
Update:
So, my OPTIONS preflight CORS is working, as is the POST now, but no X-XSRF-TOKEN being sent.
methods: {
onSubmit(e) {
this.axios
.post(
e.target.action,
{ data: this.form },
{
withCredentials: true,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN"
}
)
.then(res => {
console.log(res)
})
.catch(err => {
this.errors.push(err)
})
}
}
Thanks.
I had the same issue and was about the "secure" flag on the cookie as can be seen on the cookies tab of the request, but is not showing on the cookies under "application" tab:
In my case, I had to ask the backend to set it down.
This happens because, as secure, you cannot access to it via javascript.
document.cookie // is empty

Meteor + facebook login (loginWithFacebook) issue. client_id is always undefined in login popup's URL

I put this issue in gist as well:
https://gist.github.com/yhagio/7561f34d12bc5edb9b5fe0fc1b4bb2b6
Github Repo : https://github.com/yhagio/meteor-tatter
Issue
When I click facebook login button, it opens the login popup, but
the URL in the popup always shows that client_id=undefined, and gives "Sorry, something went wrong".
I installed service-configuration and accounts-facebook meteor packages and configured as follows.
Also, cretead the app & added Facebook Login product in https://developers.facebook.com
Am I missing something?
Screenshot
The URL is like this:
https://www.facebook.com/v2.2/dialog/oauth?client_id=undefined&redirect_uri=http://localhost:3000/_oauth/facebook&display=popup&scope=public_profile&state=eyJsb2dpblN0eW...
In server https://github.com/yhagio/meteor-tatter/blob/master/imports/startup/server/index.js
import { Meteor } from 'meteor/meteor';
import { clientId, secret } from './secret.js';
Meteor.startup(() => {
ServiceConfiguration.configurations.upsert(
{ service: "facebook" },
{
$set: {
clientId: clientId,
loginStyle: "popup",
secret: secret
}
}
);
});
In client https://github.com/yhagio/meteor-tatter/blob/master/imports/ui/helpers/auth.js
import { Meteor } from 'meteor/meteor';
export default function auth() {
return new Promise((resolve, reject) => {
Meteor.loginWithFacebook({
requestPermissions: ['public_profile']
}, (err, user) => {
if (err !== null) return reject(err);
resolve(user);
});
});
}
Problem was that it should be appId instead of clientId. Even though the guide shows clientId. Ref: http://docs.meteor.com/api/accounts.html#service-configuration

Move to another hbs in ember after the authentication is done

I have an app in which I have include a fb login.I am using ember-simple-auth for authorization and session manganement.I am able to authenticate the user and move to my "feed" hbs .The problem is when I open the app on another tab it is rendering the login page.How do I implement where if the user is authenticated it directly move to "feed" hbs.Similary to facebook,instagram where user login for the first time and after that they are redirect to feed page until they logout.
autheticator.js
const { RSVP } = Ember;
const { service } = Ember.inject;
export default Torii.extend({
torii: service('torii'),
authenticate() {
return new RSVP.Promise((resolve, reject) => {
this._super(...arguments).then((data) => {
console.log(data.accessToken)
raw({
url: 'http://example.com/api/socialsignup/',
type: 'POST',
dataType: 'json',
data: { 'access_token':'CAAQBoaAUyfoBAEs04M','provider':'facebook'}
}).then((response) => {
console.log(response)
resolve({
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
access_token: response.access_token,
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
provider: data.provider
});
}, reject);
}, reject);
});
}
});
router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('index',{path:'/'});
this.route("aboutus",{path:'/aboutus'});
this.route('feed',{path:'/feed'});
});
export default Router;
You need to use the application-route-mixin.js in the route that will be the first shown after login and authenticated-route-mixin.js for all the routes that need to be logged to see them. Check this example for further information.