How to Get Params from Http Post and Insert - javascript

I am trying to capture user entered credentials and use them as a parameter to query a database. Unfortunately, I am a little lost on how to code that process. I am using angular,express, node, jQuery, and html. I am not very experienced with angular, node, and jQuery, so forgive me if this is something very simple; I am here to learn.
Here is the html where the forms live:
<!DOCTYPE html >
<html ng-app="token">
<%include header%>
<%include navbar%>
<div ng-controller="TokenCtrl">
<form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm = {}">
<div class="form-group">
<label>email</label>
<input type="email" name="email" ng-model="loginForm.email" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>password</label>
<input type="password" name="password" ng-model="loginForm.password" required="required" class="form-control"/>
</div>
<button class="btn btn-primary btn-lg" ng-click="handleLoginBtnClick()">Sign in</button>
</form>
</div>
</body>
Here is the JS for the TokenCtrl and token module, which is a derivative of ng-token-auth:
var a = angular.module('token', ['ng-token-auth']);
a.config(function($authProvider) {
// the following shows the default values. values passed to this method
// will extend the defaults using angular.extend
$authProvider.configure({
apiUrl: '/users',
tokenValidationPath: '/auth/validate_token',
signOutUrl: '/auth/sign_out',
emailRegistrationPath: '/auth',
accountUpdatePath: '/auth',
accountDeletePath: '/auth',
confirmationSuccessUrl: window.location.href,
passwordResetPath: '/auth/password',
passwordUpdatePath: '/auth/password',
passwordResetSuccessUrl: window.location.href,
emailSignInPath: '/auth/sign_in/:email/:password',
storage: 'cookies',
forceValidateToken: false,
validateOnPageLoad: true,
proxyIf: function() { return false; },
proxyUrl: '/proxy',
omniauthWindowType: 'sameWindow',
tokenFormat: {
"access-token": "{{ token }}",
"token-type": "Bearer",
"client": "{{ clientId }}",
"expiry": "{{ expiry }}",
"uid": "{{ uid }}"
},
cookieOps: {
path: "/",
expires: 9999,
expirationUnit: 'days',
secure: false,
domain: 'domain.com'
},
createPopup: function(url) {
return window.open(url, '_blank', 'closebuttoncaption=Cancel');
},
parseExpiry: function(headers) {
// convert from UTC ruby (seconds) to UTC js (milliseconds)
return (parseInt(headers['expiry']) * 1000) || null;
},
handleLoginResponse: function(response) {
return response.data;
},
handleAccountUpdateResponse: function(response) {
return response.data;
},
handleTokenValidationResponse: function(response) {
return response.data;
}
});
});
a.controller('TokenCtrl', function($scope, $auth) {
$scope.handleRegBtnClick = function() {
$auth.submitRegistration($scope.registrationForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handlePwdResetBtnClick = function() {
$auth.requestPasswordReset($scope.pwdResetForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handleLoginBtnClick = function() {
$auth.submitLogin($scope.loginForm)
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
$scope.handleSignOutBtnClick = function() {
$auth.signOut()
.then(function(resp) {
// handle success response
})
.catch(function(resp) {
// handle error response
});
};
});
On the run of this function, it leads to this url:
'/auth/sign_in/:email/:password'
Using Express, I route this url to another function. Here is the route code:
app.post('/users/auth/sign_in/:email/:password', routes.verifyusers);
Which leads to,
exports.verifyusers= function(req, res) {
models.user.find({
where: {
email: req.params.email,
password: req.params.password
}
}).then(function(user) {
if(user) {
console.log("alright !")
};
});
};
When the code runs, this is what I get in the console:
Executing (default): SELECT "id", "username", "email", "password", "createdAt", "updatedAt" FROM "users" AS "user" WHERE "user"."email" = ':email' AND "user"."password" = ':password' LIMIT 1;
:email
:password
This is result is irrespective to the form data.

I think the problem is coming from emailSignInPath: '/auth/sign_in/:email/:password',
You should try with
// config
emailSignInPath: '/auth/sign_in'
// route declaration
app.post('/users/auth/sign_in', routes.verifyusers);
// route action
exports.verifyusers = function(req, res) {
models.user.find({
where: {
email: req.body.email,
password: req.body.password
}
}).then(function(user) {
if(user) {
console.log("alright !")
};
});
};
ps: don't forget to declare a body parser in your app app.use(express.bodyParser())

Related

MethodOverride PUT not working

I am using Node.js, Express and MethodOverride to try and have a form update only 1 part of a model (my user model).
User model:
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
profile: {
name: { type: String, default: 'Company Name' },
location: { type: String, default: 'Location' },
website: { type: String, default: 'Your Website' },
picture: { type: String, default: '' }
},
assetNumPre: { type: String, default: 'test' }, // this is the one I want to change
});
module.exports = mongoose.model('User', userSchema);
HTML form:
<form role="form-inline"action="/dashboard/settings/assetNumber?_method=PUT" method="POST">
<div class="col-md-3">
<div class="form-group">
<label for="prefix" class="control-label">Prefix for Asset Number</label>
<br>
<small>Any alphanumeric characters to a limit of 6</small>
<input type="text" class="form-control" id="prefix" name="prefix" placeholder="Prefix max 6 characters" maxlength="6" value="{{ prefix }}">
</div><!-- Prefix for Asset Number-->
<br>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Then route:
app.put('/dashboard/settings/assetNumber',
setRender('dashboard/settings/assetNumbers'),
setRedirect({auth: '/login'}),
isAuthenticated,
dashboard.getDefault,
(req, res) => {
var prefix = req.body.prefix;
console.log(req.params);
User.findByIdAndUpdate({_id: req.params.user_id}, prefix, function(err, UpdatedUser) {
if (err) {
res.send(err);
}
console.log(UpdatedUser);
});
res.locals.prefix = req.user.assetNumPre;
});
One thing my route is missing is req.user.assetNumPre which is where I need to save it but I have no clue how to do this PUT request. Docs are not helping much either.
I got the route from a Stack Overflow example a few days ago and can't find the link to it. My app.js had method override working because I have done DELETE requests already. The model has the correct field and has a default test value that shows up in my show page.
You're calling this:
User.findByIdAndUpdate({_id: req.params.user_id}, prefix...
But prefix is only the value:
var prefix = req.body.prefix;
findByIdAndUpdate takes an Object, not a value, to update a specific field.
So try:
User.findByIdAndUpdate({_id: req.params.user_id}, { assetNumPre: prefix }...
Here is the fixed route:
app.put('/dashboard/settings/assetNumber',
setRedirect({auth: '/login', success: '/dashboard/settings/assetNumber', failure: '/dashboard/settings/assetNumber'}),
isAuthenticated,
(req, res) => {
User.findById(req.user.id, function(err, user) {
if (err) return (err);
user.assetNumPre = req.body.prefix || 'pre';
user.save(function(err) {
if (err) return (err);
req.flash('success', { msg: 'Asset Number Prefix updated.' });
res.redirect(req.redirect.success);
});
});
res.locals.prefix = req.user.assetNumPre;
});
So a few things changed that were not part of the issue. I figured out I need to just set the data inside the callback function. Then do a user.save.

How do I render a handlebars layout in node.js from a button?

This is a really weird issue I am having.
I have a login form, this login form verifies your data and renders the Profile layout if the login is successful OR renders the register page if the login is not.
exports.logIn = function (req, res, data) {
var username = req.body.username.toString();
var password = req.body.password.toString();
connection.connection();
global.connection.query('SELECT * FROM Utilizador WHERE Nome_Utilizador = ? LIMIT 1', [username], function (err, result) {
if (result.length > 0) {
if (result) {
var object = JSON.parse(JSON.stringify(result));
var userObject = object[0];
var userQ = object[0].Nome_Utilizador;
global.connection.query('SELECT Password_Utilizador from Utilizador where Nome_Utilizador = ?', [username], function (err, result) {
console.log(result);
if (result.length > 0) {
if (result) {
var object2 = JSON.parse(JSON.stringify(result));
var passQ = object[0].Password_Utilizador;
if (password == passQ) {
console.log("Login efectuado com sucesso");
console.log(userObject);
res.render('home', { title: 'perfil', layout: 'perfil', data: userObject });
} else {
console.log("1");
}
}
} else if (err) {
console.log("asdsadas");
} else {
console.log("2");
res.render('home', { title: 'perfil', layout: 'registo' });
}
});
}
} else if (err) {
console.log(err);
} else {
console.log("Utilizador nao encontrado");
res.render('home', { title: 'perfil', layout: 'registo' });
}
});
};
This works.
And the only reason why it does work is because it comes from a FORM with a METHOD and an ACTION
<form id="login-nav" action="/login" method='POST' role="form" accept-charset="UTF-8" class="form">
<div class="form-group">
<label for="username" class="sr-only">Utilizador</label>
<input id="username" type="username" placeholder="Nome de utilizador" required="" class="form-control" name="username">
</div>
<div class="form-group">
<label for="exampleInputPassword2" class="sr-only">Palavra-Passe</label>
<input id="password" type="password" placeholder="Meta a palavra-passe" required="" class="form-control" name="password">
</div>
<div class="checkbox">
<label></label>
<input type="checkbox">Gravar Dados
</div>
<div class="form-group">
<button id="botaoLogin" class="btn btn-danger btn-block">Fazer Login</button>
</div>
</form>
However, I tried to do the same thing with jQuery, as I need to render a Handlebars layout for some products on button click,
$("#pacotes").on('click', ".produto", function () {
var prod = this.id;
console.log(prod);
$.get("http://localhost:3000/pacote?idPacote=" + prod);
});
And despite the query working and giving me the data I requested
exports.Pacote = function (req, res) {
var pacote = req.query.idPacote;
connection.connection();
global.connection.query('SELECT * FROM Pacotes WHERE idPacotes = ? ', [pacote], function (err, result) {
if (result.length > 0) {
if (result) {
var object = JSON.parse(JSON.stringify(result));
var packObject = object[0];
console.log(result);
res.render('home', { title: 'pacote', layout: 'pacote', data: packObject });
} else if (err) {
console.log(err);
}
};
});
}
It simply doesn't render the layout and I have no idea why.
What is the difference between doing a POST request like this or doing it by a form?
I don't understand why this only seems to work with forms.
I could solve it that way, but I don't think using empty forms for all my buttons would be a viable solution.
You are only making a request, you are not processing the return value:
$.get("http://localhost:3000/pacote?idPacote=" + prod);
Try changing to something like:
$.ajax({
method: 'GET',
url: "http://localhost:3000/pacote?idPacote=" + prod,
success: function(...) {...}
});

Error copying req.body properties into Mongoose Model

First of all I have to say that I'm new in Angular and node technologies. So sorry for my ignorance.
I get this error when I try to save an Entity from edition view: 'Cast to ObjectId failed for value "[object Object]" at path "category"'.
Well, I've got these code:
HTML:
<form class="form-horizontal" data-ng-submit="update()" novalidate>
<fieldset>
<div class="form-group">
<label for="listaCat">Categoría:</label>
<select id="listaCat" class="form-control" data-ng-Fmodel="notification.category" data-ng-options="c.name for c in listaCategorias track by c._id">
</select>
</div>
<div class="form-group">
<label class="control-label" for="name">Descripción</label>
<div class="controls">
<input type="text" data-ng-model="notification.name" id="name" class="form-control" placeholder="Descripción" required>
</div>
</div>
<div class="form-group">
<input type="submit" value="Guardar" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>`
Angular controller:
$scope.update = function() {
var notification = $scope.notification;
notification.$update(function() {
$location.path('notifications/' + notification._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Server side controller:
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Notification = mongoose.model('Notification'),
_ = require('lodash');
exports.update = function(req, res) {
var notification = req.notification;
notification = _.extend(notification , req.body);
notification.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(notification);
}
});
};
Mongoose Model:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var NotificationSchema = new Schema({
name: {
type: String,
default: '',
required: 'Rellena la notificación',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
category: {
type: Schema.ObjectId,
ref: 'Category'
}
});
mongoose.model('Notification', NotificationSchema);
var CategorySchema = new Schema({
name: {
type: String,
default: '',
required: 'Rellena la categoría',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Category', CategorySchema);
So, if I debug inside Server controller at update method with WebStorm, I can see that req.body comes with each attribute well formed, but after convert req.body into Notification Mongoose Model with:
notification = _.extend(notification , req.body);
the category attribute is not a Model but an ObjectId. It seems as lodash.extend is not working properly for complex attributes. I've tried many other ways of cloning the object but without success.
Finally I solved it, with this line inside the angular controller:
notification.category = $scope.notification.category._id;
notification.$update(function() {
Anyway, I think that this is not the right way. I guess there must be a way of copying the req.body properties into a mongoose model without doing it manually for the complex properties.
Thanks a lot in advance!
Since you are working on AngularJS and ExpressJS, i would suggest you to use $resource service which is exactly meant for interacting with the rest API.
**$resource** contains these default set of actions:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
There is nice documentation available in the link that i shared above.
In your case:
i assume, http://localhost:300/notifications/:id, this might be your rest url where you want to perform update action.
You can create your custom services like:
var module = angular.module('myapp.services',['ngResource']);
module.factory('MyAppUpdateService',function($resource){
return $resource('notifications/:id',
{
id: '#id'
},
{
'update': { method:'PUT' }
}
);
});
Now inside your angular app controller you can inject this service as dependency and hence it will be available to perform update in that REST url.
angular.module('myapp',['ngResource','myapp.services']);
angular.module('myapp').controller('MeetupsController',['$scope','$resource','$state','$location','MeetupUpdateService','socket',
function($scope,$resource,$state,$location, MyAppUpdateService){
$scope.updateMeetup = function(){
$scope.updateService = new MyAppUpdateService();
$scope.updateService.name = $scope.notification.name;
.
.
.
$scope.updateService.$update({id:$scope.notification.category._id},function(result){
$location.path("/meetup/")
});
}
})]);
So this was just an example, if you want more comprehensive implementation. Look here, i am creating a MEAN seed of my own, and i am doing the same.
Any doubt please do ask.

MeteorJS useraccounts:core and meteor-roles

I am using MeteorJS to develop simple web app. I am new at MeteorJs. I use useraccounts:core package and meteor-roles by alanning. Is it posible to assign role to user while registering a new user ?
EDIT 1
I have tried using onCreateUser hook but something is not working.
Accounts.onCreateUser(function(options, user){
var role = ['unselected'];
Roles.addUsersToRoles(user, role);
return user;
});
The below method must run on the server side only. The clue is that you need to create first the user, get the id from creation and then attach a role to it.
Meteor.methods({
rolesCreateUser: function (user) {
if (_.isObject(user)) {
if (user.username) {
var id = Accounts.createUser({
username: user.username,
email: user.email,
password: user.password
});
//We add roles to the user
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles);
}
_.extend(user, {id: id});
return user;
}
}
}
});
And then on the client side call the method with user's data:
Meteor.call('rolesCreateUser', newUserData, function (error, newCreatedUser) {
if (error) {
//The error code
} else {
//Do something with newCreatedUser
}
});
I have this way to create users (if i understond you example you alredy have some users, just need some roles, so with the current user just create this), also use some Login buttons customized or something like that
Server.js
Meteor.methods({
createUsers: function(email,password,roles,name){
var users = [{name:name,email:email,roles:[roles]},
];
.each(users, function (user) {
var id;
id = Accounts.createUser({
email: user.email,
password: password,
profile: { name: user.name }
});
if (user.roles.length > 0) {
Roles.addUsersToRoles(id, user.roles);
}
});
},
deleteUser : function(id){ ///Some Delete Method (ignore if dont needed)
return Meteor.users.remove(id);
},
});
Publish Methods
//publish roles
Meteor.publish(null, function (){
return Meteor.roles.find({})
})
Meteor.publish("Super-Admin", function () {
var user = Meteor.users.findOne({_id:this.userId});
if (Roles.userIsInRole(user, ["Super-Admin"])) {
return Meteor.users.find({}, {fields: {emails: 1, profile: 1, roles: 1}});
}
this.stop();
return;
});
Meteor.publish("Admin", function () {
var user = Meteor.users.findOne({_id:this.userId});
if (Roles.userIsInRole(user, ["Admin"])) {
return Meteor.users.find({}, {fields: {emails: 1, profile: 1, roles: 1}});
}
this.stop();
return;
});
Meteor.publish(null, function (){
return Meteor.roles.find({})
})
So on the Client side client/register.html
<template name="register">
<form id="register-form" action="action" >
<input type="email" id="register-email" placeholder="Nombre Nuevo Usuario">
<input type="password" id="register-password" placeholder="Password">
<select id="register-rol" class="form-control">
<option value="Admin" selected>Admin</option>
<option value="Super-Admin" selected>Super Admin</option>
<option value="Normal" selected>Normal</option>
</select>
<input type="submit" value="Register">
</form>
</tempalate>
and on register.js call the server methods
Template.registrar.events({
'submit #register-form' : function(e, t) {
e.preventDefault();
var email = t.find('#register-email').value,
password = t.find('#register-password').value,
roles = $( "#register-rol" ).val();
Meteor.call("createUsers", email, password,roles);
return false;
},
'click #deleteUser' : function(event,template){
var idUsuario= this._id;
Meteor.call('deleteUser',{_id:idUsuario})
}
});
Delete Part(html) this is optional just too look if accounts are creating correctly
{{#each users}}
<li id="user"><h6>{{email}}</h6><h6>{{roles}}</h6></li>
<button id="deleteUser" class="btn btn-danger btn-xs" > Borrar Usuario {{email}} </button>
{{/each}}
client/registerList.js
Template.registrar.helpers({
users: function () {
return Meteor.users.find();
},
email: function () {
return this.emails[0].address;
},
roles: function () {
if (!this.roles) return '<none>';
return this.roles.join(',');
}
});
Remember Subscribe
Meteor.subscribe('Admin');
Meteor.subscribe('Super-Admin');
Hope this help sorry for the messy code
You may want to use OnCreateUser hook: http://docs.meteor.com/#/full/accounts_oncreateuser

Comparing value from input with backbone collection data

I'm trying to create very simple login with backbonejs. Collection stores usernames and passwords. Login view has two inputs and on click it should perform check function and compare input value with data from collection.
Html part looks like this:
<div class="login-block">
<script type="text/template" id="start">
<form id="login">
<div class="input-wrapper"><input type="text" placeholder="Username" id="username" required></div>
<div class="input-wrapper"><input type="password" placeholder="Password" id="password" required></div>
<div class="input-wrapper"><button class="btn">Sign in!</button></div>
</form>
</script>
<div class="error" class="block">
Error
</div>
<div class="success">
Success
</div>
</div>
Here is my Js code:
var User = Backbone.Model.extend({
defaults: {
login: 'root',
mail: 'root#mail.com',
password: ''
}
});
var user = new User();
//variable to store username
var loginData = {
username: "",
password: ""
}
// userbase
var UserCollection = Backbone.Collection.extend({
model: User
});
var userCollection = new UserCollection([
{
username: 'Ivan',
mail: 'ivan#mail.com',
password: '1234'
},
{
username: 'test',
mail: 'test#mail.com',
password: 'test'
}
]);
// login page
var LoginView = Backbone.View.extend({
el: $(".login-block"),
events: {
"click .btn": "check"
},
check: function(){
loginData.username = this.$el.find("#username").val(); // store username
loginData.password = this.$el.find("#password").val();// store password
if (loginData.username === userCollection.each.get("username") && loginData.password === userCollection.each.get("password"))
{appRouter.navigate("success", {trigger: true});
}else{
appRouter.navigate("error", {trigger: true});
}
},
render: function () {
//$(this.el).html(this.template());
var template = _.template($('#start').html())
$(this.el).html(template());
//template: template('start');
return this;
}
});
var loginView = new LoginView({collection: userCollection});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'index', // start page
'/error': 'error',
'/success': 'success'
},
index: function() {
loginView.render();
console.log("index loaded");
},
error: function(){
alert ('error');
},
success: function(){
console.log('success');
}
});
var appRouter = new AppRouter();
Backbone.history.start();
It works fine to the check function, and it stores username and password, but something is clearly wrong either with router or check function when it starts comparison. Instead of routing to success or error page, it rerenders index page.
P.S I didn't use namespacing and code in general is not of a greatest quality, but it was made for educational purpose only.
You have to add the attribute type="button" to your button, otherwise it will submit the form when clicked (See this question):
<script type="text/template" id="start">
<form id="login">
<div class="input-wrapper"><input type="text" placeholder="Username" id="username" required></div>
<div class="input-wrapper"><input type="password" placeholder="Password" id="password" required></div>
<div class="input-wrapper"><button class="btn" type="button">Sign in!</button></div>
</form>
</script>
You can also return false in the click event handler, which would cancel the default action. (submitting the form, if you don't add type="button").
For comparing the values with the hardcoded collection, you can't call each as you where doing (which is an iteration function provided by Underscore) because you would receive an error. You could use Underscore's findWhere method which is also available in Backbone collections. So the click event handler (Your check function) could look like this:
check: function(){
loginData.username = this.$el.find("#username").val(); // store username
loginData.password = this.$el.find("#password").val();// store password
if(userCollection.findWhere({username: loginData.username, password: loginData.password})){
appRouter.navigate("success", {trigger: true});
}else{
appRouter.navigate("error", {trigger: true});
}
return false;
},
You can try it on this fiddle
The logic check you're doing doesn't look like it would work to me. I would expect the following to generate an error:
userCollection.each.get('username')
the function you're calling on your collection, each, is a wrapped underscore method which takes a function callback as a parameter. If you want to check your username and password, I'd do something like this:
var user = userCollection.findWhere({ username: loginData.userName });
This will return you the model where the username matches. Then you can check the password of that model:
if (user.get('password') === loginData.password) {
// do something
} else {
// do something else
}
EDIT Heck, you can do both checks at once:
var user = userCollection.findWhere({ username: loginData.userName, password: loginData.password });
I'll leave the previous code up just to demonstrate.

Categories

Resources