Vue Login with Axios Request HTTP - javascript

Im new at Vue and im trying to make a Request HTTP to my backend,
When i inspect in my browser, i get the access token from /login but in the api/users i get "Token is Invalid". How do i get my api/users data?
import axios from "axios";
export default {
name: "login",
async created() {
const response = await axios.get("api/users", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
});
console.log(response);
},
data() {
return {
showError: false,
email: "",
password: "",
};
},
methods: {
async EnvioLogin() {
try {
const response = await axios.post("api/auth/login", {
email: this.email,
password: this.password,
});
localStorage.setItem("token", response.data.token);
const status = JSON.parse(response.status);
if (status == "200") {
console.log(response);
this.$router.push("intermediorotas");
}
} catch (error) {
this.showError = true;
setTimeout(() => {
this.showError = false;
}, 3000);
}
},
},

You can create a service to make call to backend, i guess the problem is the url http://localhots:3000/api, you missed this part http://localhots:3000
import axios from 'axios'
const client = axios.create({
baseURL: 'http://localhots:3000/api',
headers: {
'Content-Type': 'application/json',
},
})
export default client
then import the service
import myService from './myService'
await myService.get(`/auth/login`, {})

Related

Could not GET or POST data due to Auth0

I am trying to authenticate user using Auth0. Once they have signed in, I would like to obtain the data and store it in my database. If the user exist after authentication, I would like to obtain the relevant product data from my user. But if it does not exist, I would like to axios.post in my database. The problem is now I could not post the data as I do not know what is wrong.
Here is the homepage:
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { Routes, Route } from "react-router-dom";
import { useAuth0 } from "#auth0/auth0-react";
export default function Homepage() {
const [userList, setUserList] = useState([]);
const getUser = () => {
// Sending HTTP GET request
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.get(`${process.env.REACT_APP_API_SERVER}/users`, {
headers: {
Authorization: `Bearer eXg`,
},
})
.then((response) => {
const userNames = response.data.map((res) => res.name);
setUserExist(userExist);
});
};
const {
loginWithRedirect,
user,
isAuthenticated,
getAccessTokenSilently,
logout,
} = useAuth0();
useEffect(() => {
// If there is a user, retrieve the user data
if (user) {
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.get(`${process.env.REACT_APP_API_SERVER}/users`, {
headers: {
authorization: `Bearer eXg`,
},
})
.then((response) => {
setUserList(response.data);
});
} else loginWithRedirect();
}, []);
useEffect(() => {
if (isAuthenticated) {
console.log(user);
getUser();
console.log(userList);
//Check to see if curr user exists
if (userList.includes(user.name.trim())) {
console.log("already existed");
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
}); axios.get(`${process.env.REACT_APP_API_SERVER}/products/users/${userId}`, {
headers: {
Authorization: `Bearer eXg`,
},
});
}
//else post user to database
else {
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.post(
`${process.env.REACT_APP_API_SERVER}/users`,
{
firstName: user.nickname,
lastName: user.nickname,
email: user.email,
},
{
headers: {
authorization: `Bearer eXg`,
},
}
)
.then((response) => {
});
}
} else loginWithRedirect();
}, []);
return (
<div>
Hi
</div>
);
}
My backend is showing that it managed to add the user but my database is not showing anything.

Next-auth custom auth provider with custom backend

auth authentication but i'm having an issue with sessions
My next-auth version is 4.0.0-beta.4(also tried beta.7 with same results)
I have my own JWT token backend that takes a username and password. And gives back an object with accesstoken, refreshtoken, expiretime and resfresh-time
So im trying to use that backend to handle session state with next-auth.
I manage to set the cookie "next-auth.session-token". But the session is always undefined when i'm trying to getSession.
And i don't have any sessions in my firefox browser.
const options = {
providers: [
Credentials({
name: "Credentials",
credentials: {
username: {
label: "Username",
type: "text"
},
password: {
label: "Password",
type: "password"
}
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60 // the session will last 30 days
},
authorize: async (credentials) => {
const tokenUrl = "http://192.168.0.8:8081/api/auth/token"
const token = await fetch(tokenUrl, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: credentials.username,
password: credentials.password
})
})
.then(res => res.json())
console.log("token: ", token)
if (token) {
const userUrl = "http://192.168.0.8:8081/admin/user/username/" + credentials.username;
const user = await fetch(userUrl, {
method: "GET",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token.access_token
}
}).then(res => res.json())
return {
token,
user
};
} else {
return null;
}
}
}),
],
session: {
jwt: true
},
pages: {
signIn: "/login",
},
secret: "TEST",
callbacks: {
async jwt({ token, user }) {
// Initial call
if (user) {
return {
accessToken: user.token.access_token,
accessTokenExpires: Date.now() + user.token.expire_time * 1000,
refreshToken: user.token.refresh_token,
user: user.user,
}
}
// Subsequent calls
return token;
},
async session(session) {
session.name = session.token.user.fullName
session.accessToken = session.token.accessToken
session.refreshToken = session.token.refreshToken
return session;
}
}
}
Here i'm trying to get the session after logging in
export default function Home() {
const { data: session } = getSession();
console.log("session: ", session)
return (
< div >
</div >
)
}
Any ideas?
My problem was that I was using the wrong method. I needed to use the useSession method instead of getSession. Then it worked. 🙂

Unable to access response.status with React from a custom rails API

I am trying to get the status of a request I do from a React website I am working on, using axios to fetch make requests to a RoR API I developed. I would like to confirm that the POST request succeeded by accessing the status value from this (which is the output of a console.log(response):
Promise { <state>: "pending" }​
<state>: "fulfilled"​
<value>: Object { data: {…}, status: 201, statusText: "Created", … }​​
config: Object { url: "pathname", method: "post", data: "{\"user\":{\"email\":\"lou10#email.com\",\"username\":\"lou10\",\"password\":\"azerty\"}}", … }​​
data: Object { data: {…} }​​
headers: Object { "cache-control": "max-age=0, private, must-revalidate", "content-type": "application/json; charset=utf-8" }​​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 201
statusText: "Created"​​
<prototype>: Object { … }
index.jsx:51:11
But when I try a console.log(response.status) all I get is an undefined.
Here is the code :
import axios from 'axios';
import { BASE_URL } from "./config.js";
const post = async (
endpoint,
body = null,
jwt_token = null,
header = { "Content-Type": "application/json" }) => {
let opt = header;
if (jwt_token){
opt["Authorization"] = jwt_token
}
try {
const response = await axios.post(BASE_URL + endpoint, body, { headers: opt })
return response
} catch (err) {
console.error(`An error occurred while trying to fetch ${endpoint}. ${err}`);
}
}
export default post;
const handleSignup = async ({ email, username, pwd }) => {
let body = {
user: {
email: email,
username: username,
password: pwd
}
};
return await post("/users", body);
};
useEffect(() => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);
I am thinking to change the response from my API, but I really doubt it is the right approach.
Edit 1: adding some complementary code
you have to declare the function you give in parameter to useEffect as async to be able to use await inside for your async function handleSignup
useEffect(async () => {
if (passwordCheck === false) {
console.log("Passwords do not match");
} else if (passwordCheck === true && userData) {
const response = await handleSignup(userData);
console.log(response.status);
// history.push({ pathname: "/", state: response.status });
}
}, [passwordCheck, userData]);

Having problem with Authorization in vuejs vuex stores

I am writing code to call api using axios. So, for this code I have to send an otp to the api along with an authorization token. I am using vuex store.
I am getting an error of 406(not applicable). This is the code I have written.
import { isAuthenticated } from './auth'
import axios from 'axios'
export default ({
state: {
},
mutations: {
},
getters: {
},
actions: {
VERIFY: (payload) => {
const userId = isAuthenticated().user._id
return axios
.post(apilink, payload, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${isAuthenticated().token}`,
Accept: 'application/json'
}
}).then(response => {
console.log(response)
return response.data
})
.catch(error => {
if (error) {
console.log(error)
}
})
}
},
modules: {
}
})
<template>
<mdb-btn color="info" #click="verify()">Verify</mdb-btn>
</template>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
data () {
return {
value: ''
}
},
methods: {
verify () {
this.$store.dispatch('VERIFY', {
otp: this.value
}).then(success => {
console.log(success)
}).catch(error => {
console.log(error)
})
}
}
</script>
I think it's the problem with authorization part. Please help me.
isAuthenticated is funtion used to get data from localStorage
export const isAuthenticated = () => {
if (localStorage.getItem('auth')) {
return JSON.parse(localStorage.getItem('auth'))
}
return false
}
406 error is appearing because of Accept parameter in the header try after removing "Accept: 'application/json'"

ember-simple-auth custom authorizer not called with ember-django-adpter

I am using ember-django-adapter with ember-simple-auth and have written the custom authorizer for token authentication. I am able to obtain the token from server but not able to inject it into the api requests using the adapter.
app/authorizers/application.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
const { service } = Ember.inject;
export default Base.extend({
session: service('session'),
init: function () {
console.log('Intialize authorizer');
},
authorize(data, block) {
const accessToken = data['access_token'];
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
block('Authorization', `Token ${accessToken}`);
console.log("authorizer called with token: " + accessToken);
}
}
});
app/adapters/application.js
import Ember from 'ember';
import DRFAdapter from 'ember-django-adapter/adapter/drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
const { service } = Ember.inject;
export default DRFAdapter.extend(DataAdapterMixin, {
session: service('session'),
authorizer: 'authorizer:application'
});
app/authenticators/token.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
serverTokenEndpoint: 'http://localhost:8000/ember-auth/',
authenticate: function(email, password) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.serverTokenEndpoint,
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
console.log('Got token: ' + response.token);
Ember.run(function() {
resolve({
token: response.token
});
});
}, function(xhr) {
var response = xhr.responseText;
Ember.run(function() {
reject(response);
});
});
});
},
invalidate: function() {
console.log('invalidate...');
return Ember.RSVP.resolve();
}
});
Ember tries to transition to protected route but due to non injection of Authorization header the request fails with 403 error.
Any help is appreciated.

Categories

Resources