2

Desinfecta tu html (sanitizer)

Posted by mauro on Jun 12, 2009 in Rails

simple_sanitizer_html es un plugin muy sencillo que arme para Rails, que te permite básicamente escapar el html.
Lo interesante de este plugin es que solo debemos extender el modelo y de forma automática guarda todo los registros escapando el html en la base de datos.

Instalar simple_sanitizer_html

  http://github.com/chebyte/simple_sanitizer_html/tree/master

Uso Práctico

# ruby script/generate model Post title:string copy:text
class Post
 simple_sanitizer_html
end
$ ruby script/console 
Loading development environment (Rails 2.3.2)
p >> p = Post.new
=> #<Post id: nil, title: nil, copy: nil, created_at: nil, updated_at: nil>
>> p.title = "<script>alert('hi tuquito')</script>"
=> "<script>alert('hi tuquito')</script>"
>> p.save
=> true
>> p.title
=> "&lt;script&gt;alert(&#39;hi tuquito&#39;)&lt;/script&gt;"
>>

Este plugin puede ser muy útil para prevenir ataques XSS o del estilo

 
1

Google Scrap con Rails

Posted by mauro on Jun 12, 2009 in Rails

web_search_plugin es un nuevo plugin de Rails que hice, para poder obtener los resultados de una determinada consulta en google y mostrarla en tu sitio. Hasta el momento solo realiza búsquedas en Google, a futuro lo voy a integrar con Yahoo y Live.

Instalar web_search_plugin

# cd myapprails
# ruby script/plugin install git@github.com:chebyte/web_search_plugin.git

Uso
Como ejemplo, tenemos el modelo #link.rb

 class Link < ActiveRecord::Base
   include Chebyte::WebSearch
   web_search
 end

Ahora para obtener los resultados solo debemos llamar al método search_web

 Link.google_search(:query => "tuquito")

esto nos devolveria

=> #<Google::Response:0xb734d3cc @results=[{:domain=>"www.tuquito.org.ar", :content=>"Proyecto Linux de Tucumán, datos y temas relacionados al proyecto, foros y ayuda para usuarios de la distribución y descargas.", :title=>"Tuquito 3", :cache_url=>"http://www.google.com/search?q=cache:4NZXKc3gQA8J:www.tuquito.org.ar", :url=>"http://www.tuquito.org.ar/"}, {:domain=>"en.wikipedia.org", :content=>"Oct 11, 2008 ... Tuquito is a Debian-based operating system created in Tucumán, Argentina, by Ignacio Díaz, Chris Arenas and Mauro Torres, students of The ...", :title=>"Tuquito - Wikipedia, the free encyclopedia", :cache_url=>"http://www.google.com/search?q=cache:a1xAEvHHujUJ:en.wikipedia.org", :url=>"http://en.wikipedia.org/wiki/Tuquito"}, {:domain=>"www.slideshare.net", :content=>"Tuquito 3 Nuevo Diseño En varios idiomas (Ingles,Portugues y Español) Interfaces mas intuitivas Optimizado para la conectividad(wifi, ...", :title=>"Tuquito 3", :cache_url=>"http://www.google.com/search?q=cache:T8VfO-4iyioJ:www.slideshare.net", :url=>"http://www.slideshare.net/chebyte/tuquito-3"}, {:domain=>"www.olpcnews.com", :content=>"OLPC Tuquito's team began to work at 1st January of 2007, with the knowledge acquisition about the project One Laptop Per Child and then with development ...", :title=>"OLPC Tuquito Project Progress in Argentina - OLPC News", :cache_url=>"http://www.google.com/search?q=cache:eoGfDNbaZ8kJ:www.olpcnews.com", :url=>"http://www.olpcnews.com/countries/argentina/olpc_tuquito_project_argentina.html"}], @status=200, @size=4, @query="tuquito">

El resultado es un simple objecto hash, algunos de los campos disponibles son
* title titulo del resultado
* url Url del resultado
* domain Root url del resultado
* content contenido
* cache_url Google cache url

 
0

Configurar passenger con nginx

Posted by mauro on Jun 7, 2009 in Rails

Instalar Ruby Enterprise Edition

sudo apt-get install build-essential zlib1g-dev libssl-dev libreadline5-dev
wget http://rubyforge.org/frs/download.php/51100/ruby-enterprise-1.8.6-20090201.tar.gz
tar xvfz ruby-enterprise-1.8.6-20090201.tar.gz 
rm ruby-enterprise-1.8.6-20090201.tar.gz 
cd ruby-enterprise-1.8.6-20090201/
sudo ./installer

Agregar ruby entrerprise al path del sistema

echo "export PATH=/opt/ruby-enterprise-1.8.6-20090201/bin:$PATH" >> ~/.profile && . ~/.profile

Nginx

sudo /opt/ruby-enterprise-1.8.6-20090201/bin/passenger-install-nginx-module

Elegir la opcion 1. Yes: download, compile and install Nginx for me. (recommended)

Script de inicio Nginx

Agregar el siguiente codigo en

/etc/init.d/nginx
sudo chown root:root /etc/init.d/nginx

Probar una aplicacion rails en nginx
agregar un virtual host

server {
    listen 80;
    # server_name www.mycook.com;
    root /home/deploy/testapp/public;
    passenger_enabled on;
}

 
0

Configurar un servidor con thin y nginx

Posted by mauro on Jun 7, 2009 in Rails

Instalar thin

  sudo gem install thin

Configurar thin en el sistema

 sudo thin install

Configurar thin en nginx

sudo thin config -C /etc/thin/<config-name>.yml -c <rails-app-root-path> --servers <number-of-threads> -e <environment> --socket /tmp/thin.sock

Reemplaza config-name con el nombre del archivo de configuracion, rails-app-root-path con la ruta de tu aplicacion rails, number-of-threads con el numero de procesos de thin que quieres iniciar y  environment con el enviroment que quieres inicializar, por ejemplo

$ sudo thin config -C /etc/thin/chebyte.com.ar.yml -c /var/rails/chebyte --servers 5 -e production --socket /tmp/thin.sock

Esto nos generara el siguiente archivo en /etc/thin

---
pid: tmp/pids/thin.pid
socket: /tmp/thin.sock
log: log/thin.log
timeout: 30
max_conns: 1024
chdir: /var/ror/chebyte
max_persistent_conns: 512
environment: production
servers: 4
daemonize: true
require: []

Iniciamos thin

/etc/init.d/thin start

–socket /tmp/thin.sock esta opcion permite que nginx se comunique con thin mediante socket y no mediante una interace ethernet interna, muy recomendado para obtener mas perfomance

Configurar thin en nginx

user nginx;
worker_processes 5;
 
error_log /var/log/nginx.error.log;
pid /var/run/nginx.pid;
 
events {
  worker_connections 1024;
}
 
http {
  include mime.types;
  default_type application/octet-stream;
 
  log_format main '$remote_addr - $remote_user [$time_local] $request '
                      '"$status" $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
  access_log /var/log/nginx.access.log main;
 
  sendfile on;
 
  keepalive_timeout 65;
 
  upstream thin_cluster {
    server unix:/tmp/thin.0.sock;
    server unix:/tmp/thin.1.sock;
    server unix:/tmp/thin.2.sock;
    server unix:/tmp/thin.3.sock;
    server unix:/tmp/thin.4.sock;
  }
 
  server {
    listen 80;
    server_name www.myserver.com;
 
    root /var/rails/mysapp/public;
 
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect false;
 
      if (-f $request_filename/index.html) {
        rewrite (.*) $1/index.html break;
      }
      if (-f $request_filename.html) {
        rewrite (.*) $1.html break;
      }
      if (!-f $request_filename) {
        proxy_pass http://thin_cluster;
        break;
      }
    }
 
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      root html;
    }
  }
}

Copyright © 2010 Chebyte’s Blog All rights reserved.