I'm using http.post node.js to post to https://api.mmitnetwork.com/Token to get an access Token.
How do I take the reponse I get back and set the state?
var App = React.createClass ({
getInitialState() {
return {
token: ''
}
},
componentDidMount() {
var _this = this;
var request = http.post('https://api.mmitnetwork.com/Token', {grant_type: 'password', username: 'myusername', password: 'mypassword'}, function(response) {
console.log(response.statusCode);
response.on('data', function(chunk) {
console.log('BODY: ' + chunk);
_this.setState({
token: response.chunk.access_token
})
});
})
request.on('error', function(err) {
console.error(err.message);
})
},
render() {
{this.state.token}
}
Related
const login = (req, res) => {
// console.log(req.body);
// let email = req.body.email.toLowerCase();
sequelize.models.User.findOne({
where: {
email: req.body.email,
},
})
.then(async (user) => {
if (!user) {
// console.log(" email not found is true");
return res.status(401).json({
success: false,
message: " Authentication failed, Wrong Credentials",
});
}
if (user.isActive == false) {
// console.log("user is not activated", user.isActive);
return res.status(400).json({
success: false,
message: "account is not activated",
});
}
console.log("test entry");
await user.comparePassword(req.body.password, async (err, isMatch) => {
console.log(req.body.password);
if (isMatch && !err) {
console.log("user crap");
// role_id: user.role_id,
const payload = {
user_id: user.user_id,
};
const options = {
expiresIn: "10day",
};
const token = await jwt.sign(payload, process.env.SECRET, options);
console.log("sssssss", payload);
if (user.twoFactorAuth == false) {
return res.json({
success: true,
token,
});
} else {
// let mobile = user.phone;
await twoFactorAuth(user); // we call the 2fa that will send a otp to the users cellphone
// console.log("after cb");
}
} else {
return res.json({
success: false,
msg: "Authentication failed.",
});
}
});
// console.log("user crap", user.user_id);
})
.catch((error) => {
return res.status(400).send(error);
});
};
const twoFactorAuth = async (user) => {
var data = qs.stringify({
sender: "hehe",
mobile: user.phone,
channel: "sms",
});
var config = {
method: "POST",
url: "https://blablabla",
headers: {
Authorization: "Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
},
data: data,
};
axios(config)
.then( async function (response) {
console.log(JSON.stringify(response.data));
// await verifyTwoFactorAuth (realToken)
})
.catch(function (error) {
console.log(error);
});
};
const verifyTwoFactorAuth = async(req, res) => {
//console.log("tet",req);
let otpcode = req.body.otpcode;
let mobile = req.body.mobile;
var data = qs.stringify({ mobile: mobile, code: otpcode });
var config = {
method: "POST",
url: "https://blablabla",
headers: {
Authorization: "Bearer xxxxxxxxxxxxxxxxxxxxxxxx",
},
data: data,
};
axios(config)
.then(async function (response) {
console.log(JSON.stringify(response.data));
if (response.data.code == 63 || response.data.status == 200) {
return res.json({
success: true,
token,
});
} else if (response.data.code == 21 || response.data.status == 422) {
return res.status(400).json({
success: false,
message: "wrong code, check your sms again",
});
}
})
.catch(function (error) {
console.log(error);
});
};
Hello, I am looking for a structure solution to how I should implement what I want.
Scenario: user try to login, system checks for username and passoword and generates the TOKEN, system finds that 2fa is active in users settings, system sends OTP to users cellphone.
Now my struggle begins, I am not sure what to do next, I thought about storing the token in users fields as tempToken then i look for the user via users mobile and extract the token that way, but I dont believe that this is best practice.
Any ideas of how to tackle this would be appreciated ! thank you
I have a controllerfile where I use passport.authenticate. I declare my payload and sign my token now i need the info declared in the payload in another file so I could use them in my sql request.
Here's the code for the login auth :
login: (req, res, next) => {
console.log(" login");
passport.authenticate("local", { session: false }, (error, user) => {
console.log("executing callback auth * from authenticate for local strategy ");
//if there was an error in the verify callback related to the user data query
if (error || !user) {
next(new error_types.Error404("Email ou Mot de passe invalide !"))
}else {
console.log("*** Token generation begins ***** ");
console.log(user)
const payload = {
sub: user.id,
exp: Date.now() + parseInt(process.env.JWT_LIFETIME),
email: user.email,
name: user.prenom,
lastName: user.nom,
type:user.type,
};
const token = jwt.sign(JSON.stringify(payload), process.env.JWT_SECRET, {algorithm: process.env.JWT_ALGORITHM});
res.json({ token: token,type: user.type,userid:user.id });//added userid
}
})(req, res);
}
Now in my other file i need to get the user.id and user.type so that i could use them in my request :
const createProp=(req, res, next) => {
let con=req.con
let { xx,yy } = req.body;
con.query('INSERT INTO tab1
(xx,yy,user_id,user_type ) VALUES ($1, $2, $3, $4) ',[xx,yy,user_id,user_type],
(err, results) => {
if (err) {
console.log(err);
res.status(404).json({error: err});
}
else
{res.status(200).send(`success`)}
}
);
}
in my frontend VUEJS this is my file:
import router from '#/router'
import { notification } from 'ant-design-vue'
import JwtDecode from "jwt-decode";
import apiClient from '#/services/axios'
import * as jwt from '#/services/jwt'
const handleFinish = (values) => {
const formData = new FormData()
for (var key of Object.keys(formState)) {
formData.append(key, formState[key])//here im appending some fields in my
//form i have more than just xx,yy files i just put them as an
//example
}
const token = localStorage.getItem("accessToken");
var decoded = JwtDecode(token);
console.log(decoded)
formData.append('user_id',decoded.sub)
formData.append('user_type',decoded.type)
fileListFaisabilite.value.forEach((file) => {
formData.append('xx', file)
})
fileListEvaluation.value.forEach((file) => {
formData.append('yy', file)
})
// store.dispatch('user/PROPOSITION', formData)
}
methods:{
PROPOSITION({ commit, dispatch, rootState }, formData ) {
commit('SET_STATE', {
loading: true,
})
const proposition=
mapAuthProviders[rootState.settings.authProvider].proposition
proposition(formData)
.then(success => {
if (success) {
notification.success({
message: "Succesful ",
description: " form submited!",
})
router.push('/Accueil')
commit('SET_STATE', {
loading: false,
})
}
if (!success) {
commit('SET_STATE', {
loading: false,
})
}
})
return apiClient
.post('/proposition', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(response => {
if (response) {
return response.data
}
return false
})
.catch(err => console.log(err))
},
},
What im looking for is how i can store in my database the userid and usertype using insertinto sql request.
You can set user data in your jwt sign function without stringify method:
const payload = {
sub: user.id,
exp: Date.now() + parseInt(process.env.JWT_LIFETIME),
email: user.email,
name: user.prenom,
lastName: user.nom,
type: user.type // <-- Add this
};
const token = jwt.sign(
payload, // Don't use JSON.stringify
process.env.JWT_SECRET,
{algorithm: process.env.JWT_ALGORITHM}
);
And access user info:
jwt.verify(token, process.env.JWT_SECRET, (err, payload) => {
if (err) {
// Handle error
}
// Get some data
let user_id = payload.sub;
let user_type = payload.type;
console.log(user_id, user_type);
next();
});
The vue file:
PROP({ commit, dispatch, rootState }, payload ) {
commit('SET_STATE', {
loading: true,
});
const prop = mapAuthProviders[rootState.settings.authProvider].prop
prop(payload)
.then(success => {
if (success) {
// success contains user information and token:
const { token, userid, type } = success;
// Save to localStorage (Optional)
localStorage.setItem("accessToken", token);
localStorage.setItem("userid", userid);
localStorage.setItem("type", type);
// This not works if don't have a JWT SEED
// var decoded = JwtDecode(token);
commit('SET_STATE', {
user_id: userid,
user_type: type,
})
//dispatch('LOAD_CURRENT_ACCOUNT')
notification.success({
message: "Succesful ",
description: " form submited!",
})
router.push('/Home')
commit('SET_STATE', {
loading: false,
})
}
if (!success) {
commit('SET_STATE', {
loading: false,
})
}
})
},
The api call file:
export async function prop(payload) {
try {
const response = await apiClient.post('/prop', payload, {
headers: { 'Content-Type': 'multipart/form-data'},
});
if (response) {
return response.data;
}
} catch (err) {
console.log(err);
}
return false;
}
I'm asking again with this code provided Please Help Thank you. I am calling this API with Firebase function from Android using okhttp3, here the code below. I already subscribed to a plan in firebase to call external API
Firebase Cloud Function Code
exports.CustomerProfile = functions.https.onRequest((req, res) => {
const options = {
method: "POST",
uri: "http://3.xxxx.xx.xx2:3000/api/customers/profile",
formData: {
session_token: req.body.session_token
},
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-auth-token": "xxxxxxE"
},
resolveWithFullResponse: true,
json: true,
simple: false
};
rp(options)
.then(function(response) {
res.send(response.body);
})
.catch(function(err) {
res.send(err);
});
});
API CODE
router.post("/profile", async (req, res) =>{
const customers = new Customers();
var data = req.body;
var token = req.body.session_token;
customers.findBySessionToken(token, (err, result) => {
if (!err) {
if(result[0].provider === 'gmail'){
var gmail = result[0].access;
customers.findByGmail(gmail, (err, result) => {
res.status(200).send(result);
});
}else if(result[0].provider === 'facebook') {
var facebook = result[0].access;
customers.findByFb(facebook, (err, result) => {
res.status(200).send(result);
});
}else if(result[0].provider === 'mobile') {
var mobile = result[0].access;
customers.findByMobile(mobile, (err, result) => {
res.status(200).send(result);
});
}
} else {
if (err.code === "ER_SIGNAL_EXCEPTION") {
res.status(400).send([{ message: err.sqlMessage }]);
} else {
res.status(400).send(err);
}
}
});
});
this means that you have already sent a response res.send... somewhere else , you cant do more than one response for a request.
i can't figure out what to place in exchange of the JSON.stringify syntax in the body parameter. It is returning a SyntaxError with a code of 800A03EA
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
body: JSON.stringify({
status: 'automated message to post'
})
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
Nothing. Instead, add
json: true to your options and don't attempt any stringification. request() will do the magic for you.
const request = require('request');
const username = 'myUserName';
const password = 'myPassword';
const options = {
method: 'POST',
url: 'https://siteToPostTo.com/api/v1/statuses',
auth: {
user: username,
password: password
},
json: true,
body: {
status: 'automated message to post'
}
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
I'm creating a web app that connects with an API in order to do a login and some stuff, currently I'm trying to test a /authenticate route on my app using chai, chai-http and nock.
var chai = require('chai');
var expect = chai.expect;
var chaiHttp = require('chai-http');
var nock = require('nock');
chai.use(chaiHttp);
describe('/authenticate', function() {
var agent = chai.request.agent('http://localhost:3000');
afterEach(function() {
agent.close();
nock.cleanAll();
});
describe('User authorized', function() {
it('redirects to /dashboard', function() {
// I'm trying to mock the response here but is not working.
nock('http://the.api.com:8080')
.post('/v1/authenticate')
.reply(201, {
'authorized': true,
'jwt': 'thejwtasdf'
});
agent
.post('/authenticate')
.send({ email: 'test#gmail.com', password: 'TheAmazingPass' })
.then(function(res) {
expect(res).to.redirectTo('http://localhost:3000/dashboard');
expect(res.text).to.match(/Dashboard/);
})
.catch(function(e) { console.log(e); });
});
});
});
The test pass but I got this caught error, according to this, the page is not redirected because the call is not caught by nock and it is directly sent to the API:
{ AssertionError: expected redirect with 30X status code but got 200
at Proxy.<anonymous>
... rest of the error omitted.
But when I use a real and valid email and password this test pass with no caught error:
var chai = require('chai');
var expect = chai.expect;
var chaiHttp = require('chai-http');
var nock = require('nock');
chai.use(chaiHttp);
describe('/authenticate', function() {
var agent = chai.request.agent('http://localhost:3000')
afterEach(function() {
agent.close();
nock.cleanAll();
});
describe('User authorized', function() {
it('redirects to /dashboard', function() {
agent
.post('/authenticate')
.send({ email: 'realemail#gmail.com', password: 'RealPass' })
.then(function(res) {
expect(res).to.redirectTo('http://localhost:3000/dashboard');
expect(res.text).to.match(/Dashboard/);
})
.catch(function(e) { console.log(e); });
});
});
});
With this code the test passes, Am I missing something with nock?
=== EDIT ===
This is the code that I'm trying to test:
This is my login router (flashMessages is a custom middleware that helps with flash messages).
var loginService = require('../services/login');
var flashMessages = require('../utils/flash_messages').flashMessages;
var router = require('express').Router();
// check if user is logged in
var sessionChecker = function(req, res, next) {
if (req.session.auth && req.cookies.user_sid) {
res.redirect('/dashboard');
} else {
next();
}
};
router.get('/', sessionChecker, flashMessages, function(req, res, next){
res.render('login', {
title: 'Welcome',
errors: res.locals.flash.errors,
typeError: res.locals.flash.errorType,
});
});
router.post('/authenticate', function(req, res, next){
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Invalid email format').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.getValidationResult().then(function(result){
if (result.isEmpty()) {
loginService.authenticate(req.body).then(function(result){
if (result.authorized){
// success
req.session.auth = result;
req.session.auth.user = loginService.currentUser(result.jwt)
res.redirect('/dashboard');
} else {
// user not found error
req.session.flash = {
errors: [{msg: result.msg}],
errorType: 'anotherError'
};
res.redirect('/');
}
}).catch(function(e){
// server errors
req.session.flash = {
errors: [e],
errorType: 'anotherError'
};
res.redirect('/');
});
} else {
//validation errors
req.session.flash = {
errors: result.array(),
errorType: 'validationError'
};
res.redirect('/');
}
});
});
module.exports = router;
The login router uses a loginService, this is the part that works with the login:
var httpReq = require('../utils/http_requests');
module.exports.authenticate = function(params){
return new Promise(function(resolve, reject) {
httpReq.callToAPI(params, {
path: '/v1/authenticate',
method: 'POST'
})
.then(function(authorization) {
resolve(JSON.parse(authorization));
})
.catch(function(err) {
reject(err);
});
});
};
module.exports.currentUser = function(shaCode){
return JSON.parse(Buffer.from(shaCode.split('.')[1], 'base64').toString());
};
And finally I have a utils for http requests:
var http = require('http');
function createOptions(options) {
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'close'
};
if (options.jwt) { headers['Authorization'] = 'Bearer ' + options.jwt; }
return {
hostname: 'the.api.com',
port: 8080,
path: options.path,
method: options.method,
headers: headers
};
};
module.exports.callToAPI = function(params, options) {
reqObj = createOptions(options);
return new Promise(function(resolve, reject) {
body = [];
req = http.request(reqObj, function(res) {
res.on('data', function(chunk) {
body.push(chunk);
});
res.on('end', function() {
console.log(body.join(''));
resolve(body.join(''));
});
});
req.on('error', function(err) {
reject({ msg: "We're sorry, but something went wrong" });
});
if (params) { req.write(JSON.stringify(params)); }
req.end();
});
};
Any help will be appreciated.
Regards.