I am trying to add a REST API to my Meteor application using Restivus
I putted the following code in server folder of my Meteor application. Currently, I am trying to get the URL parameters.
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true
});
Api.addRoute('login/:id/:password', {authRequired: true}, {
get:{
action: function(){
var id = this.queryParams.id;
var password = this.queryParams.password;
return {
id: id,
password: password
}
}
}
});
I got this response
{
"status": "error"
"message": "API endpoint does not exist"
}
to my request:
http://localhost:3000/api/login?id=BGrZbGtKZZQYr9jDR&password=myPassword
the way you wrote the url login/:id/:password means it is expecting the url to be
http://localhost:3000/api/login/BGrZbGtKZZQYr9jDR/myPassword
However in your code, you are looking at the queryParams not urlParams:
var id = this.queryParams.id;
var password = this.queryParams.password;
You should choose one or the other:
use the code:
var id = this.urlParams.id;
var password = this.urlParams.password;
with the /login/:id/:password URL,
or use the route with just /login and pass the params as query params to use as you described:
http://localhost:3000/api/login?id=BGrZbGtKZZQYr9jDR&password=myPassword
var Api = new Restivus({
useDefaultAuth: true,
prettyJson: true
});
Api.addRoute('login', {authRequired: true}, {
get:{
action: function(){
var id = this.queryParams.id;
var password = this.queryParams.password;
return {
id: id,
password: password
}
}
}
});
Related
I created a custom authorizer for API Gateway so that i can pass the Facebook token and it will authenticate it using Cognito's Federated identity.
My problem is that the fb token seems to expire so I keep getting 403 errors. I am wondering if my approach is correct. Should I pass the Facebook token as part of the request header to API gateway on every REST API call or so I pass AWS identity id instead. Any feedback is appreciated. Thank you.
var AWS = require('aws-sdk');
var cognitoidentity = new AWS.CognitoIdentity();
exports.handler = (event, context, callback) => {
var params = {
IdentityPoolId: 'us-west-2:xxxxxxxxxxxxxxxxx’, /* required */
AccountId: ‘xxxxxxxxxxxxxxxxx,
Logins: {
'graph.facebook.com': event.authorizationToken //Token given by Facebook
}
};
console.log(event.methodArn);
cognitoidentity.getId(params, function(err, data) {
if (err) {
console.log(err);
callback(null, generatePolicy('user', 'Deny', event.methodArn));
}
else{
console.log("success");
callback(null, generatePolicy('user', 'Allow', event.methodArn));
}
});
};
var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17'; // default version
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke'; // default action
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
return authResponse;
}
I am using jasmine-protractor e2e framework to test one of our desktop App. I am totally new to this. So if something is not clear please ask.
This is how I am logging in to the server. Server uses SSO for authentication
describe('Protractor', function() {
beforeEach(function() {
browser.ignoreSynchronization = true
browser.get('https://myserver.com/login.html',60000);
});
it('hi', function () {
var btn = element(by.css('.loginFormGroup')).element(by.partialLinkText('Tegile'));
btn.click();
// browser.ignoreSynchronization = false;
var user = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_UsernameTextBox'));
user.sendKeys('user');
var pass = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_PasswordTextBox'));
pass.sendKeys('passwd');
var SignIn = element(by.css('.UsernamePasswordTable')).element(By.id('ctl00_ContentPlaceHolder1_SubmitButton'));
// browser.pause();
SignIn.click();
});
After this i would like to execute restapi on the same server. I want it to use same session if possible.
I tried to use request/request, but didnt work. Maybe i was not using it correctly.
You can simply use nodejs http module to make API calls.Look at below examples on how to make both GET and POST calls using http module.
GET call:
var http = require('http');
var headerObj = { Cookie : 'cookie-value' }
var options = {
host: "localhost" ,
path: "/someurl",
port: 8080,
headers : headerObj
};
var req= http.request(options,function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body);
});
}).on('error', function (err) {
console.log(err);
});
req.end();
POST call:
var http = require('http');
var data = { name : "somename" }; //data that need to be posted.
var options = {
"method": "POST",
"hostname": "localhost",
"port": 8080,
"path": "/someurl",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
cookie: 'cookie-value'
}
};
var req = http.request(options, function (res) {
var body = '';
res.on("data", function (chunk) {
body = body + chunk;
});
res.on("end", function () {
console.log(body);
});
});
req.write(JSON.stringify(data));
req.end();
I used SuperAgent to make REST API calls for my application,
below is the link describes the usage of superagent.
npm package superagent
I want to authenticate the user_name and password field. the user_name and password field is stored in database with php. how to get the data from the server in ionic project.
Thanks in advance.
You can create a service script that can send post data to PHP and receive a JSON response.
Post data should be sent as an object containing element name and values in the following format:
var myObj = {username: 'username', password:'password'};
Below is a service example:
yourApp.service('YourService', function ($q, $http) {
return {
login: function (data) {
var deferred = $q.defer(),
promise = deferred.promise;
$http({
url: 'http://www.example.com/yourPHPScript.php',
method: "POST",
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function (response) {
if (response.data.error.code === "000") {
deferred.resolve(response.data.appointments);
} else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error);
});
promise.success = function (fn) {
promise.then(fn);
return promise;
};
promise.error = function (fn) {
promise.then(null, fn);
return promise;
};
return promise;
}
};
});
From your login controller you call the following code to use the service (make sure you add the name of the service to your controller declaration)
YourService.login(loginData)
.then(function (data) {
// on success do sthg
}, function (data) {
//log in failed
// show error msg
});
I am new to QUnit and sinon.js and working to build tests for an ember-cli package. I am having problems getting sinon.spy(Ember.run, 'later') to work with the code below. inside the callback Ember.run.later is not being spied / has no .getCalls() etc...
How can I handle this type of test?
test('#authenticate rejects with invalid credentials', function() {
sinon.spy(Ember.run, 'later');
var jwt = JWT.create(),
expiresAt = (new Date()).getTime() + 60000;
var token = {};
token[jwt.identificationField] = 'test#test.com';
token[jwt.tokenExpireName] = expiresAt;
token = window.btoa(JSON.stringify(token));
var credentials = {
identification: 'username',
password: 'password'
};
App.server.respondWith('POST', jwt.serverTokenEndpoint, [
400,
{
'Content-Type': 'application/json'
},
'{"message":["Unable to login with provided credentials."]}'
]);
Ember.run(function(){
App.authenticator.authenticate(credentials).then(null, function(){
// Check that Ember.run.later was not called.
equal(Ember.run.later.getCall(0), null);
});
});
Ember.run.later.restore();
});
PS I currently am able to get this working by moving the sinon.spy and corresponding Ember.run.later.restore() to the module.setup() and module.teardown() methods respectively. Is there anything wrong with that that strategy other than it means they are spied for every test in my suite?
Thanks!
EDIT: Here is my authenticate method:
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = _this.getAuthenticateData(credentials);
_this.makeRequest(_this.serverTokenEndpoint, data).then(function(response) {
Ember.run(function() {
var tokenData = _this.getTokenData(response),
expiresAt = tokenData[_this.tokenExpireName];
_this.scheduleAccessTokenRefresh(expiresAt, response.token);
response = Ember.merge(response, { expiresAt: expiresAt });
resolve(_this.getResponseData(response));
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
I am new to node.js and want to send private message to my facebook friends. I used facebook-chat
but above framework is not supported.
Please give me sample code or example for the same.
I use facebook-chat-api module:
var login = require("facebook-chat-api");
login({
email: "your#mail.com",
password: "password"
}, function callback(err, api) {
if (err) return console.error(err);
var userId = "12345";
var msg = {
body: "Hey! That's Node.js!"
};
api.sendMessage(msg, userID);
});
Example above didn't work with (string) user nicknames - only with user ids.