Cognito WebService from Amazon crashing on Apache server - javascript

I'm doing an user management with Cognito webservice from Amazon.
Everything is running smoothly on local but everything crash when I use it on a Wamp server and I can not figure out why.
I'm doing as of now my registration directly on my controller like this :
AWSCognito.config.region = 'eu-west-1';
var cognitoUser;
var poolData = {
UserPoolId: 'eu-west-1_XXXXXXXX',
ClientId: '4dkagd3xxxxxxxxxxxxxx'
};
AWSCognito.config.credentials = new AWSCognito.CognitoIdentityCredentials({
IdentityPoolId: 'eu-west-1:xxxxxx-xxxx-xxx-xxxxx-xxxxxxxxxx',
});
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData)
userPool.signUp($scope.username, $scope.password, attributeList, null, function(err, result) {
if (err) {
alert(err);
return;
} else {
alert('successfully registered');
routeService.goToView('/users-confirmation');
}
});
The mysterious thing is that I never get any of the two alerts (error or success) and I'm directly redirected to my main page...
Does anyone know why and how can I fixe it ?

Related

Unable to connect with SQL Server using Node.js

I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
var Connection = require('tedious').Connection;
// config for your database
var config = {
user: "****",
password: "*****",
server: "abc",
database: "xyz"
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from employee;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.
I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.

Why is this callback function not executing?

I have been having this issue. It seems like it works for a while and then breaks without much rhyme or reason to it.
router.get('/home/', function(req, res, next) {
var code = req.query.code;
console.log("acquired code from SC");
req.SC.authorize(code, function(err, accessToken) {
if ( err ) {
throw err;
} else {
console.log("traded code for access token");
req.session.oauth_token = accessToken;
// Client is now authorized and able to make API calls
//res.render('home', { token: accessToken });
soundcloud.getLoggedInUser(accessToken, function(user){
console.log("done getting user from SC");
});
}
});
});
Here is the getLoggedInUser function.
//get data for the user who is logged in
function getLoggedInUser(accessToken, done){
var href = 'https://api.soundcloud.com/me?oauth_token=' + accessToken;
getRequest(href, done);
}
//used for get requests to soundcloud API
function getRequest(href, done){
console.log(href);
requestify.get(href).then(function(response){
console.log(done);
done(response.getBody());
});
}
Here is the output.
acquired code from SC
traded code for access token
https://api.soundcloud.com/me?oauth_token=
[Function]
I'm guessing this is a problem with my node / express setup rather than a problem with this code itself. Any ideas?

Send REST calls from Node server to third party application using OAuth

I'm implementing a server that handles chat messages. In some cases I want to access data from a JIRA instance. I'm using passport-atlassian-oauth strategy for authenticating with JIRA and BearerStrategy for requests, but my issue is that the authentication is only valid in the browser after a user has given "My Server" read and write access to JIRA. In many guides they just call res.redirect('/successfulLogin') or something similar after a successful authentication, but I would instead like to do a rest call to JIRA, process the data and send it to my connected client application.
How do I do that?
I'm completely new to all this and everything just spins around in my head. I save and have access to the token used for authentication and when I for instance navigate to .../test/access_token=?[token] in my browser it works.
passport.use(new BearerStrategy(
function(token, done) {
// Find user by token
client.smembers('access_token:' + token, function(err, replies) {
if (err) {
return done(err);
}
// if user found
// TODO: yet again, hard coded for one
if (replies.length > 0) {
console.log('SHOULD BE 1:', replies[0]);
client.hgetall('users:' + replies[0], function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
return done(null, user, {scope: 'all'});
});
}
});
}
));
As you can see it's hard coded for just one user and I'm using Redis as a "database".
passport.use(new AtlassianOAuthStrategy({
applicationURL: 'http://localhost:2990/jira',
callbackURL: '/auth/atlassian-oauth/callback',
consumerKey: RsaPublicKey,
consumerSecret: rsaPrivateKey,
clientId: 'MyBot'
},
function(accessToken, tokenSecret, profile, done) {
// Find user
client.hgetall('users:1', function(err, user) {
if(err) {
return done(err);
}
// user not found
if(!user) {
// create new user, no worries!
// TODO: HARD CODED FOR ONE USER
client.hmset('users:1', 'id', profile.id, 'access_token', accessToken, function(err, res) {
client.sadd('id:admin', '1');
client.sadd('access_token:'+ accessToken, '1');
client.hgetall(profile.id, function(err, user) {
return done(null, user);
});
});
} else {
// Update access token!
client.hmset(profile.id, 'access_token', accessToken, function() {
client.sadd('access_token:' + accessToken, '1', function() {
client.hgetall(profile.id, function(err, result) {
return done(null, user);
});
});
});
}
});
}
));
Here's the rest
app.get('/auth/atlassian-oauth',
passport.authenticate('atlassian-oauth', {session: false, scope: []}),
function(req, res) {
console.log('- Function: /auth/atlassian-oauth - should not be called)');
});
app.get('/auth/atlassian-oauth/callback',
passport.authenticate('atlassian-oauth', {session: false, failureRedirect: '/login'}),
function(req, res) {
console.log('- Function: /auth/atlassian-oauth/callback - Authentication successful!', req.user.access_token);
// Update access token!
// Should I even do this? Shouldn't I already have the correct token?
client.hmset('users:1', 'access_token', req.user.access_token, function() {
client.sadd('access_token:' + req.user.access_token, '1', function() {
client.hgetall('users:1', function(err, result) {
res.redirect('/test?access_token=' + req.user.access_token);
});
});
});
});
So now that you've seen some relevant (just tell me and I'll post more) code, how do I send a rest call to JIRA without getting a 401? :)
EDIT: Any help appreciated! You would make me really happy if you just can point me into the right direction!
Ok. I figured it out! First of all you want to save both you access token and token secret to you db in AtlassianOAuthStrategy. Second, in order to send a REST call to a third party service you can just use http request with OAuth:
var request = require('request');
var oauth = {
signature_method : 'RSA-SHA1',
consumer_key : RsaPublicKey,
private_key : rsaPrivateKey,
token : [get access_token from you db],
token_secret : [get token_secret from you db]'
};
var url = 'http://localhost:2990/jira/rest/api/2/issue/' + id;
request.get({url:url, oauth:oauth, json:true}, function (e, r, issue) {
console.log(issue)
});
Now that everything is working I'm going to start refactoring and reading some more documentation in order to make the design prettier and figure out how to use Redis properly :)

how to redirect using pure javascript in an express application

I have a node.js/express/mysql/angular.js application and I'm trying to redirect a user after they login, on the server side. This is the server-side controller and I cannot figure out how to redirect the user to another page. Ive tried res.render, res.redirect, window.location.href with no success. Errors I'm getting with res.render() are 'No default engine was specified and no extension was provided.' window.location.href says window is undefined. And res.redirect() allows me to console.log the html of the page I want to direct too. Any help is greatly appreciated, Thanks!
var Query = require('./../models/query.js');
module.exports = (function(){
return {
show: function(req,res) {
req.getConnection(function(err,connection){
connection.query('SELECT * FROM users',function(err,rows){
res.json(rows);
});
});
},
add: function(req,res){
var newUser = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created_at: req.body.created_at
};
var table = "users";
Query.insert(req,newUser,table,function(err,results){
if(err) return res.json(err);
Query.find(req,table,function(err,results){
if(err) return res.json(err);
res.json(results);
});
});
},
login: function(req,res) {
var input = req.body;
console.log("got here", input);
req.getConnection(function(req, connection) {
// console.log("got connections",connection);
connection.query('SELECT * FROM users WHERE email = ?',input.email, function(err, rows) {
if (err) {
console.log("User doesn't exist: %s", err);
res.redirect('/', { data:"failed"});
} else {
if (input.password == rows[0].password) {
console.log("User password is matched");
*** success redirect right here ****
res.redirect('/static/taxonomer'+'.html');
} else {
console.log("failed here", rows[0].password);
res.redirect( '/', { data:"failed"});
}
}
});
});
}
};
})();
Without seeing your routes I am guessing that login method on the above controller corresponds to a POST route. For example,
app.post('some/login/route', theAboveController.login)
Therefore, the redirect is controlled on the client side.
So, make then following changes:
1) Use res.send to send a redirect url as a string to the client. For example,
res.send('/static/taxonomer'+'.html')
2) Then on the client side in your success callback, change the location to the url you received from the res.send method. For example,
$http.post('/some/login/route', data).then(function(response) {
$window.location.href = response;
}, errorCallback);
Express's docs are pretty good here: http://expressjs.com/api.html#res.redirect
res.redirect('https://stackoverflow.com'); will redirect them to that specific URL.
res.redirect('/foo'); will redirect to a specific URL
res.redirect('back'); will redirect to the referrer. So you can do something like a middleware that redirects to /login and then the login finishes successfully and it goes back to the original path.

Apigee error when behind gateway proxy

I'm creating an HTML 5 client to app services, however our app services are enterprise so behind an apigee gateway proxy ( not directly through api.usergrid.com).
I'm initializing like this:
$(function() {
var client = new Apigee.Client({
orgName:'myorg',
appName:'sandbox',
monitoringEnabled:false,
URI:'https://prod.OURURL.com/appservices/v1'
});
var username = "myusername";
var password = "mypass";
client.login(username, password,
function (err) {
if (err) {
console.log('There was an error logging you in.');
} else {
//login succeeded
client.getLoggedInUser(function(err, data, user) {
if(err) {
//error - could not get logged in user
console.log("error on lvl2");
} else {
if (client.isLoggedIn()){
appUser = user;
console.log('data')
// showFullFeed();
}
}
});
}
}
);
});
I'm immediately getting:
Error: Apigee APM configuration unavailable.
and then of course:
There was an error logging you in.
using the trace tool in the proxy I can see this errorr on the request to /proxy_path/org/app/apm/apigeeMobileConfig
{"timestamp":"1398263318219","duration":"0","error":"illegal_argument","exception":"java.lang.IllegalArgumentException","error_description":"JSON source MUST not be null"}
of course this is all called by the above code.
thank you in advance.
[EDIT FOR MORE INFORMATION]
Just tested with my own private org, so not setting the options.URI param, the second log message is normal as I had not created the app user, however the initialization is NOT working on the enterprise org, so this:
var client = new Apigee.Client({
orgName:'myorg',
appName:'sandbox',
monitoringEnabled:false,
URI:'https://prod.OURURL.com/appservices/v1'
});
is returning the APM error.
It seems you need to enable some of the options in the app services app ( inthe configuration option) for this api call to return something, thus enabling the sdk.

Categories

Resources