vi /etc/nginx/nginx.confadd or modify the following line inside http {…}
client_max_body_size 20M;vi /etc/nginx/nginx.confclient_max_body_size 20M;
1
|
# gem 'bcrypt-ruby', '~> 3.0.0'
|
1
2 3 4 5 |
group :test do
... gem 'email_spec' ... end |
1
|
require 'email_spec'
|
1
2 3 4 5 6 |
RSpec.configure do |config|
... config.include(EmailSpec::Helpers) config.include(EmailSpec::Matchers) ... end |
1
|
/spec/features/users_spec.rb
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
require 'spec_helper'
feature 'User Management', %q{ As the site owner I want to provide an user management so that I can protect functions and grant access based on roles } do background do @agent = create(:user,:agent) end scenario 'Real estate agent sign up' do visit root_path click_link 'Sign Up' fill_in 'user[name]', with: 'Jane Doe' fill_in 'user[email]', with: 'newagent@example.com' fill_in 'user[password]', with: 'newpassword' fill_in 'user[password_confirmation]', with: 'newpassword' click_button 'Submit' expect(page).to have_content "Sign up complete. Please check your inbox for activation email." end scenario 'Real estate agent activation' do activate(@agent) expect(page).to have_content "Activation complete. Welcome #{@agent.name}" end scenario 'User log in' do activate(@agent) login(@agent) expect(page).to have_content "Successfully logged in." end scenario 'User log out' do activate(@agent) login(@agent) logout(@agent) expect(page).to have_content "Successfully logged out." end scenario 'Inactive User are not able to login' do login(@agent) expect(page).to have_content "Account inactive. Please activate your account." end scenario 'Agents have access to their office page' do activate(@agent) login(@agent) visit office_path expect(page).to have_content "Welcome to your office, #{@agent.name}" end scenario 'Visitors dont have access to any office' do visit office_path expect(page).to have_content "This site is protected. Please log in first." end scenario 'Users with no agent role dont have office access' do @agent.destroy @noagent = create(:user,:no_agent) activate(@noagent) login(@noagent) visit office_path expect(page).to have_content "Access denied. Insufficent rights." end end |
1
|
/spec/support/users_helper.rb
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
module UserHelper
def login(a) visit root_path click_link 'Log In' fill_in 'session[email]', with: a.email fill_in 'session[password]', with: a.password click_button 'Log In' end def logout(a) visit root_path click_link 'Log Out' end def activate(a) visit activate_path(:code => a.activation_code) end end |
1
2 3 4 5 |
RSpec.configure do |config|
... config.include(UserHelper) ... end |
1
|
rails g model User email:string password_digest:string name:string is_admin:boolean role:string activation_code:string
|
1
2 |
bundle exec rake db:migrate
bundle exec rake db:test:clone |
1
|
User.delete_all
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
require 'spec_helper'
describe User do it "is valid with name, email and password confirmation" do u = create(:user, :agent) expect(u).to be_valid end it "sends a confirmation email after sign up" do u = create(:user, :agent) open_last_email.should be_delivered_to u.email end it "is invalid without email" do u = build(:user, :agent, :email=> nil) expect(u).to have(1).errors_on(:email) end it "is invalid without name" do u = build(:user, :agent, :name=> nil) expect(u).to have(1).errors_on(:name) end it "is invalid if passwords don't match" do u = build(:user, :agent, :password => "pw1", :password_confirmation => "wp1") expect(u).to have(1).errors_on(:password) end it "is invalid if no activation code is generated" do u = create(:user, :agent) expect(u.activation_code).to_not be_nil end end |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do factory :user do email "john@example.com" password "secret" name "John Doe" trait :no_agent do role "no_agent" end trait :agent do role "agent" end trait :admin do is_admin true end end end |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class User < ActiveRecord::Base
has_secure_password attr_accessible :email, :is_admin, :name, :role, :activation_code, :password, :password_confirmation validates :name, :presence => true validates :email, :presence => true before_create :create_activation_code after_create :send_confirmation_email def send_confirmation_email UserMailer.confirmation_email(self).deliver end def create_activation_code self.activation_code = random_string(length=10) end def random_string(length=10) (1..length).collect {alphanumeric_characters.sample}.join end def alphanumeric_characters ("a".."z").to_a + ("0".."9").to_a end def is_active? self.activation_code == nil end end |
1
|
rails g mailer UserMailer
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
require "spec_helper"
describe UserMailer do include Rails.application.routes.url_helpers before(:all) do @user = create(:user,:agent) @email = UserMailer.confirmation_email(@user) end it "should be sent to the user email" do @email.should deliver_to(@user.email) end it "should contain the activation link inside" do pending("Uncomment after activation function works") # @email.should have_body_text(/#{activate_path(:code => @user.activation_code)}/) end end |
1
2 3 4 5 6 7 8 9 |
class UserMailer < ActionMailer::Base
default from: "byorels@example.com" def confirmation_email(user) @user = user mail(:to => user.email, :subject => "Please Activate Your Account") end end |
1
|
rails g controller users new
|
1
|
resources :users
|
1
|
<%= link_to "Sign Up", new_user_path %>
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<div class="page-header">
<h1>Sign Up</h1> </div> <%= form_for @user, :html => { :class => 'form-horizontal' } do |f| %> <% if @user.errors.any? %> <div class="alert alert-error"> <a class="close" data-dismiss="alert">×</a> <% for message in @user.errors.full_messages %> <%= message %><br /> <% end %> </div> <% end %> <div class="control-group"> <%= f.label :name, :class => 'control-label' %> <div class="controls"> <%= f.text_field :name, :class => 'text_field' %> </div> </div> <div class="control-group"> <%= f.label :email, :class => 'control-label' %> <div class="controls"> <%= f.text_field :email, :class => 'text_field' %> </div> </div> <div class="control-group"> <%= f.label :password, :class => 'control-label' %> <div class="controls"> <%= f.password_field :password, :class => 'text_field' %> </div> </div> <div class="control-group"> <%= f.label :password_confirmation, :class => 'control-label' %> <div class="controls"> <%= f.password_field :password_confirmation, :class => 'text_field' %> </div> </div> <div class="form-actions"> <%= f.hidden_field :role, :value => "agent" %> <%= f.submit 'Submit', :class => 'btn btn-primary' %> </div> <% end %> |
1
2 3 |
def new
@user = User.new(:role => "agent") end |
1
2 3 4 5 6 7 8 |
def create
@user = User.new(params[:user]) if @user.save redirect_to root_path, notice: 'Sign up complete. Please check your inbox for activation email.' else render action: "new" end end |
1
2 3 4 5 6 7 8 9 |
def activate
@user = User.find_by_activation_code(params[:code]) @user.activation_code = nil if @user.save redirect_to root_path, notice: "Activation complete. Welcome #{@user.name}" else render action: "new" end end |
1
|
get "activate/:code" => "users#activate", :as => "activate"
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!DOCTYPE html>
<html> <head> <title>Tutorial</title> <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> </head> <body> <div class="container"> <% if flash[:notice] -%> <div class = "alert alert-success"> <a class="close" data-dismiss="alert">×</a> <%= flash[:notice] %> </div> <% end %> <% if flash[:error] -%> <div class = "alert alert-error"> <a class="close" data-dismiss="alert">×</a> <%= flash[:error] %> </div> <% end %> <% if flash[:warning] -%> <div class = "alert alert-warning"> <a class="close" data-dismiss="alert">×</a> <%= flash[:warning] %> </div> <% end %> <%= yield %> </div> </body> </html> |
1
2 3 4 5 |
<%= @user.name %>, please activate your account.
Activation link: <%= "http://www.example.com/"+activate_path(:code => @user.activation_code) %> Thanks for signing up! |
1
|
rails g controller sessions new
|
1
|
resource :session
|
1
|
<%= link_to "Log In", new_session_path %>
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<div class="page-header">
<h1>Log In</h1> </div> <%= form_for :session, :url => session_path, :html => { :class => 'form-horizontal' } do |f| %> <div class="control-group"> <%= f.label :email, :class => 'control-label' %> <div class="controls"> <%= f.text_field :email, :class => 'text_field' %> </div> </div> <div class="control-group"> <%= f.label :password, :class => 'control-label' %> <div class="controls"> <%= f.password_field :password, :class => 'text_field' %> </div> </div> <div class="form-actions"> <%= f.submit 'Log In', :class => 'btn btn-primary' %> </div> <% end %> |
1
2 3 4 5 6 7 8 9 10 11 12 13 |
def create
user = User.find_by_email(params[:session][:email]).try(:authenticate, params[:session][:password]) if user if user.is_active? session[:user_id] = user.id redirect_to (session[:target_url] || root_path), :notice => "Successfully logged in." else redirect_to new_session_path, :flash => { :error => "Account inactive. Please activate your account." } end else redirect_to new_session_path, :flash => { :error => "Invalid username or password." } end end |
1
2 3 4 |
def destroy
session[:user_id] = nil redirect_to root_path, :notice => "Successfully logged out." end |
1
|
<%= link_to "Log Out", "/session", :method => "DELETE" %>
|
1
|
rails g controller offices show
|
1
|
resource :office
|
1
2 3 |
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id] end |
1
2 3 4 5 |
class ApplicationController < ActionController::Base
... helper_method :current_user ... end |
1
2 3 4 5 6 |
def auth_required
unless current_user session[:target_url] = request.fullpath redirect_to new_session_path, :flash => { :error => "This site is protected. Please log in first." } end end |
1
2 3 4 5 6 7 8 |
def access_only_with_roles(*roles)
if current_user unless roles.include? current_user.role session[:target_url] = request.fullpath redirect_to new_session_path, :flash => { :warning => "Access denied. Insufficent rights." } end end end
This function we use to limit the access to certain roles. In each
action we want to protect we can use the following syntax to limit the
access:
|
sudo yum -y update sudo ln -sf /usr/share/zoneinfo/America/Indianapolis \ /etc/localtime sudo yum -y install gcc make
wget http://redis.googlecode.com/files/redis-2.6.0-rc3.tar.gz tar xzf redis-2.6.0-rc3.tar.gz cd redis-2.6.0-rc3 make
sudo mkdir /etc/redis /var/lib/redis sudo cp src/redis-server src/redis-cli /usr/local/bin sudo cp redis.conf /etc/redis
sudo nano /etc/redis/redis.conf
[..] daemonize yes [..]
[..] bind 127.0.0.1 [..]
[..] dir /var/lib/redis [..]
wget https://raw.github.com/saxenap/install-redis-amazon-linux-centos/master/redis-server
sudo mv redis-server /etc/init.d sudo chmod 755 /etc/init.d/redis-server sudo nano /etc/init.d/redis-server
redis="/usr/local/bin/redis-server"
sudo chkconfig --add redis-server sudo chkconfig --level 345 redis-server on
sudo service redis-server start
brew install elasticsearchcurl -X GET http://localhost:9200/ in the terminal.
rails new demoapp
cd demoapp
echo "gem 'elasticsearch-rails'" >> Gemfile
echo "gem 'elasticsearch-model'" >> Gemfile
bundle
Create the Article model and populate the db with some data that we will search against later:
rails g model article title:string body:text
rake db:migrate
rails c
hello_world = Article.create title: 'Hello World', body: 'Lovely day!'
power_search = Article.create title: 'Power Search', body: 'Elasticsearch rules the world!'
(Those variable names will be used later in the examples, so keep them noted).
class Article < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
end
Add this line to the top of the app Rakefile to include the handy elasticsearch rake tasks:require 'elasticsearch/rails/tasks/import'
The new tasks can be listed with bundle exec rake -D elasticsearch.bundle exec rake environment elasticsearch:import:all
We can do the very same thing in the rails console:Article.import
search = Article.search 'world'
This will return an object with class Elasticsearch::Model::Response::Responseresultsmethod, which conveniently wraps the JSON returned by Elasticsearch in ruby objects:
search.results.map { |res| res.title }
# => ["Hello World", "Power Search"]
If you want to see the actual found records, then you just need to call records on that object:search.records
The above query could be rewritten using Elasticsearch JSON DSL syntax like follows:Article.search('{"query": {"match": {"_all": "world"}}}').records
Luckily the gem allows us to use both JSON or ruby hash syntax and of course we prefer the latter, don’t we? All the following examples will use ruby hashes.title field:
records = Article.search(query: {multi_match: {query: 'world', fields: ['title^10', 'body']}}).records
records.size # => 2
records.first == hello_world # => true
Let’s change the records order boosting the body field instead:
records = Article.search(query: {multi_match: {query: 'world', fields: ['title', 'body^10']}}).records
records.first == power_search # => true
fuzziness param:
records = Article.search(query: {match: {_all: {query: 'wold', fuzziness: 2}}}).records
records.first.title # => "Hello World"
fuzziness represents the maximum allowed Levenshtein distance, it accepts an integer between 0 and 2 (where 2 means the fuzziest search possible) or the string “AUTO” which will generate an edit distance based on the charachers length of the terms in the query.<a href='http://www.facebook.com/sharer.php?s=100&p[title]=WEB1CHANNEL&p[summary]=Web+Design+Company+in+Dubai.&p[url]=http://www.webchannel.ae&p[images][0]=http://qacode.com/test.jpg'>Facebook Share</a>