SyntaxError: Unexpected end of JSON input - Passport-local - node.js

I am using passport local and I already got the user data using req.session.passport.user
But for some reason I am having trouble receiving the user data by using Ajax or fetch request.
Any ideas?
app.get('/api/student/compose', function(req, res) {
if (req.isAuthenticated()) {
res.json({
data: req.session.passport.user
});
} else {
res.json({data: "Not logged in!"});
}
});
The following code is on the client side:
/**
* Get the user data
*
* #returns {Object} Return the user data
*/
async userData() {
let url = `http://localhost:3000/api/student/compose`;
let receivingData = {};
await fetch(url, {
method: "get",
mode: "cors",
headers: {
Accept: "application/json", // expected data sent back
}
}).then((data) => {
receivingData.data = data;
receivingData.err = false;
})
.catch((error) => {
receivingData.err = true;
receivingData.errMessage = error;
});
return receivingData;
}

Related

Implementation of rxjs BehaviourSubject in Next.js for state management not working

Trying to store jwt token on login using rxjs behavioursubject
Then creating a http request with Authorization: Bearer ${user.jwtToken} in the
I believe I need to have
a) initial value,
b) a source that can be turned into an observable
c) a public variable that can be subscribed
On log in the user is correctly added to the user subject here "userSubject.next(user);"
But whenever I try to create the bearer token its always null
// The Accounts Service
// initialise and set initial value
const userSubject = new BehaviorSubject(null);
const authApiUrl = "https:testApi";
export const accountService = {
` user: userSubject.asObservable(), get userValue() { return userSubject.value },
login,
getAllUsers
};
function login(email, password) {
return fetchWrapper.post(process.env.AuthApiUrl + '/accounts/authenticate', { email, password })
.then(user => {
userSubject.next(user);
localStorage.setItem('user', JSON.stringify(user));
return user;
});
}
function getAllUsers() {
return await fetchWrapper.get(process.env.AuthApiUrl + '/accounts/get-all-users');
}
}
// The fetchwrapper
export const fetchWrapper = {
get,
post
};
function post(url, body) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeader(url) },
credentials: 'include',
body: JSON.stringify(body)
};
return fetch(url, requestOptions).then(handleResponse);
}
function get(url) {
const requestOptions = {
method: 'GET',
headers: authHeader(url)
};
return fetch(url, requestOptions).then(handleResponse);
}
function authHeader(url) {
// return auth header with basic auth credentials if user is logged in and request is to the api url
// THE accountService.userValue IS ALWAYS NULL???
const user = accountService.userValue;
const isLoggedIn = user && user.jwtToken;
const isApiUrl = url.startsWith(process.env.AuthApiUrl);
if (isLoggedIn && isApiUrl) {
return { Authorization: `Bearer ${user.jwtToken}` };
} else {
return {};
}
}
function handleResponse(response) {
return response.text().then(text => {
const data = text && JSON.parse(text);
if (!response.ok) {
if ([401, 403].includes(response.status) && accountService.userValue) {
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
accountService.logout();
}
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
return data;
});
}

Svelte: Hooks.js file is not getting recently created cookies

Someone knows why my hooks.js file not getting recently created cookies
When I do login with discord api in my svelte website, the cookies are created and the hooks only get it minutes after.
Someone can help me please?.....
I'm using parts of the medium discord Oauth2 svelte example
import cookie from 'cookie';
const DISCORD_API_URL = import.meta.env.VITE_DISCORD_API_URL;
const HOST = import.meta.env.VITE_HOST;
/** #type {import('#sveltejs/kit').GetSession} */
export async function getSession(req) {
const cookies = cookie.parse(req.request.headers.get("cookie") || '');
console.log(cookies)
// if only refresh token is found, then access token has expired. perform a refresh on it.
if (cookies.disco_refresh_token && !cookies.disco_access_token) {
console.log("Tem o refresh mas não tem o acess")
const discord_request = await fetch(`${HOST}/api/refresh?code=${cookies.disco_refresh_token}`);
const discord_response = await discord_request.json();
if (discord_response.disco_access_token) {
console.log('setting discord user via refresh token..')
const request = await fetch(`${DISCORD_API_URL}/users/#me`, {
headers: { 'Authorization': `Bearer ${discord_response.disco_access_token}` }
});
const response = await request.json();
if (response.id) {
return {
user: {
// only include properties needed client-side —
// exclude anything else attached to the user
// like access tokens etc
...response
}
}
}
}
}
if (cookies.disco_access_token) {
console.log('setting discord user via access token..')
const request = await fetch(`${DISCORD_API_URL}/users/#me`, {
headers: { 'Authorization': `Bearer ${cookies.disco_access_token}`}
});
// returns a discord user if JWT was valid
const response = await request.json();
if (response.id) {
return {
user: {
...response
}
}
}
}
// not authenticated, return empty user object
return {
user: false
}
}
My Auth callback file:
const DISCORD_CLIENT_ID = import.meta.env.VITE_DISCORD_CLIENT_ID;
const DISCORD_CLIENT_SECRET = import.meta.env.VITE_DISCORD_CLIENT_SECRET;
const DISCORD_REDIRECT_URI = import.meta.env.VITE_DISCORD_REDIRECT_URI;
/**
* #type {import('#sveltejs/kit').RequestHandler}
*/
export async function get({ url }) {
// fetch returnCode set in the URL parameters.
const returnCode = url.searchParams.get("code");
console.log('returnCode =>', returnCode);
// initializing data object to be pushed to Discord's token endpoint.
// the endpoint returns access & refresh tokens for the user.
const dataObject = {
client_id: DISCORD_CLIENT_ID,
client_secret: DISCORD_CLIENT_SECRET,
grant_type: 'authorization_code',
redirect_uri: DISCORD_REDIRECT_URI,
code: returnCode,
scope: 'identify email guilds'
};
// performing a Fetch request to Discord's token endpoint
const request = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams(dataObject),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
const response = await request.json();
console.log(response)
if (response.error) {
console.log('redirect to / due error');
return {
headers: { Location: '/' },
status: 302
}
}
// redirect user to front page with cookies set
const access_token_expires_in = new Date(Date.now() + response.expires_in); // 10 minutes
const refresh_token_expires_in = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days
console.log('redirect to /logged with cookies');
return {
headers: {
'set-cookie': [
`disco_access_token=${response.access_token}; Path=/; HttpOnly; SameSite=Strict; Expires=${access_token_expires_in}}`,
`disco_refresh_token=${response.refresh_token}; Path=/; HttpOnly; SameSite=Strict; Expires=${refresh_token_expires_in}`,
],
Location: '/'
},
status: 302
}
}

How to send parameters through axios get method in react?

I have a axios GET method and I need to pass parameters with the get request. I am calling the GET method in Client side (React.js) like this,
const [Cart] = useState([]);
const user = {
userId : session.userId
};
console.log(user);
useEffect((user) => {
if(session.userId !== null){
//Axios.get('http://localhost:5000/api/cart/getCart', user) <- I tried both these ways
Axios({
method: 'GET',
url: 'http://localhost:5000/api/cart/getCart',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: {},
params: {
"userId" : session.userId
}
})
.then(res => {
const cart = res.data;
let tempProducts = [];
cart.data.forEach(item => {
const singleItem = {...item};
tempProducts = [...tempProducts, singleItem];
});
this.setState(() => {
return {Cart: tempProducts};
});
})
}
console.log(Cart)
});
But in server side (node.js), it doesn't get the parameter value.
router.get('/getCart', (req, res) => {
console.log(req.body.userId) //This gives the output as undefined
User.findOne({_id: req.body.userId}
,(err, userInfo) => {
res.json(userInfo.Cart);
})
});
I implemented the uncommented axios.get request by referring to this. Can you please help me to find the error? Or can you suggest me any other method to do this? Thanks
UseEffect :
axios.get('/api', {
params: {
foo: 'bar'
}
});
Server :
function get(req, res, next) {
let param = req.query.foo
.....
}

How to logout once jwt token is expired

I am working on a web-app using node.js and vue.js, I am doing authentication and maintaining session using jwt and passport.js using passport-jwtstrategy
I have done all the things from creating jwt to protecting routes all the things now my issue is while generating jwt I am passing expiresIn:3600 so I want to auto-logout my user from Ui and remove token from localStorage once it has been one hour
On decoding my jwt I am getting
{
"name": "Dheeraj",
"iat": 1571896207,
"exp": 1571899807
}
So how can I get the real-time when to logout
In my auth.js vue store file my logout code when user clicks on logout is
logout({ commit }) {
return new Promise((resolve, reject) => {
localStorage.removeItem('jwt-token')
localStorage.removeItem('user-name')
commit('setAuthUser', null)
resolve(true)
})
},
In the same file, I have a method getAuthUser which is running whenever a page is loading or reloading to check to protect rout and guestUser
getAuthUser({ commit, getters }) {
const authUser = getters['authUser']
const token = localStorage.getItem('jwt-token')
const isTokenValid = checkTokenValidity(token)
if (authUser && isTokenValid) {
return Promise.resolve(authUser)
}
commit('setAuthUser', token)
commit('setAuthState', true)
debugger
return token
}
So how can I logout once my token is expired
Anyone out here please guide me how can I logout once the token is expired
Edit
In my router.js file
router.beforeEach((to, from, next) => {
store.dispatch('auth/getAuthUser')
.then((authUser) => {
const isAuthenticated = store.getters['auth/isAuthenticated']
if (to.meta.onlyAuthUser) {
if (isAuthenticated) {
next()
} else {
next({ name: 'login' })
}
} else if (to.meta.onlyGuestUser) {
if (isAuthenticated) {
next({ name: 'welcome' })
} else {
next()
}
} else {
next()
}
})
})
from my auth file I am calling get authUser which I have already mention above
for checking token validity I am using this code
function checkTokenValidity(token) {
if (token) {
const decodedToken = jwt.decode(token)
return decodedToken && (decodedToken.exp * 1000) > new Date().getTime()
}
return false
}
but it returns false when I am on login page and there is no token there but once I am loged in it shows null
My global api file
import axios from 'axios';
export default () => {
let headers = {
'cache-control': 'no-cache'
};
let accessToken = localStorage.getItem('jwt-token');
if (accessToken && accessToken !== '') {
headers.Authorization = accessToken;
};
return axios.create({
baseURL: 'http://localhost:8086/',
headers: headers
});
}
Refer to the axios documentataion: https://github.com/axios/axios
import axios from 'axios';
export default () => {
let headers = {
'cache-control': 'no-cache'
};
let accessToken = localStorage.getItem('jwt-token');
if (accessToken && accessToken !== '') {
headers.Authorization = accessToken;
};
const instance = axios.create({
baseURL: 'http://localhost:8086/',
headers: headers
});
instance.interceptors.response.use((response) => {
if(response.status === 401) {
//add your code
alert("You are not authorized");
}
return response;
}, (error) => {
if (error.response && error.response.data) {
//add your code
return Promise.reject(error.response.data);
}
return Promise.reject(error.message);
});
return instance;
}

Firebase cloud messaging: Request contains an invalid argument

I'm following this tutorial, I got to the point to send an HTTP request to the fcm endpoint, but I'm getting the following error:
{
error:
{
code: 400,
message: 'Request contains an invalid argument.',
status: 'INVALID_ARGUMENT'
}
}
Instead of sending the request using curl I'm using a cloud function using node.js | express with the following code:
exports.messages = function (req, res) {
const api = 'https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send';
const headers = {
'Accept': 'application/json',
'Content-type': 'application/json',
};
return getAccessToken().then((accessToken) => {
headers.Authorization = `Bearer ${accessToken}` // <-- accessToken is OK
const { title, body, token } = req.body;
return fetch(api, {
headers,
method: 'POST',
body: JSON.stringify(
{
'message': {
'token': token, // <-- this is the client fcm token
'notification': {
'title': title,
'body': body
}
}
}
)
}).then(res => res.json()).then(data => {
console.log(data);
res.sendStatus(200);
}).catch((error) => {
console.error(error);
});
});
}
Where the token is an OAuth 2 token for my service account
function getAccessToken() {
return new Promise(function (resolve, reject) {
var key = require('../keys/service-account.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
[
'https://www.googleapis.com/auth/firebase',
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/firebase.messaging',
],
null
);
jwtClient.authorize(function (err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
what am I missing here? any advice will be appreciated
I just realized I copied the uri for the fcm endpoint from the tutorial. I changed it to:
const api = 'https://fcm.googleapis.com/v1/projects/{project-Id}/messages:send';
and it worked!

Resources