Marcio Garcia

Software Empowerment²

Archive for the ‘Uncategorized’ Category

BlipBadge escolhido!

without comments





O BlipBadge foi escolhido pelo Mergulhão e pela HostNet para ter um ano de hospedagem grátis!

Obrigado pela confiança e vamos que vamos dar uma melhorada no Badge e colocá-lo na casa nova!

Obrigado Mergulhão!

Obrigado HostNet!

Segue o link do resultado: resultado-da-promo-o-de-natal-da-hostnet

Written by Marcio

January 4th, 2009 at 8:44 pm

Posted in Uncategorized

Wordle.net

without comments

My Wordle.net delicious:


First:


Wordle: mangar-delicious-01


Second:


Wordle: mangar-delicious-02



Written by Marcio

January 3rd, 2009 at 11:05 pm

Posted in Uncategorized

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

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

Eclipse / JBoss in Debug mode

without comments

JBoss configuration

Open file run.sh (or run.bat if windows) in <JBOSS>\bin directory, locate the line:

JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true"
replace by:

JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"
JBoss will start to listening on port 8787 for debug.

Eclipse configuration

Click on Run > Open Debug Dialog..
Select Remote Java Application, click on the first icon (New launch configuration)

Replace fields:
Project: your_project_name
Port: 8787

Click in Source tab and “Add” button, Select “Java Project” and “Select All” Button, OK.

If you did the JBoss steps and it is running (if JBoss is not running, that is a good time to put it to run) , click on Debug.

Written by Marcio

August 20th, 2008 at 10:18 pm

Posted in Eclipse, JBoss, Uncategorized

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