AJAX get request does not recognize submitted data? - javascript

I have the following code ran on the client-side to access the properties of a user within the database.
firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) {
console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid)
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
$.ajax(
{
// Send token to your backend via HTTPS (JWT)
url: '/auth',
type: 'POST',
data: {token: idToken},
success: function (response){
var userID = response.userID
firebase.database().ref('/users/' + userID).once('value').then(function(snapshot) {
var industry = snapshot.val().industry
var company = snapshot.val().company
var firstname = snapshot.val().firstname
var email = snapshot.val().email
var source = snapshot.val().source
var phone = snapshot.val().phone
var password = snapshot.val().password
var lastname = snapshot.val().lastname
$.get(
{
url: '/members-area/'+userID,
data: {userID: userID,
industry: industry,
email: email},
success: function(response){
window.location = '/members-area/'+userID
}
})
My server-side code:
app.get('/members-area/:userID', function(req,res,next) {
res.render('members-area', { userID: req.params.userID, industry: req.params.industry, email: req.params.email})
})
However, when I try to access the 'industry' variable in pug, it shows undefined. As you can see I send it above within the GET ajax call so what is the problem? It's also weird because I logged to the console the variables names'right after the function snapshot and they were there. Also, mysteriously 'userID' shows up as a var with content but 'industry' and 'email' do not at all.

I don't quite know what you're trying to do but hopefully I can help some.
First off you don't need a second call to get the token. When you call signInWithEmailAndPassword firebase returns the user. So you can call getToken right away
firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) {
console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid)
console.log('we also got the token: ' + user.getToken());
...
You also seem to be posting to a route that isn't defined, and then you query a different route with get.
Also, mysteriously 'userID' shows up as a var with content but
'industry' and 'email' do not at all.
In your server side code your route is only defined with one parameter: userID. The line
app.get('/members-area/:userID', function(req,res,next)
Defines userID as a parameter, not the other 2 variables. So it makes sense that they're undefined.
What I think you're trying to do is:
firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) {
const userId = user.getToken();
firebase.database().ref('/users/' + userID).once('value').then(function(snapshot) {
$.post('/members-area/' + userId, snapshot.val(), function(data, status) {
console.log(data);
console.log(status);
});
});
And then in your server code:
app.post('/members-area/:userID', function(req,res,next) {
const theSnapshot = req.body;
res.send(theSnapshot)
});
I still don't understand why you would want to retrive information using client code from a database and then post it a server only to get it again. But maybe I am misunderstanding something :)
Its also very strange to see a get request that sends data, I'm pretty sure its against the specs. You usually want to use post to send data and then use get to ehm get the data :)

Related

AWS Cognito custom authentication flow - initiateAuth giving error

I am trying to make a custom authentication flow using AWS Cognito so that i can send MFA codes via email instead through the cognito triggers. I am using the initiateAuth() method to do this which is correct according to the documentation;
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#initiateAuth-property
My payload seems to be valid but when i try login with a user i get the error 't.getauthparameters is not a function'
I've had a look through some other stackoverflow posts but nothing is helping
Any ideas what is going wrong?
This is a snippet from my code below:
const payload = {
AuthFlow: 'CUSTOM_AUTH',
ClientId: 'my client id',
AuthParameters: {
USERNAME: $('input[name=username]').val(),
PASSWORD: $('input[name=password]').val(),
CHALLENGE_NAME: 'SRP_A'
}
};
cognitoUser.initiateAuth(payload, {
onSuccess: function(result) {
// User authentication was successful
},
onFailure: function(err) {
// User authentication was not successful
},
customChallenge: function(challengeParameters) {
// User authentication depends on challenge response
var verificationCode = prompt('Please input OTP code' ,'');
cognitoUser.sendCustomChallengeAnswer(verificationCode, this);
},
});
So i ended up finding out that initiateAuth() is not the correct method to use.
The right method to use is cognitoUser.authenticateUser() (since i am using SRP-based authentication then adding a custom challenge) - My updated code is below
This was a similar example that i followed to help me find the answer
I couldnt find very much online for doing it with just the Amazon Cognito Identity SDK so hopefully this is helpful for anyone doing the same!
AWSCognito.config.region = 'region';
var poolData = {
UserPoolId : 'user pool id',
ClientId : 'client id'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: $('input[name=username]').val(),
Pool: userPool,
};
var authenticationData = {
Username : $('input[name=username]').val(),
Password : $('input[name=password]').val(),
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.setAuthenticationFlowType('CUSTOM_AUTH');
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('success');
var resultStr = 'Login Successful';
console.log(resultStr);
$('#resultsSignIn').html(resultStr);
},
onFailure: function(err) {
alert(err);
},
customChallenge: function(challengeParameters) {
// User authentication depends on challenge response
var verificationCode = prompt('Please input OTP code' ,'');
cognitoUser.sendCustomChallengeAnswer(verificationCode, this);
},
});
return false;`
A downside to the authenticateUser() method is that you won't be able to get user's input mid-execution during the authenticateUser workflow (i.e, having to use prompts in the callbacks for customchallenge etc). I believe initiateAuth() would solve this issue.
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html

Creating Firebase User and simultaneously adding data into database

I want to have my create users to be added into my database by their user uid when i sign them up from my firebase.
currently my code is working , just i dont understand why when my data is save into my firebase, the name (which is suppose to be the created user uid) shows "undefined". but the data that is grabbed and saved is correct.
My firebase database which shows undefined: https://imgur.com/ATRsmKe
My JS code which i am trying to save and create user:
/*Show Login User*/
// Firebase Variables
var auth = firebase.auth();
$(document).ready(function () {
//Pass parameter from form to Firebase
$('.addpic').on('submit', event => {
event.preventDefault();
const name = $('#name').val();
const hp = $('#hp').val();
const email = $('#email').val();
const password = $('#password').val();
const role = $('#role').val();
//Firebase user authentication
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => {
//set data into User database
firebase.database().ref('Admin/Person In Charge' + "/" + user.uid).set({
Name: name,
ContactNo: hp,
Email: email,
Password: password,
Role: role
}).then(success => {
console.log(user);
window.alert("Registered");
window.location = "user.html";
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
});
});
});
I want my data to be saved under the UID of the created user. I tried all possible solutions, but none work for me.
You should take a look at the return type of createUserWithEmailAndPassword. If I'm reading the docs correctly, it returns an instance of firebase.auth.UserCredential, not an actual user. I think you need to actually drill down one more level into that credential object and get the user.uid.
Example
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(userCredential => {
//set data into User database
firebase.database().ref('Admin/Person In Charge' + "/" + userCredential.user.uid).set({
Name: name,
ContactNo: hp,
Email: email,
Role: role
}).then(success => {
console.log(user);
window.alert("Registered");
window.location = "user.html";
});
})
You could figure this out in the future by inspecting the value of your user in your then via a console.log().

Async api request with db request in js mocha?

I build nodejs server, and now I'm testing it with mocha.
I have problem with async requests. I send my object to API, and then check record for with object in DB. I need use only co library and generators.
There's error:
TypeError: Cannot read property 'id' of null
It depends on insertUser object is null, but I don't know why object from database is null.
API works fine, and sequilize works fine.
it('it should POST a user', () => {
return co(function *() {
let user = {
name: "testInsertUser",
password: "12345"
};
let res = yield chai.request(server)
.post('/api/users')
.send(user);
res.should.have.status(HTTPStatus.OK);
res.body.should.be.a('object');
res.body.should.have.property('name').eql(user.name);
res.body.should.not.have.property('password');
//Find user in db
let insertUser =
yield models.User.findOne({
where: {
name: user.name,
password: user.password
}
});
res.body.should.have.property('id').eql(insertUser.id);
});
});
I solve my problem.
Code is fine, but password in db is hashing and I check hash password and order password

Pouchdb database creation no_db_file

I'm trying doing the following: I have a local database (using PouchDB), I check if user is logged in (with pouchdb-authentication login function) and if true I sync the locale db with the remote one.
Unfortunately, when I try to create a new database on CouchDB (I want one db for every user) I always get the error {"error":"not_found","reason":"no_db_file"}. I saw this is a common error described in PouchDB documentation (https://pouchdb.com/guides/databases.html#remote-databases) but CORS is enabled and I can't figure out where is the problem.
My couchdb configuration is:
I do the login as follow:
var user = {
name: 'name',
password: 'password'
};
var url = "http://ip/";
var pouchOpts = {
skipSetup: true
};
var ajaxOpts = {
ajax: {
headers: {
Authorization: 'Basic ' + window.btoa(user.name + ':' + user.password)
}
}
};
var db = new PouchDB(url+'auth', pouchOpts);
db.login(user.name, user.password, ajaxOpts).then(function() {
return db.allDocs();
}).then(function(docs) {
//HERE I TRY TO CREATE THE NEW DATABASE
pouchDBService.sync(url+"newDatabase", user);
}).catch(function(error) {
console.error(error);
});
And, in my pouchDBService I have:
var database;
//I call this function as app starts
this.setDatabase = function(databaseName) {
database = new PouchDB(databaseName, {
adapter: 'websql'
});
}
this.sync = function(remoteDatabase, user) {
var remoteDB = new PouchDB(remoteDatabase, {
auth: {
username: user.name,
password: user.password
},
skip_setup: true //without this I get the login popup! Why if I'm passing the auth params???
});
remoteDB.info().then(function (info) {
console.log(info);
database.sync(remoteDB, {live:true, retry: true})
})
}
Is there something wrong? Any help is appreciated.
Thanks
To create databases on the CouchDB server, you need to be an admin. You could create a small custom API on the server for this (e.g. with a small node http server), or use the couchperuser plugin for CouchDB.

Azure Mobile Services - Getting more user information

I inherited a Windows 8 application that is written with XAML. So in C# when I make this call
user = await MobileServices.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
(This is for Azure Mobile Services)
The user object is ONLY giving me the Token and the MicrosoftAccount:..............
In order to get to authenticate people, I need to be able to see WHO is requesting access...
I looking at articles like below, but I seem to be missing something? Is this javascript in the article something I would have to write in Node.js?
Example article:
http://blogs.msdn.com/b/carlosfigueira/archive/2013/12/12/expanded-login-scopes-in-azure-mobile-services.aspx
Currently to be able to get more information about the logged in user, you need to make a second call to the service to retrieve the user info. You don't really need to ask for additional login scopes (the topic of the post you mentioned) to retrieve the user name, since that is given by default for all the providers.
This post should have the code you need to write in the server side (node.js) to get more information about the logged in user. The TL;DR version is given below:
On the server side: add this custom API (I'll call it "userInfo"; set the permission of GET to "user", and all others to admin):
exports.get = function(request, response) {
var user = request.user;
user.getIdentities({
success: function(identities) {
var accessToken = identities.microsoft.accessToken;
var url = 'https://apis.live.net/v5.0/me/?method=GET&access_token=' + accessToken;
var requestCallback = function (err, resp, body) {
if (err || resp.statusCode !== 200) {
console.error('Error sending data to the provider: ', err);
response.send(statusCodes.INTERNAL_SERVER_ERROR, body);
} else {
try {
var userData = JSON.parse(body);
response.send(200, userData);
} catch (ex) {
console.error('Error parsing response from the provider API: ', ex);
response.send(statusCodes.INTERNAL_SERVER_ERROR, ex);
}
}
}
var req = require('request');
var reqOptions = {
uri: url,
headers: { Accept: "application/json" }
};
req(reqOptions, requestCallback);
}
});
}
On the client side, after a successful login, call that API:
user = await MobileServices.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
var userInfo = await MobileServices.MobileService.InvokeApiAsync(
"userInfo", HttpMethod.Get, null);
userInfo will contain a JObject with the user information. There is an open feature request to make this better at http://feedback.azure.com/forums/216254-mobile-services/suggestions/5211616-ability-to-intercept-the-login-response.

Categories