Marcio Garcia

Software Empowerment²

Archive for the ‘RubyOnRails’ Category

Ubuntu + Ruby on Rails + Apache + Passenger

without comments

Guia expresso para instalação de um ambiente de produção RoR/Apache/Passenger no Ubuntu

sudo apt-get install rubygems
 
sudo gem install rails
 
sudo apt-get install ruby
 
sudo apt-get install ruby rdoc irb libyaml-ruby libzlib-ruby ri libopenssl-ruby
 
wget http://rubyforge.rubyuser.de/rubygems/rubygems-1.3.1.tgz
 
tar xzvf rubygems-1.3.1.tgz 
 
sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
 
sudo mv /usr/bin/gem /usr/bin/gem-old
 
sudo gem update --system
 
sudo gem install rails
 
sudo apt-get install build-essential ruby1.8-dev
 
sudo gem install mongrel
 
sudo gem install capistrano
 
sudo apt-get install mysql-client mysql-admin mysql-query-browser libmysqlclient15-dev
 
sudo apt-get install sqlite3 swig libsqlite3-ruby libsqlite3-dev
 
sudo gem install sqlite3-ruby
 
echo "export RUBYOPT=rubygems" >> ~/.profile
 
sudo apt-get install build-essential apache2-mpm-prefork apache2-prefork-dev libapr1-dev
 
sudo gem install passenger
 
sudo passenger-install-apache2-module
 

Written by Marcio

January 16th, 2009 at 12:17 am

Posted in Apache, RubyOnRails, Ubuntu

Tagged with , , ,

restful_authentication - autenticação com terceira chave

without comments

Recentemente publiquei um post com screencast a respeito de autenticação com restful_authentication, o Kadu Adu me questionou como fazer autenticação utilizando uma terceira chave como validação, por exemplo:

  • Username
  • Password
  • Filial
Andei dando uma fuçada no código do restful_authentication e encontrei como fazer isso de uma forma bem simples, talvez não a mais correta (?!?!?!) mas consegui resolver o problema do nosso amigo Kadu Adu, segue as alterações logo abaixo.


1 - Arquivo: /app/view/sessions/new.html.erb

<%= flash[:notice] %>
<% form_tag session_path do -%>
<label for="login">Login</label>
<%= text_field_tag 'login' %>
 
<label for="password">Password</label>
<%= password_field_tag 'password' %>
 
<!-- Uncomment this if you want this functionality
<label for="remember_me">Remember me:</label>
<%= check_box_tag 'remember_me' %>
-->
 
<!-- autenticacao com terceira chave.... -->
<label for="filial">Filial</label>
<%= text_field_tag 'filial' %>
<%= submit_tag 'Log in' %>
 
<% end -%>
<%= link_to "Criar usuario",  { :controller => "users", :action => "new" } %>
 -<%= link_to "Login",  { :controller => "sessions", :action => "new" } %>
 -<%= link_to "Sair", { :controller => "sessions", :action => "logout" } %>

2 - Arquivo: app/controller/sessions_controller.rb

# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
 
  # render new.rhtml
  def new
    #alterado....................
    flash[:notice] = "Usuario logado!" if logged_in?
    flash[:notice] = "Usuario NÃO logado!" unless logged_in?
 
  end
 
  def create
 
    #autenticacao com terceira chave......
    self.current_user = User.authenticate(params[:login], params[:password], params[:filial])
    # self.current_user = User.authenticate(params[:login], params[:password])    
 
    if logged_in?
      if params[:remember_me] == "1"
        current_user.remember_me unless current_user.remember_token?
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default('/')
      flash[:notice] = "Logged in successfully"
    else
      render :action => 'new'
    end
  end
 
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default('/')
  end
end

3 - Arquivo: app/model/user.rb

Coloque este método antes da definição do último método que é protected
  #autenticacao com terceira chave.....
  def self.authenticate(login, password, filial)
    u = find_by_login_and_filial(login, filial) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

4 - Arquivo: db/migrate/01_create_user.rb

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table "users", :force => true do |t|
      t.column :login,                     :string
      t.column :email,                     :string
      t.column :crypted_password,          :string, :limit => 40
      t.column :salt,                      :string, :limit => 40
      t.column :created_at,                :datetime
      t.column :updated_at,                :datetime
      t.column :remember_token,            :string
      t.column :remember_token_expires_at, :datetime
 
      #alteracao para terceira chave....
      t.column :filial,                    :string
    end
  end
 
  def self.down
    drop_table "users"
  end
end

Altere o seu banco de dados via rake ou alter table para que a nova coluna filial seja criada e após as alterações com a aplicação no ar, voce poderá verificar que se passado apenas um usuário e senha válidos sem que a filial seja correta o sistema não autenticará o usuário.

Fiz este código bem rápido, pode ser que esta não seja a melhor solução, se alguém tiver uma melhor saída, fell free to contribute!

Enjoy!

Written by Marcio

November 10th, 2008 at 9:23 pm

Screencast - restful_authentication

with 3 comments


restful_authentication - Screencast (pt-br) from Marcio Garcia on Vimeo.

Instalação do restful_authentication

URL do plugin:

http://svn.techno-weenie.net/projects/plugins/restful_authentication/

./scrpt/plugin source http://svn.techno-weenie.net/projects/plugins/restful_authentication/
 
./script/plugin install restful_authentication

Criação dos controllers e model padrão
./script/generate authenticated user sessions

Alterações de código

routes.rb
#novas rotas....
map.signup '/', :controller => 'sessions', :action => 'new'
map.signup '/signup', :controller => 'users', :action => 'new'
map.login  '/login',  :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'

app/views/layouts/application.html.erb
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <%= stylesheet_link_tag 'scaffold' %>
</head>
<body bgcolor="#1471B7">
<center>
<p>&nbsp;</p>
<table width="90%"  bgcolor="#FFFFFF">
	<tr>
		<td align="center">
		<%= yield%>			
		</td>
	</tr>
</table>
</center>
</body>
</html>





app/controllers/application.rb
include AuthenticatedSystem

app/controllers/sessions_controller.rb
def new
  #alterado....................
  flash[:notice] = "Usuario logado!" if logged_in?
  flash[:notice] = "Usuario NÃO logado!" unless logged_in?
end

app/controllers/users_controller.rb
#alterado......................
before_filter :authentication
def authentication
  redirect_back_or_default('/') unless logged_in?
end

Código fonte

rademo.zip

Written by Marcio

November 7th, 2008 at 12:13 am

Ajax on Rails - Checkbox and Link

without comments

This two samples of how to use a checkbox and a link to call remote methods on server (AJAX):

Checkbox

<%= text_field_tag :zip1, "#{@cart.zip1}" %>
<%= text_field_tag :zip2, "#{@cart.zip2}" %>			
<%= check_box_tag ("id","id", false, 
    :onclick => remote_function(
      :update => "jstemp", 
      :url => { :action => :update_zip }, 
      :with => "'value='+$('zip1').value+'+'+$('zip2').value", 
      :complete => "updateZipAndPrice()"  ))%> 

Link

<%= link_to_remote (image_tag("bt_calcular.png"),
  :url => { :action => :update_zip }, 
  :with => "'value='+$('zip1').value+'+'+$('zip2').value", 
  :complete => "updateZipAndPrice()",
  :update => "jstemp" ) %>

  • image_tag: function to display the image
  • :action: method inside the controller
  • :with: parameters sent to action
  • :complete: JavaScript function that will be called when the AJAX call is over
  • :update: html object when the content of the return method (:action) will be stored. My “jstemp” is just a div tag like this:

Controller Action

As return of the controller you can choose to return a JSON object like this:

render :text =>  
"{\"checkout\": { \"zipprice\": \"\", \"checkouttotalvalue\": \"#{str_valor_total.real_formatado}\"}}"

HTML / Javascript

And as a handler for the JSON I used this small and smart Javascript function:
function updateZipAndPrice() {
 var myJSONtext = $('jstemp').innerHTML;
 var myJSONObject = eval('(' + myJSONtext + ')');
 $('freteValue').innerHTML = myJSONObject.checkout.zipprice;
 $('checkoutValue').innerHTML = myJSONObject.checkout.checkouttotalvalue;
}

Written by Marcio

September 28th, 2008 at 4:51 pm

Posted in RubyOnRails, Uncategorized

Tagged with

Git on MacOS

without comments

Today I decide to install git (I prefer do not mention about problems with svn lock file) but I was with some problems with port (sudo port install git-core +svn) so I found this commands on the web that was very helpful:

wget http://www.kernel.org/pub/software/scm/git/git-1.5.3.8.tar.gz
tar xzvf  git-1.5.3.8.tar.gz
cd git-1.5.3.8
./configure
sudo make && sudo make install

Written by Marcio

September 26th, 2008 at 10:55 pm

Posted in Git, RubyOnRails

Tagged with ,

Womp.us! - new URL Shortcut!

without comments

I’m proud to announce Womp.us! new URL Shortcut, try: http://womp.us

Written by Marcio

August 16th, 2008 at 12:05 am

Posted in RubyOnRails, Uncategorized

Tagged with