Sign user in upon account creation - ruby-on-rails

I'm using the ng-token-auth module and the devise_token_auth gems.
The default behavior seems to be that when a user registers, the user gets sent an email with a confirmation link. I don't want this behavior; I just want the user to immediately be signed in following account creation, which is of course a really common way for account creation to work.
I'm so unsure how to achieve this that I don't even know what to ask. Would anyone happen to have used these libraries before who can provide some insight?

Jason, your answer is mostly correct. You will also need to instruct the server to bypass the email confirmation step. If this isn't done, the user won't be able to sign in until the link in the confirmation email has been visited. Here are the complete instructions:
1. Bypass email confirmation server-side
Assuming the model is called User, run the skip_confirmation! method as a pre-create callback. This really just sets the user's confirmed_at value to the current time, but the step is necessary to bypass email confirmation.
class User < ActiveRecord::Base
include DeviseTokenAuth::Concerns::User
before_create :skip_confirmation!
end
2. Sign in immediately after successful registration
Assuming the html form looks like this:
<form ng-submit="submitRegistration(registrationForm)" role="form" ng-init="registrationForm = {}">
<fieldset>
<div>
<label>email</label>
<input type="email" name="email" ng-model="registrationForm.email" required>
</div>
<div class="form-group">
<label>password</label>
<input type="password" name="password" ng-model="registrationForm.password" required>
</div>
<div class="form-group">
<label>password confirmation</label>
<input type="password" name="password_confirmation" ng-model="registrationForm.password_confirmation" required>
</div>
<button type="submit">Register</button>
</fieldset>
</form>
Update - as of devise_token_auth version 0.1.29.beta2, users will be automatically authenticated upon registration if the above before_create :skip_confirmation! callback is used. So the above code is all that is necessary.

Okay, I figured out the answer to my own question (natch).
I modified my controller to look like this:
'use strict';
/**
* #ngdoc function
* #name lunchHubApp.controller:UserRegistrationsCtrl
* #description
* # UserRegistrationsCtrl
* Controller of the lunchHubApp
*/
angular.module('lunchHubApp')
.controller('UserRegistrationsCtrl', ['$scope', '$rootScope', '$location', '$auth', function ($scope, $rootScope, $location, $auth) {
$scope.handleRegBtnClick = function() {
$auth.submitRegistration($scope.registrationForm)
.then(function() {
$auth.submitLogin({
email: $scope.registrationForm.email,
password: $scope.registrationForm.password
});
});
};
}]);

Related

Rails server as database for mobile app

I would like to test some mobile app development.
I choose to use Rails as my back-end and Phonegap as my front-end.
What do you think about those choice ?
I already manage to register a user from my app (Using AVD) to my server Rails.
But now, after registering the user, rails want to redirect to a page on the rails server. But I don't want it, is it possible that Rails send a "callback" (or whatever) to my mobile app that say "Ok the user is register" and then perform an action in my mobile app according to this message ?
My register form looks like
form accept-charset="UTF-8" action="http://3dcb84c4.ngrok.com/users" id="new_user" method="post">
<label for="user_name">Pseudo</label>
<input id="user_name" name="user[name]" type="text">
<br>
<label for="user_email">Email</label>
<input id="user_email" name="user[email]" type="email">
<input type="submit" value="Submit">
</form>
And my controller on my server looks like
def create
#user = User.new(user_params)
if #user.save
# send OK
else
# something
end end
thanks
You're probably looking for the rails-api gem.
you have to respond to the format and if it is js you have to
msg = {:status => 200, msg_text => 'Ok the user is register'}
render json: msg
instead of render the default erb.

Query string not being passed to controller

I have what should be a relatively simple form in Rails that I'm using to send an email for two different previews, a desktop preview and a mobile preview.
<form id="email-form" role="form" action="<%= action_name == 'desktop_preview' ? email_preview_newsletter_path(#newsletter) : email_preview_newsletter_path(#newsletter, mobile: 'true') %>">
<label for="email_address">Email</label>
<input type="email" id="email_address" name="email_address" value="<%= params[:email_address] %>" placeholder="PLEASE ENTER EMAIL">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Send" class="btn btn-primary"></input>
</form>
Right now I have it setup so that both previews get sent to the same endpoint, '/email_preview', but in the case of the mobile_preview I want to pass in a 'mobile' query string so that it ends up looking like this:
'/email_preview?mobile=true'
When I inspect the form on the page everything looks in order, however when it gets passed to the controller the 'mobile' part of the query string disappears and only the 'email_address' exists.
I suppose I could pass in the mobile value as a hidden field, but something about that just doesn't feel right to me. What is the best way to setup this form so that both the 'mobile' and 'email_address' key value pairs are passed as query strings when sent to the controller?
In the process of writing out this question I realized exactly what the problem was:
I had the form setup as a GET request as opposed to a POST request.
This was causing any pre-established query strings to get erased in the process of setting up the GET params being defined in the form (in this case, the 'email_address' param). Changing the form from GET to POST, (i.e. form method="POST")
Took care of this issue. Please note that if you are going to manually setup a form like this in rails then you also need to explicitly take care of the csrf token. This can be done by inserting the following input with the helper method into your form:
input type="hidden" name="authenticity_token" value="<%=form_authenticity_token%>"

Create Customer w/ simple Stripe Checkout

My aim to to verify a users card information and store that info in a customer object.
I run a pay-upon delivery service and am building a hack to protect against fake orders (we can charge people via the strip dashboard if they place false orders or don't show up).
A full stripe integration is the long term goal, but I need something ASAP. I've read (re-read) the the docs but am having trouble.
The simple stripe checkout works great, but I am clueless about how to create a customer from there.
Script:
<form action="/charge" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="TEST KEY"
data-image="/square-image.png"
data-name="Food Bazooka"
data-description="Customer Verification. No charges :)"
data-panel-label="Confirm and Verify"
data-label="Confirm">
</script>
</form>
Any feedback or ideas are greatly appreciated.
Thanks!
You're using the embedded form, where as you need to use custom forms and some server side code.
You would need first create a single use token which represents a customer card from your form
(Assuming your form contains credit card number, expiry date etc...)
Taken from the docs:
Form markup:
<form action="/customer" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input type="text" size="4" data-stripe="exp-year"/>
</div>
<button type="submit">Submit Payment</button>
</form>
Javascript:
jQuery(function($) {
$('#payment-form').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
This essentially takes your form, and adds a hidden field called stripeToken before submitting
Notice the form action is /customer
I see you're using Ruby On Rails from your tag - so you would need to handle the customer POST with a controller
This is what you'll need to do:
https://stripe.com/docs/tutorials/charges#saving-credit-card-details-for-later
# Set your secret key: remember to change this to your live secret key in production
# See your keys here https://dashboard.stripe.com/account
Stripe.api_key = "sk_test_X9S2nHIxFy399uoNvakwJYSn"
# Get the credit card details submitted by the form
# notice stripeToken - this is the hidden field
token = params[:stripeToken]
# Create a Customer
customer = Stripe::Customer.create(
:card => token,
:description => "payinguser#example.com"
)
# Charge the Customer instead of the card
# ** I have commented this block out, as you say you do not want to charge the customer
# Stripe::Charge.create(
# :amount => 1000, # incents
# :currency => "gbp",
# :customer => customer.id
# )
# Save the customer ID in your database so you can use it later
save_stripe_customer_id(user, customer.id)

MVC Form Submit Button will Conditionally have OnClick Event

Posting a form from .cshtml. If the Email Textbox has the value of "Admin" and the Password TextBox has the value of "12345" I want to include an onclick event on the submit button.
I thought about if/else block but what to place in the if condition below where you see question mark (?):
<form class="fvalidate" action="/entry" method="post">
<input type="text" name="Email" class="email required"/>
<input type="password" name="Sifre" class="required" />
#if (?)
{
<input type="submit" value="LOG IN" class="mTop15"
onclick="ibFunc.openBoxOpen('/entry/adv'); return false;" />
}
else
{
<input type="submit" value="LOG IN" class="mTop15" />
}
</form>
How could I accomplish this?
You need to understand the flow of the application and what fires when. You seem to be mixing Client and Server side technology.
The flow should be
Step 1 Submit the form
Step 2 The controller validates the login and works out whether they are admin or not.
Step 3 The controller redirects the user to the /entry or /entry/adv page depending on whether they are an admin or not
Step 4 On the /entry page don't fire the javascript
Step 4a On the /entry/adv page fire the javascript
To answer your question directly. There is nothing you can put in the place of the ? that will do what you want because that is Razor code which is executed on the server before the user has interacted with the page.
Do the control in POST in the controller, when the "Admin" submit the form make an if then use
return RedirectToAction("adv", "entry");

Why does the post method seem to be clearing my rails session data?

After the user has logged in and their username authenticated and saved in session[:user_name], when submitting a form with method="post" (using standard html) all session data is cleared and user is routed back to the login page. This does not happen if the method is set to get.
Post works when I use the rails "form_tag" which generates these additional lines:
<div style="margin: 0pt; padding: 0pt; display: inline;">
<input type="hidden" value="✓" name="utf8">
<input type="hidden" value="a_bunch_of_gibberish" name="authenticity_token">
</div>
What is happening?
Are you using Rails 3.0.4? It sounds like it might be related to the CSRF fix.
If you need a fix specific to your needs, you can overwrite #handle_unverified_request in your controller. See https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/request_forgery_protection.rb.
Here's an example where this issue was with OmniAuth and OpenId. (See section 'CSRF Protection In Rails 3.0.4')
This issue can also happen if you're creating your own html form.
If you're getting redirected without knowing why, it's because of "protect_from_forgery" in your ApplicationController
In order to allow your form to post, add the following code to it (or use form_tag, explanation below):
<form ... >
...
<%= hidden_field_tag "authenticity_token", form_authenticity_token %>
...
</form>
The reason the "form_tag" works is because form_tag generates the hidden field for you =)

Resources