No user save in database with rest restangular.all post - javascript

I have a problem to perform a rest post request for saving data in a database .
I created a form register.html and a RegisterCtrl.js controller to add the user account in the database .
The url to create a user is register : http://localhost:8100/#/register
I use the framework Ionic and AngularJS
Unfortunately, no post application works .
Can you help me.
Thank you.
Template register.html
<ion-modal-view ng-controller="RegisterCtrl">
<ion-content>
<form ng-controller="RegisterCtrl">
<div class="register listRegister">
<label class="register item item-input">
<span class="spanLogin icon-left ion-person"></span>
<input type="text" class="form-control" ng-model="user.username" placeholder="Username" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-email"></span>
<input type="email" class="form-control" ng-model="user.email" placeholder="Email" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-key"></span>
<input type="password" class="form-control" ng-model="user.password" placeholder="Password" />
</label>
</div>
<div class="registerButton">
<button class="validLogin button button-block button-assertive" type="submit">Registration
</button>
Back
</div>
</div>
</form>
</ion-content>
</ion-modal-view>
Controller registerCtrl.js
'use strict'
angular.module('djoro.controllers',['restangular']);
.controller('RegisterCtrl', function($scope, restangular) {
var userRegister = {
"username": user.username,
"email": user.email,
"password": user.password
};
Restangular.all('register').post(userRegister).then(
function (data) {
$scope.register = data;
});
});
Api rest by python Django
class UserRegistration(viewsets.ViewSet):
"""
Called with the URL r'^register/*$'. It allows POST requests.\n
POST requests allow to create a new user. The parameters to post are 'username','email','password'.\n
It raises an HTTP 400 error if the POST request is invalid and an HTTP 401 error if an user with the username or email specified already exists.
"""
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
email=request.data.get('email')
try :
user=register(username, email, password)
user.backend='django.contrib.auth.backends.ModelBackend'
user.save()
login(request, user)
return HttpResponseRedirect("/me/")
except AttributeError:
return Response({"detail": "User with this email or username already exists"}, status=HTTP_401_UNAUTHORIZED)

Related

Cannot Modify The Value of HTML Elements From Node.js

I have an HTML form, which should be completed by the user. After completing the form, the introduced data is checked, in order to see whether the introduced username was introduced before or not. If the username is unique, then the input data is valid. If the username has already been used by someone else, I want to reload the sign up page, which is called signUp.html, but I also want to modify the values and placeholders of those fields contained by that HTML form. Excepting the Username and Password fields, I want every other field to contain the data, which was introduced by the user before. For sample, if the First Name field contained the value Toma, then I want, after reloading the page, the First Name field to have the value of Toma. On the other hand, I want to change the message of the placeholder of the Username field, which would be something like: Sorry, this username is invalid.... I tried to use the jsdom package, in order to acces the HTML file: signUp.html, which is to be found in public/views. The code of the HTML form is:
<form method="POST" action="signUp" style="margin-left: 5%; margin-right: 5%; margin-top: 5%" class="was-validated">
<div class="form-group">
<label style="color: #ffffff"> First Name </label>
<input type="text" name="firstName" class="form-control" placeholder="e.g.: Toma" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Second Name </label>
<input type="text" name="secondName" class="form-control" placeholder="e.g.: Alex" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Email </label>
<input type="email" name="email" class="form-control" placeholder="e.g.: somename#somedomain.com" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Username </label>
<input type="text" name="username" class="form-control" placeholder="e.g.: miauMiau23 (this is the name your friends will identify you with)" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Password </label>
<input type="password" name="password" class="form-control" placeholder="please, use a solid password, having a minimum of 6 characters, small and capital letters, as well as numbers and symbols!" required>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%"> Submit </button>
</form>
The code found in server.js, which tried to achieve what I've described before:
app.post('/signUp', urlencodedParser, function(req, res){
console.log("sorry... this username is invalid!");
res.render('signUp');
var { document } = (new JSDOM('public/views/signUp.html')).window;
var firstNameField = document.getElementsByName('firstName');
var secondNameField = document.getElementsByName('secondName');
var emailField = document.getElementsByName('email');
var usernameField = document.getElementsByName('username');
var passwordField = document.getElementsByName('password');
console.log(firstNameField.placeholder);
firstNameField.value = req.body.firstName;
secondNameField.value = req.body.secondName;
emailField.value = req.body.email;
usernameField.value = "";
usernameField.placeholder = "'" + req.body.username + "' is an invalid username...";
passwordField.value = "";
}
After reloading, the page loses all of the introduced data.
The reason is not working is because res.render will render the page on the server and then send it to the client. What you're doing after that is simply loading the HTML again into the server's memory with JSDOM and modifying it, at the end of the request that is just thrown away and doesn't effect what has already been sent to the client by res.render.
The correct way to do this would be to use a templating language (there are many to choose from) with your express.js server to dynamically render the page and inject the values you want in the right place. You can then simply pass the variables to the res.render to be available when rendering your template:
app.post('/signUp', urlencodedParser, function(req, res) {
console.log("sorry... this username is invalid!");
res.render('signUp', {
firstName: req.body.firstName,
secondName: req.body.secondName,
email: req.body.email,
error: "'" + req.body.username + "' is an invalid username...",
});
});
For example, if you went with Pug.js as a templating engine your sign-up page could look something like this (I've not included all formatting which should go into CSS):
form(method='POST' action='/signUp')
div.form-group
label(for='firstName') First Name
input#firstName.form-control(type='text', name='firstName', value=firstName, required)
div.form-group
label(for='secondName') Second Name
input#secondName.form-control(type='text', name='secondName', value=secondName, required)
div.form-group
label(for='email') Email:
input#email.form-control(type='email', name='email', value=email, required)
div.form-group
label(for='username') Username
if error:
input#username.form-control(type='text', name='username', placeholder=error)
else:
input#username.form-control(type='text', name='username', placeholder='e.g.: miauMiau23 (this is the name your friends will identify you with')
div.form-group
label(for='password') Password:
input#passwordw.form-control(type='password' name='password')
button.btn.btn-primary(type='submit') Submit

How to determine post request inputs using javascript

I am trying to login to a website using python but not having much success. Whenever I post my credentials, I get a 200 response but I'm redirected to the login screen. I think this is because the website's login is using javascript that requires more than just a username and password in the post command, but I'm not sure how to parse it to fix my login code.
This is my python code:
s = requests.session()
login_url = "example.com"
result = s.get(login_url)
payload = {
"user_login": "xx",
"user_pass": "xx"
}
print(payload)
postresult = s.post(
login_url,
data = payload,
allow_redirects=True
)
Here's what the input form looks like:
<div id="loginForm">
<ul>
<li>
<label>Email:</label>
<input class="txt" type="email" name="user_login" tabindex="1" value="">
</li>
<li>
<label>Password:</label>
<input class="txt" type="password" name="user_pass" tabindex="2">
</li>
<li class="submit">
<a id="a-fgt" class="sub" href="#" tabindex="4">Forgot Password</a>
<input type="submit" id="logSubmit" value="Login" tabindex="3" />
<div id="rightBlock">
<span id="respMsg"></span>
</div>
</li>
</ul>
</div>
And here's part of the javascript code that's executing:
function init_login(){
var form = document.forms.loginForm;
$submit(form,login_request);
$listen($('a-fgt'),'click',function(){buildForgotPassword(false);},false);
var lgn = getCookie('login');
if(lgn){form.user_login.value = lgn;}
form[wordCount(form.user_login.value)?'user_pass':'user_login'].focus();
formVal = new FormValidator(form);
}
/*---\\\ LOGIN FUNCTIONS ///---*/
function login_request(form){
form = validateForm(form, 'user_pass');
$post("/JSMX/admin_login.cfc?method=login",login_response,form);
}

Possible to create Token with Stripe JS with no payment information

I have a client that wants to have a Stripe subscription that does not cost anything. Currently, their application is set up to take CC info because their older plan did require a monthly fee.
I want to know if it is possible to create a Stripe customer token via Stripe JS without taking any kind of CC info/bank account etc from the user?
I tried removing the CC fields with jQuery, but I keep getting a Stripe Invalid Request error because it cannot find the payment information.
So to summarize, when a user selects the 'free' plan from the dropdown, they should not see the CC fields and they should be able to progress through the sign up page without any Stripe validations while also creating their customer token.
Is this possible?
Relevant files
Hosts Controller #create
def create
#host = User.new(host_params)
if #host.valid?
customer = Stripe::Customer.create(
stripe_params.merge(email: host_params[:email], coupon: coupon)
)
#host.update(
stripe_customer_id: customer[:id],
subscription_plan: stripe_params[:plan]
)
sign_in(:user, #host)
redirect_to dashboard_path, notice: t('notices.hosts.created')
else
render :new
end
rescue Stripe::CardError, Stripe::InvalidRequestError => error
render :new, alert: error.message
end
Stripe JS code
$(document).on 'ready page:load', ->
$cardFields = $('#credit-card-fields')
$parentForm = $cardFields.parents('form')
$parentBtn = $('.js-payment-btn', $parentForm)
return unless $parentForm.length
$parentBtn.on 'click', (event) ->
event.preventDefault()
pub_key = $('meta[name=stripe-publishable-key]').attr('content')
$parentBtn.prop('disabled', true)
Stripe.setPublishableKey(pub_key)
Stripe.card.createToken $parentForm, (status, response) ->
if response.error
$parentForm.find('.payment-errors').text(response.error.message)
$parentBtn.prop('disabled', false)
else
token = response.id
S> $parentForm.append($('<input type="hidden" name="stripe[source]" />').val(token))
$parentForm.get(0).submit()
Stripe JS Form
<script type="text/javascript" src="https://js.stripe.com/v2/" data-turbolinks-track="true"></script>
<div class="clearfix" id="credit-card-fields">
<span class="payment-errors"></span>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon icon icon-credit-card"></span>
<input id="card-number" class="form-control input-cc" required placeholder="Card Number" type="text" size="16" maxlength=16 data-stripe="number" />
</div>
</div>
<div class="form-group side-by-side">
<div class="input-group">
<span class="input-group-addon icon icon-calendar"></span>
<input id="card-month" class="form-control input-exp" required placeholder="MM" type="text" size="2" maxlength="2" data-stripe="exp-month" />
<input id="card-year" class="form-control input-exp" required placeholder="YY" type="text" size="2" maxlength="2" data-stripe="exp-year" />
</div>
</div>
<div class="form-group side-by-side">
<div class="input-group">
<span class="input-group-addon icon icon-lock"></span>
<input id="card-cvc" class="form-control input-cvv" required placeholder="CVC" type="text" size="4" maxlength="4" data-stripe="cvc" />
</div>
</div>
</div>
It would not make sense to create a card token without any card details so this is not possible. As you mentioned, if you try to create a token without the required parameters such as the card number or the expiration date you get an invalid_request_error back.
If you don't want to require card details then you should just not create a token. When someone attempts to subscribe to a free plan, you would bypass the need to create a token and simply collect the rest of the information you want such as the customer's email address or name. Then server-side, you'd call the Create Customer API and pass the plan id in the plan parameter to subscribe them.
If the plan is free then there's no need to pass a token and you can simply ignore the source parameter completely.

Sending HTML form via AJAX to PHP server

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

How to create Custom Login Fields in Meteor?

In meteor, I current am using the default login field. However, I would like to have the user create a unique user ID upon creating an account. I could hardcode this in, but I was wondering if there was a way to do this by editing the loginButton field somehow.
Would anybody know how to add extra fields in general that the user signing up would be forced to fill out? Such as name, username, etc.?
The loginButtons helper is meant to be an easy, drop-in helper for prototyping. For customization, you need to create your own custom login/signup forms. This is actually pretty easy with the documented Accounts API. Here's a simple example of custom login/signup forms:
<template name="signupForm">
<form id="signup-form">
<h2>Sign Up</h2>
<label for="signup-username">Username</label>
<input type="text" id="signup-username" placeholder="Username" />
<label for="signup-password">Password</label>
<input type="password" id="signup-password" placeholder="Password" />
<label for="signup-name">Full Name</label>
<input type="text" id="signup-name" placeholder="Full Name" />
<button type="submit">Sign Up</button>
</form>
</template>
<template name="loginForm">
<form id="login-form">
<h2>Log In</h2>
<label for="login-username">Username</label>
<input type="text" id="login-username" placeholder="Username" />
<label for="login-password">Password</label>
<input type="password" id="login-password" placeholder="Password" />
<button type="submit">Log In</button>
</form>
</template>
<template name="logoutForm">
<form id="logout-form">
<button type="submit">Log Out</button>
</form>
</template>
Template.signupForm.events({
"submit #signup-form": function(event, template) {
event.preventDefault();
Accounts.createUser({
username: template.find("#signup-username").value,
password: template.find("#signup-password").value,
profile: {
name: template.find("#signup-name").value
// Other required field values can go here
}
}, function(error) {
if (error) {
// Display the user creation error to the user however you want
}
});
}
});
Template.loginForm.events({
"submit #login-form": function(event, template) {
event.preventDefault();
Meteor.loginWithPassword(
template.find("#login-username").value,
template.find("#login-password").value,
function(error) {
if (error) {
// Display the login error to the user however you want
}
}
);
}
});
Template.logoutForm.events({
"submit #logout-form": function(event, template) {
event.preventDefault();
Meteor.logout(function(error) {
if (error) {
// Display the logout error to the user however you want
}
});
}
});
You can use the Accounts.validateNewUser() and Accounts.onCreateUser() methods to validate the user fields and perform further customization on the user objects, respectively. For example, in your onCreateUser callback, you can change the user's _id field to whatever you want before returning the user object to be inserted into the DB.
Note that this example doesn't include the code for when the user forgot their password and wants to reset it. You can use the Accounts.forgotPassword and Accounts.resetPassword methods for that.
If you are having email as a field in your 'users' collection and you enters email id in the place of username it makes login into the system as we are not using accounts-ui here. So we can not be able to use accounts-ui config facility.

Categories

Resources