Archive for the ‘RubyOnRails’ tag
restful_authentication - autenticação com terceira chave
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:
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!
- Username
- Password
- Filial
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!
Ajax on Rails - Checkbox and Link
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; }
Git on MacOS
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
Womp.us! - new URL Shortcut!
I’m proud to announce Womp.us! new URL Shortcut, try: http://womp.us
