How do you add an administratior in a rails 3 appliction - ruby-on-rails

I have just built a rails 3 application by using Mike Hartl's "Learn Rails by Example". I am ready to deploy it but I am confused about how to add the administrator to the application. I will be the only administrator. Will the administrator be added before deployment and if so how do I do this.

What I believe you need when you talk about an "administrator account" is in fact two different things: authentication (the login) & authorization (what a login can/cannot do).
Under rails, one way to do that is by using two different gems. I suggest you have a look at devise, and cancan. They have both been developed and are actively maintained by rails superstars: José Valim and Ryan Bates.

The tutorial doesn't actually go through creating an interface where you can create admins. If you want to test the part where you're not allowed to delete other administrator accounts, you can test it with faker by adding 2 admins to the sample_data.rake file:
def make_users
admin = User.create!(:name => "Example User",
:email => "example#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
admin.toggle!(:admin)
admin2 = User.create!(:name => "Example User2",
:email => "example2#railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
admin.toggle!(:admin)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
If you want to add an admin to production, I'm guessing you could create your account and toggle the admin function with a database editor and then push the db to the production server? That's what I would do but I'm by no means an expert.

for admin control panel on my web-apps i'm using typus gem https://github.com/fesplugas/typus/
it will generate an admin page and by the default typus will use your model default_scope to fetch data.

I'm busy with the same thing!
I found this on STACK:
rails c
Loading development environment (Rails 3.0.0.beta3)
irb(main):001:0> admin = Admin.create! do |u|
irb(main):002:1* u.email = 'sample#sample.com'
irb(main):003:1> u.password = 'password'
irb(main):004:1> u.password_confirmation = 'password'
irb(main):005:1> end
I changed the Admin to User, but the problem is it creates a normal user not an admin user. Somewhere we need to put in - admin.toggle!(:admin) or make it true. I'll let you know if I find anything else.

Related

paypal gem multiple accounts ruby on rails

I'm using the paypal-sdk-merchant gem. So far I have set one merchant account with this command:
PayPal::SDK.configure(
:mode => "sandbox",
:app_id => "APP-sdfgjkl",
:username => "lprieto-facilitator_api1.hasu.cl",
:password => "Z7XGVDCHBJN",
:signature => "AFcWxV21C7fd0v3bYYYRCpSSRlXDCFVGBHLBRTnmAzXxHddoa5e",
:sandbox_email_address => "lprieto-facilitator_api1.hasu.cl")
and then create a payment with
api = PayPal::SDK::Merchant::API.new
This have work perfectly so far but now I have to change the paypal account according to the country the person is buying from. If I'm constantly changing the PayPal::SDK.configure will there be any consistence problems??
For example, if a person in Brasil access and the configuration is change. Then a person in Chile access and the configuration is change. After, the brasilian pays. Will it have the brasilian configuration or the chilean one?
What would you recommend for having multiple Paypal accounts in a ruby on rails app?
Thank you in advance.
I recommend taking a look at https://github.com/paypal/PayPal-Ruby-SDK because this gem doesn't support rails 4 and will be deprecated.
As for your problem at hand: Seeing the API, you would indeed need to call PayPal::SDK.configure() for each different type of merchant/country. You can create a YML config file for this something like config/paypal.yml:
chile:
mode: sandbox
app_id: APP-123
username: user1
password: pass1
signature: ABCDEF
sandbox_email_address: test#example.com
brasil:
mode: sandbox
app_id: APP-456
username: user2
password: pass2
signature: GHIJKL
sandbox_email_address: test2#example.com
and use this in your app like:
#api_chile = PayPal::SDK::Merchant::API.new(:chile)
#api_brasil = PayPal::SDK::Merchant::API.new(:brasil)
Hope this helps!

Devise "Confirmation token is invalid" when user signs up

Using Rails 4 and Devise 3.1.0 on my web app. I wrote a Cucumber test to test user sign up; it fails when the "confirm my account" link is clicked from the e-mail.
Scenario: User signs up with valid data # features/users/sign_up.feature:9
When I sign up with valid user data # features/step_definitions/user_steps.rb:87
Then I should receive an email # features/step_definitions/email_steps.rb:51
When I open the email # features/step_definitions/email_steps.rb:76
Then I should see the email delivered from "no-reply#mysite.com" # features/step_definitions/email_steps.rb:116
And I should see "You can confirm your account email through the link below:" in the email body # features/step_definitions/email_steps.rb:108
When I follow "Confirm my account" in the email # features/step_definitions/email_steps.rb:178
Then I should be signed in # features/step_definitions/user_steps.rb:142
expected to find text "Logout" in "...Confirmation token is invalid..." (RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/user_steps.rb:143:in `/^I should be signed in$
This error is reproducible when I sign up manually through the web server as well, so it doesn't appear to be a Cucumber issue.
I would like:
The user to be able to one-click confirm their account through this e-mail's link
Have the user stay signed in after confirming their account
I have setup:
The latest Devise code, from GitHub (3.1.0, ref 041fcf90807df5efded5fdcd53ced80544e7430f)
A User class that implements confirmable
Using the 'default' confirmation controller (I have not defined my own custom one.)
I have read these posts:
Devise confirmation_token is invalid
Devise 3.1: Now with more secure defaults
GitHub Issue - Devise confirmation_token invalid
And have tried:
Setting config.allow_insecure_tokens_lookup = true in my Devise initializer, which throws an 'unknown method' error on startup. Plus it sounds like this is only supposed to be a temporary fix, so I'd like to avoid using it.
Purged my DB and started from scratch (so no old tokens are present)
Update:
Checking the confirmation token stored on the User after registering. The emails token matches the DBs token. According to the posts above, the new Devise behavior says not supposed to, and that instead it is should generate a second token based on the e-mail's token. This is suspicious. Running User.confirm_by_token('[EMAIL_CONFIRMATION_TOKEN]') returns a User who has errors set "#messages={:confirmation_token=>["is invalid"]}", which appears to be the source of the issue.
Mismatching tokens seems to be the heart of the issue; running the following code in console to manually change the User's confirmation_token causes confirmation to succeed:
new_token = Devise.token_generator.digest(User, :confirmation_token, '[EMAIL_TOKEN]')
u = User.first
u.confirmation_token = new_token
u.save
User.confirm_by_token('[EMAIL_TOKEN]') # Succeeds
So why is it saving the wrong confirmation token to the DB in the first place? I am using a custom registration controller... maybe there's something in it that causes it to be set incorrectly?
routes.rb
devise_for :users,
:path => '',
:path_names => {
:sign_in => 'login',
:sign_out => 'logout',
:sign_up => 'register'
},
:controllers => {
:registrations => "users/registrations",
:sessions => "users/sessions"
}
users/registrations_controller.rb:
class Users::RegistrationsController < Devise::RegistrationsController
def create
# Custom code to fix DateTime issue
Utils::convert_params_date_select params[:user][:profile_attributes], :birthday, nil, true
super
end
def sign_up_params
# TODO: Still need to fix this. Strong parameters with nested attributes not working.
# Permitting all is a security hazard.
params.require(:user).permit!
#params.require(:user).permit(:email, :password, :password_confirmation, :profile_attributes)
end
private :sign_up_params
end
So upgrading to Devise 3.1.0 left some 'cruft' in a view that I hadn't touched in a while.
According to this blog post, you need to change your Devise mailer to use #token instead of the old #resource.confirmation_token.
Find this in app/views/<user>/mailer/confirmation_instructions.html.erb and change it to something like:
<p>Welcome <%= #resource.email %>!</p>
<p>You can confirm your account email through the link below:</p>
<p><%= link_to 'Confirm my account', confirmation_url(#resource, :confirmation_token => #token) %></p>
This should fix any token-based confirmation problems you're having. This is likely to fix any unlock or reset password token problems as well.
A friend of mine just found this question and emailed me asking if I had figured this out, which reminded me that I never submitted my own answer, so here goes :)
I ended up resetting the token & using send to get the raw token. It's ugly, but it works in a punch for devise (3.5.1).
26 it "should auto create org" do
27 email = FG.generate :email
28 visit new_user_registration_path
29 fill_in :user_name, with: 'Ryan Angilly'
30 fill_in :user_user_provided_email, with: email
31 fill_in :user_password, with: '1234567890'
32
33 expect do
34 click_button 'Continue'
35 end.to change { Organization.count }.by(1)
36
37 expect(page.current_path).to eq(confirmation_required_path)
38 u = User.where(email: email).first
39 u.send :generate_confirmation_token
40 email_token = u.instance_variable_get(:#raw_confirmation_token)
41 u.save!
42 os = u.organizations
43 expect(os.size).to eq(1)
44 visit user_confirmation_path(confirmation_token: email_token)
45 o = os.first
46
47 u.reload
48 expect(u.confirmed?)
49 expect(page.current_url).to eq(organization_getting_started_url(o))
50 end
As of devise 3.5.2, the confirmation token is no longer digested during the confirmation process. This means that the token in the email will match the token in the database.
I was still having trouble with confirmations after figuring this out, but in my case it turned out to be a bug I introduced when I overrode find_first_by_auth_conditions. By fixing the bug I introduced in that method, I fixed my errors with confirmation.

Rails 3.1. Create one user in console with secure password

I want to create one user (admin) and I want to use console (without user registration model). I use solution from RailsCasts (http://railscasts.com/episodes/270-authentication-in-rails-3-1).
But I have one problem: when I do User.create(..., :password => "pass") in console my password stored in database without encription (like "pass"). And I can't login with my data.
How can I create user from console? :)
Straight from the Rails API
# Schema: User(name:string, password_digest:string)
class User < ActiveRecord::Base
has_secure_password
end
user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
user.save # => false, password required
user.password = "mUc3m00RsqyRe"
user.save # => false, confirmation doesn't match
user.password_confirmation = "mUc3m00RsqyRe"
user.save # => true
user.authenticate("notright") # => false
user.authenticate("mUc3m00RsqyRe") # => user
You need to include :password_confirmation => "pass in your hash!
Right, so taking a look at has_secure_password you want to perform BCrypt::Password.create(unencrypted_password) to obtain it. You'll need the bcrypt-ruby gem to do the above.

Testing Rails Controllers Inherited from Typus

I've been fighting with this for a couple of days and there doesn't seem to be much help online. I've looked at the Typus wiki, sample app, and tests and I appear to be doing things correctly but I stil get HTTP Status Code 302 (Redirect) where I expect 200 (Success) in my tests.
Below are what should be the appropriate files (with irrelevant stuff removed)
config/initializers/typus.rb (rails g typus:migration has been run as I have an admin_users table):
Typus.setup do |config|
# Application name.
config.admin_title = "Something"
# config.admin_sub_title = ""
# When mailer_sender is set, password recover is enabled. This email
# address will be used in Admin::Mailer.
config.mailer_sender = "noreply#somewhere.com"
# Define paperclip attachment styles.
# config.file_preview = :medium
# config.file_thumbnail = :thumb
# Authentication: +:none+, +:http_basic+
# Run `rails g typus:migration` if you need an advanced authentication system.
config.authentication = :session
# Define user_class_name.
config.user_class_name = "AdminUser"
# Define user_fk.
config.user_fk = "admin_user_id"
# Define master_role.
config.master_role = "admin"
end
config/typus/admin_user.yml
AdminUser:
fields:
default: first_name, last_name, role, email, locale
list: email, role, status
form: first_name, last_name, role, email, password, password_confirmation, locale
options:
selectors: role, locale
booleans:
status: Active, Inactive
filters: status, role
search: first_name, last_name, email
application: Admin
description: Users Administration
test/factories/admin_users.rb:
Factory.define :admin_user do |u|
u.first_name 'Admin'
u.last_name 'User'
u.email 'admin#somewhere.com'
u.role 'admin'
u.password 'password!'
u.token '1A2B3C4D5E6F'
u.status true
u.locale 'en'
end
test/functional/admin/credits_controller_test.rb:
require 'test_helper'
class Admin::CreditsControllerTest < ActionController::TestCase
setup do
#admin_user = Factory(:admin_user)
#request.session[:admin_user_id] = #admin_user.id
#request.env['HTTP_REFERER'] = '/admin/credits/new'
end
context "new" do
should "be successful" do
get :new
assert_response :success
end
end
end
#response.body:
<html>
<body>You are being redirected.
</body>
</html>
As you can see, I've set up the typus to use admin_user and admin_user_id for the session key. But for some reason that test fails getting 302 rather than 200. I'm sure this is because I'm doing something wrong that I just don't see. I've also created all these a gist, just in case someone prefers that.
Edited 2011-05-19 09:58am Central Time: Added Response body text per request.
I figured this out. It was a problem with the config/typus/admin_roles.yml file.
Before:
admin:
Category: create, read, update
Credit: read
...
After:
admin:
Category: create, read, update
Credit: read, create
...
The problem was that admin users didn't have access to the CREATE action on the admin/credits_controller which resulted in the user being sent back to the admin login address.
Giving admin users access to the action and changing the
#session[:admin_user_id]
to
#session[:typus_user_id] #Just like in the Typus docs
solved the problem. I had changed it to :admin_user_id because of the
config.user_fk = "admin_user_id"
in the typus config files, while trying to troubleshoot this issue.

Create a devise user from Ruby console

Any idea on how to create and save a new User object with devise from the ruby console?
When I tried to save it, I'm getting always false. I guess I'm missing something but I'm unable to find any related info.
You can add false to the save method to skip the validations if you want.
User.new({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" }).save(false)
Otherwise I'd do this
User.create!({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" })
If you have confirmable module enabled for devise, make sure you are setting the confirmed_at value to something like Time.now while creating.
You should be able to do this using
u = User.new(:email => "user#name.com", :password => 'password', :password_confirmation => 'password')
u.save
if this returns false, you can call
u.errors
to see what's gone wrong.
When on your model has :confirmable option this mean the object user should be confirm first. You can do two ways to save user.
a. first is skip confirmation:
newuser = User.new({email: 'superadmin1#testing.com', password: 'password', password_confirmation: 'password'})
newuser.skip_confirmation!
newuser.save
b. or use confirm! :
newuser = User.new({email: 'superadmin2#testing.com', password: 'password', password_confirmation: 'password'})
newuser.confirm!
newuser.save
If you want to avoid sending confirmation emails, the best choice is:
u = User.new({
email: 'demo#greenant.com.br',
password: '12feijaocomarroz',
password_confirmation: '12feijaocomarroz'
})
u.confirm
u.save
So if you're using a fake email or have no internet connection, that'll avoid errors.
None of the above answers worked for me.
This is what I did:
User.create(email: "a#a.com", password: "asdasd", password_confirmation: "asdasd")
Keep in mind that the password must be bigger than 6 characters.

Resources