having issus with axios get method (401 unauthorized) - encryption

ok so im having issues with axios, im getting 401 unauthorized for something that worked perfectly fine.
for some reason my token is added to the Authorization header but i cant access a page i could just yesterday.
as you can see here -
also the token is saved in the localstorage -
encryption-util -
function issueJWT(user) {
const { _id } = user;
const expiresIn = 24 * 60 * 60 * 1000; // 1 day
const payload = {
sub: _id,
iat: Date.now(),
};
const signedToken = jsonwebtoken.sign(payload, PRIV_KEY, {
expiresIn,
algorithm: "RS256",
});
return {
token: `Bearer ${signedToken}`,
expires: expiresIn,
};
}
function authMiddleware(req, res, next) {
let tokenParts = " ";
if (typeof req.headers.authorization === "string") {
tokenParts = req.headers.authorization.split(" ");
}
if (
tokenParts[0] === "Bearer" &&
tokenParts[1].match(/\S+\.\S+\.\S+/) !== null
) {
try {
const verification = jsonwebtoken.verify(tokenParts[1], PUB_KEY, {
algorithms: ["RS256"],
});
req.jwt = verification;
next();
} catch (err) {
res.status(401).json({
success: false,
msg: "You are not authorized to visit this route",
});
}
} else {
res.status(401).json({
success: false,
msg: "You are not authorized to visit this route",
});
}
}
does anyone have an idea what could cause it?

Related

push notification FCM - 401 INVALID_KEY or MismatchSenderId postman

Code to generate keys : Ps validPublicKey is a firebase code p256dh.
I don´t know where is the problem. If is in the generate code, or the send notification.
I need to put it in php code yet.
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg;
console.log(swreg.pushManager.getSubscription());
console.log(JSON.stringify(swreg.pushManager.getSubscription()));
return swreg.pushManager.getSubscription();
})
.then(function(sub) {
if (sub === null) {
console.log('criando a chave');
var validPublicKey = 'BIG2EEduGTIoAYMFC3zpq2lksUw-OLRUrq_abhLs1Y2Zbo_xDUGwlozyezbSKqNkYylNN2yWKV5adB0819nQ1y0';
var convertValidPublicKey = urlBase64ToUint8Array(validPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:convertValidPublicKey
});
} else {
//we have
}
}).then(function(newSub) {
return fetch('https://???????.firebaseio.com/subscriptions.json', {
method:'POST',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body:JSON.stringify(newSub)
})
}).then(function(res) {
if (res.ok) {
displayConfirmNotification();
}
}).catch(function(err) {
console.log(err);
});
}

Download or view file using google firebase cloud function

What I'm trying to do:
Generate invoice using a third party lib.
Download/View invoice
My code
let createPdf = functions.https.onRequest(async (request, response) => {
// more code here
if (download == 'true') {
return response.status(200).download(__dirname + "/docs/" + newFileName, newFileName, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("Downloaded:", filename)
}
})
} else {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
return response.status(200).sendFile("/docs/" + newFileName, options, (err) => {
if (err) {
console.log(err);
} else {
console.log('Sent:', filename);
}
});
}
});
The error
{
"error": {
"code": 500,
"status": "INTERNAL",
"message": "function crashed",
"errors": [
"socket hang up"
]
}
}
Note:
When I return a simple string instead of the file it works.
Use express request and response objects to send a file.
Read this documentation: using_express_request_and_response_objects
And don't forget to use absolute path when using sendFile

navigation after AsyncStorage.setItem: _this3.navigateTo is not a function

Currently, I am implementing a chat. After user pressed a chat button, the app will navigate the user to the Chat component. The chat content will simply store in firebase and chatId is needed to identify which chat belongs to the user.
Since I don't know how to pass props during navigation, I decided to save the CurrentChatId in AsyncStorage. After navigated to the Chat component, it will get the CurrentChatId from AsyncStorage so that I can map the chat content with the firebase.
However, I got the error _this3.navigateTo is not a function with code below:
let ref = FirebaseClient.database().ref('/Chat');
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
The function navigateTo is copied from the demo app of NativeBase
import { actions } from 'react-native-navigation-redux-helpers';
import { closeDrawer } from './drawer';
const {
replaceAt,
popRoute,
pushRoute,
} = actions;
export default function navigateTo(route, homeRoute) {
return (dispatch, getState) => {
const navigation = getState().cardNavigation;
const currentRouteKey = navigation.routes[navigation.routes.length - 1].key;
dispatch(closeDrawer());
if (currentRouteKey !== homeRoute && route !== homeRoute) {
dispatch(replaceAt(currentRouteKey, { key: route, index: 1 }, navigation.key));
} else if (currentRouteKey !== homeRoute && route === homeRoute) {
dispatch(popRoute(navigation.key));
} else if (currentRouteKey === homeRoute && route !== homeRoute) {
dispatch(pushRoute({ key: route, index: 1 }, navigation.key));
}
};
}
You should bind this to the function that contains the try & catch. The best practice is to add this bind the constructor of the the component:
constructor(props) {
super(props);
this.myFunctoin = this.myfuction.bind(this);
}
Finally, I solved the problem. It is really because this.navigateTo('chat'); is inside function(snapshot)
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
Take it out from the function will solve the problem.

Reauthenticate Firebase User

I am working on a project with angularfire and I am trying to implement the method to update user password. Due the messed documentation about it, please help me to find a solution to re-authenticate an user. I've already read this stackoverflow question
account.js:
vm.updateUserPassword = function() {
if (vm.oldPassword && vm.newPassword && vm.confirmNewPassword) {
if (vm.newPassword === vm.confirmNewPassword) {
var currentCredential = firebaseAuth.EmailAuthProvider.credential(vm.currentAuth.email, vm.oldPassword);
vm.currentAuth.reauthenticate(currentCredential)
.then(function() {
Database.updateUserPassword(vm.newPassword);
}, function(error) {
console.error('[Account]', error);
});
} else {
toastr.error('A nova senha não confere');
}
} else {
toastr.error('Preencha todos os campos corretamente');
}
};
database.js service:
vm.updateUserPassword = function(newPassword) {
firebaseAuth.$updatePassword(newPassword)
.then(function() {
console.log('[Database] Password changed successfully!');
}).catch(function(error) {
switch (error.code) {
case 'auth/requires-recent-login':
vm.translationId = 'FIREBASE.AUTH.REQUIRES_RECENT_LOGIN.ERROR_MSG';
break;
default:
vm.translationId = error.message;
}
$translate(vm.translationId)
.then(function(translated) {
toastr.error(translated);
}, function(translationId) {
vm.translationId = translationId;
});
});
};
Console error:
TypeError: Cannot read property 'credential' of undefined
You can get credential using:
firebase.auth.EmailAuthProvider.credential(user.email, userProvidedPassword);
instead of:
firebase.auth().EmailAuthProvider.credential(user.email, userProvidedPassword);

Api-Service and HTTP-Service in Angular 2

Im fairly new to Angular 2 and i have got a question.
In my "older" Angular 1 Webapps i had a "Api-Service" and a "Http-Service" every time.
They looked like this:
"ApiService":
angular.module('ionicApp.apiServices', [])
.service('apiService', function(httpService) {
return {
getProfile: function(){
return httpService.async('get', 'profile', {}, {}, {});
},
addSkills: function(skillList) {
var url = 'profile/skills';
return httpService.async('post', url, {}, {}, skillList);
}
}
HTTP-Service:
angular.module('ionicApp.httpService', [])
.service('httpService', function ($http, $rootScope, $state, $ionicLoading, $ionicHistory) {
var httpCall = {
async : function (method, url, header, params, data) {
// Setze den X-AUTH-TOKEN in den Header, welcher für die Authentifizierung des Users verantwortlich ist
if (url != 'login' || url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
header['X-AUTH-TOKEN'] = $rootScope.userToken;
}
header['Access-Control-Allow-Origin'] = '*';
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http({
method : method,
url : ipurl + url,
headers : header,
params : params,
data : data,
timeout: 10000,
withCredentials : true
}).then(function successCallback(response) {
if (url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
$rootScope.userToken = response.headers('X-AUTH-TOKEN');
}
return response;
}, function errorCallback(response) {
if (response.status === 401) {
$rootScope.isFailure = true;
$rootScope.failure = "Sie haben keine gültige Session mehr. Bitte loggen Sie sich erneut ein.";
doLogout();
} else {
return response;
}
});
// Return the promise to the controller
return promise;
},
doLogout : doLogout
};
return httpCall;
});
Ok, now my question is, how can i do this with angular 2?
I already did an Api-Service and an HTTP-Service (both are Injectables), and injected them in each component.
But what´s the trick to get them functional?
Thanks so much!

Resources