I am using this code to authenticate on Outlook Calendar (Oauth2) and then post an event to my calendar. I'm getting an error that after my first authentication the token is expired so O can't post on the calendar. If someone can help to find the error in my code :)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var moment = require('moment');
var querystring = require('querystring');
var outlook = require('node-outlook');
var microsoftGraph = require("#microsoft/microsoft-graph-client");
var currentToken;
var authHelper = require('./authHelper');
// 3- Configure express
// Set up rendering of static files
app.use(express.static('static'));
// Need JSON body parser for most API responses
app.use(bodyParser.json());
// Set up cookies and sessions to save tokens
app.use(cookieParser());
app.use(session(
{ secret: '************',
resave: false,
saveUninitialized: false
}));
// 4- Home page
app.get('/', function(req, res) {
res.write('<a id="signin-button" class="ms-Button ms-Button--primary"
href="'+authHelper.getAuthUrl()+ '"><span class="ms-Button-label">Click here
to sign in</span></a>');
res.end();
});
app.get('/authorize', function(req, res) {
var authCode = req.query.code;
if (authCode) {
console.log('');
console.log('Retrieved auth code in /authorize: ' + authCode);
authHelper.getTokenFromCode(authCode, tokenReceived, req, res);
}
else {
// 5- redirect to home
console.log('/authorize called without a code parameter, redirecting to
login');
res.redirect('/');
}
});
// 6- if it can't take the token
function tokenReceived(req, res, error, token) {
if (error) {
console.log('ERROR getting token:' + error);
res.send('ERROR getting token: ' + error);
}
else {
// 7- save tokens in session
req.session.access_token = token.token.access_token;
req.session.refresh_token = token.token.refresh_token;
req.session.email = authHelper.getEmailFromIdToken(token.token.id_token);
res.redirect('/logincomplete');
}
}
// 8- login complete
app.get('/logincomplete', function(req, res) {
var access_token = req.session.access_token;
var refresh_token = req.session.access_token;
var email = req.session.email;
currentToken = access_token;
var http = require("https");
var options = {
"method": "POST",
"hostname": "graph.microsoft.com",
"port": null,
"path": "/v1.0/me/events",
"headers": {
"authorization": "Bearer 'access_token'",
"content-type": "application/json",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write("{\n \"subject\": \"My M\",\n \"start\": {\n \"dateTime\":
\"2017-11-30T15:34:40.942Z\",\n \"timeZone\": \"UTC\"\n },\n \"end\":
{\n \"dateTime\": \"2017-12-07T15:34:40.942Z\",\n \"timeZone\":
\"UTC\"\n }\n}");
req.end();
});
// Start the server
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Related
My code is not working, I can't figure out why and it keeps giving me a 401 meaning the API key is missing so I don't know how this is happening and I would like to figure out what my problem is on this piece of code?
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var data = {
members: [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
url: "https://us20.api.mailchimp.com/3.0/lists/listId"
method: "POST",
headers: {
"Authorization": "mkouk24 Api Key"
},
body: jsonData
};
request(options, function(error,response,body){
if (error) {
console.log(error);
} else {
console.log(response.statusCode);
}
});
});
app.listen(3000, function() {
console.log("Server is running on port 3000!");
});
First of all, according to the documentation, I think you need to use app.use(bodyParser.json()) in order to pass parameters in post request.
Second, you should generate an API token from MailChimp and add it here Authorization": "mkouk24 Api Key"
More on that on this link: https://mailchimp.com/help/about-api-keys/
I'm building web app using Node.js Express.js for the server-side and Angular 6 SPA for the client.
Using the simple Express.js code, below, I've successfully authenticated a user via SAML2.js ADFS and now I want to access the user on the client side Angular SPA. How do I do that?
I found a similar setup here, but there is not an answer there and its a bit dated.
var saml2 = require('saml2-js');
var fs = require('fs');
var express = require('express');
var https = require('https');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
// Create service provider
var sp_options = {
entity_id: "https://localhost:44301/",
private_key: fs.readFileSync("key.pem").toString(),
certificate: fs.readFileSync("certificate.crt").toString(),
assert_endpoint: "https://localhost:44301/assert",
force_authn: true,
auth_context: { comparison: "minimum", class_refs: ["urn:oasis:names:tc:SAML:2.0:ac:classes:password"] },
nameid_format: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
sign_get_request: false,
allow_unencrypted_assertion: true
};
var sp = new saml2.ServiceProvider(sp_options);
// Create identity provider
var idp_options = {
sso_login_url: "https://mmusmaadfs.company.com/adfs/ls/",
sso_logout_url: "https://mmusmaadfs.company.com/adfs/ls/",
certificates: [fs.readFileSync("./2018ADFSSigningBase64Cert.cer").toString()],
force_authn: true,
sign_get_request: false,
allow_unencrypted_assertion: true
};
var idp = new saml2.IdentityProvider(idp_options);
// ------ Define express endpoints ------
// Endpoint to retrieve metadata
app.get("/metadata.xml", function(req, res) {
res.type('application/xml');
res.send(sp.create_metadata());
});
// Starting point for login
app.get("/login", function(req, res) {
sp.create_login_request_url(idp, {}, function(err, login_url, request_id) {
if (err != null)
return res.send(500);
res.redirect(login_url);
});
});
// Assert endpoint for when login completes
app.post("/assert", function(req, res) {
var options = {request_body: req.body};
sp.post_assert(idp, options, function(err, saml_response) {
if (err != null){
console.log("got here");
console.log(err);
return res.send(err);
}
// Save name_id and session_index for logout
// Note: In practice these should be saved in the user session, not globally.
name_id = saml_response.user.name_id;
session_index = saml_response.user.session_index;
res.send("Hello " +name_id +".");
//res.send("Hello #{saml_response.user.name_id}!");
});
});
// Starting point for logout
app.get("/logout", function(req, res) {
var options = {
name_id: name_id,
session_index: session_index
};
sp.create_logout_request_url(idp, options, function(err, logout_url) {
if (err != null)
return res.send(500);
res.redirect(logout_url);
});
});
var httpsOptions = {
key: fs.readFileSync('./key.pem')
, cert: fs.readFileSync('./certificate.crt')
}
var httpsServer = https.createServer(httpsOptions, app);
// app.listen(44301,console.log("App on 44301"));
httpsServer.listen(44301,console.log("App on 44301"));
I'm trying to use body-parse version 1.18.3 with express to parse a json post. In app.js I've included it like so
app.js
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
...
//App setup
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
app.set('trust proxy', 1) // trust first proxy
// Use the session middleware
app.use(session({ secret: 'secretletters', cookie: {}}))
app.post('/', jsonParser, function (req, res) {
console.log(req.body);
if (req.session.username) {
} else {
}
res.send({'status': 'ok'})
});
and in my script on the frontend send a username back to it
$('.login-btn').click(function() {
let username = $('.username').val();
if (username == '') {
$('.login-error').removeClass('hidden');
return null;
}
//if passed hide error
$('.login-error').addClass('hidden');
var data = {
'username': username
}
$.ajax({
url: "/",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
success: function(response){
},
error: function(xhr){
},
});
/* End Ajax Call */
});
It send the username successfully, here's a screenshot of the results of the post request from the network tools
the bug is when on console.log(req.body); on app.post I get back and empty {} dict
I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue
I am using formdata to have multipart data and for that i am using busboy-body-parser. But somehow the body is not accessible and the value is undefined.
app.js
var express = require('express');
var mongoose = require('mongoose');
var Uploader = require('s3-image-uploader');
var config = require('./config.js');
var busboyBodyParser = require('busboy-body-parser');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var multer = require('multer');
// var uuid = require("uuid");
var app = express();
var morgan = require('morgan');
var path = require('path');
var port = process.env.PORT || 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var login = require('./controller/login.js');
var itemInfo = require('./controller/item_info.js');
var review = require('./controller/reviews.js');
var popularitems = require('./controller/popularitems.js');
var foodtruck = require('./model/datafoodtruck');
var truckData = require('./model/foodtruck.js');
var webToken = require('./controller/webtoken.js');
var userprofile = require('./controller/userprofile.js');
var notificationdata = require('./model/dataNotifications.js');
var notification = require('./controller/notifications.js');
var foodtruckItemList = require('./controller/item_list_foodtruck.js');
var orderList = require('./controller/orders_foodtruck.js');
var ordermanagement = require('./controller/ordermanagement.js');
var db = mongoose.connect(config.local_mongo_url);
mongoose.connection.once('connected', function() {
console.log("Connected to database")
// foodtruck.save();
// notificationdata.save();
});
app.use(bodyParser.urlencoded({
extended: true
}));
// app.use(multipartyMiddleware);
app.post('/testupload', function(req, res) {
// var file = req.files.file;
// var stream = fs.creatReadStream(req.files.file.path);
// return s3fsImpl.writeFile(file.originalFilename, stream).then(function() {
// console.log(file);
// return;
// fs.unlink(file.path, function(err) {
// if (err) console.error(err);
// res.json({
// status: '200',
// message: 'uploaded'
// });
// });
// })
res.connection.setTimeout(0);
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/food-3-mdpi.png',
name: 'food-3-mdpi.png'
},
function(data) { // success
// console.log('upload success:', data);
res.json({
status: '200',
message: 'image uploaded successfully'
});
},
function(errMsg, errObject) { //error
// console.error('unable to upload: ' + errMsg + ':', errObject);
res.json({
status: '404',
message: 'image is not uploaded successfully'
});
});
});
// app.use('/public/images', express.static(__dirname + '/public/images'));
app.use(morgan('dev'));
// app.use(bodyParser.urlencoded({extended: true}));
app.get('/foodtrucklist', foodtrucklist);
app.post('/itemInfo', itemInfo.itemInfo);
app.post('/likeitem', itemInfo.likeItem);
app.get('/popularitems', popularitems);
app.post('/notification', notification);
app.post('/submitreview', review.addreview);
app.post('/getreview', review.getReview);
app.post('/addOrder', ordermanagement.addOrder);
app.post('/orderHistory', ordermanagement.orderHistory);
app.post('/cancelOrder', ordermanagement.cancelOrder);
app.post('/getOrderStatus', ordermanagement.getOrderStatus);
app.post('/rateOrder', ordermanagement.rateOrder);
app.post('/updateUser', userprofile.updateUser);
app.post('/getUserInfo', userprofile.getUserInfo);
app.post('/createToken', webToken.createToken);
app.post('/checkToken', webToken.checkToken);
app.post('/itemList', foodtruckItemList.getItemList);
app.post('/updateItemStatus', foodtruckItemList.updateItemStatus);
app.post('/addItem', foodtruckItemList.addItem);
app.post('/deletItem', foodtruckItemList.deletItem);
app.post('/orderlist', orderList.getOrderList);
app.post('/statusOrderlist', orderList.getStatusOrderList);
app.post('/updateorder', orderList.updateOrder);
app.use(bodyParser.urlencoded({extended: false}));
app.use(busboyBodyParser({ limit: '50mb' }));
app.post('/login', function(req,res) {
console.log("body" + req.body.email_id + "file" + req.files);
});
app.listen(port, function() {
console.log('express listining on port' + port);
});
so, how can I access body parameters even I tried to use multer but the problem was same.
Busboy has parameters inside busboy.on('field') event
We explicitly have to attach it to req.body before Busboy.on('finish') event like so :
busboy.on('field', (fieldName, value) => {
req.body[fieldName] = value
})
This will attach parameters to req.body as it should be !