Browse Source

Clean whitespaces and add missing empty lines

pull/1/head
Marius Karnauskas 9 years ago
parent
commit
358a65ecdb
  1. 32
      app/controllers/application_controller.rb
  2. 14
      app/controllers/concerns/records_controller_common.rb
  3. 16
      app/controllers/public/pages_controller.rb
  4. 8
      app/controllers/users/aaaas_controller.rb
  5. 10
      app/controllers/users/as_controller.rb
  6. 10
      app/controllers/users/cnames_controller.rb
  7. 20
      app/controllers/users/domains_controller.rb
  8. 10
      app/controllers/users/hosts_controller.rb
  9. 10
      app/controllers/users/mxes_controller.rb
  10. 12
      app/controllers/users/ns_controller.rb
  11. 16
      app/controllers/users/omniauth_callbacks_controller.rb
  12. 8
      app/controllers/users/permissions_controller.rb
  13. 16
      app/controllers/users/records_controller.rb
  14. 2
      app/controllers/users/registrations_controller.rb
  15. 10
      app/controllers/users/soas_controller.rb
  16. 12
      app/controllers/users/srvs_controller.rb
  17. 8
      app/controllers/users/txts_controller.rb
  18. 4
      app/controllers/users_controller.rb
  19. 12
      app/helpers/application_helper.rb
  20. 2
      app/helpers/users/authentications_helper.rb
  21. 4
      app/helpers/users/domains_helper.rb
  22. 2
      app/helpers/users/records_helper.rb
  23. 4
      app/mailers/contact_form.rb
  24. 2
      app/mailers/users/permission_mailer.rb
  25. 8
      app/models/a.rb
  26. 4
      app/models/aaaa.rb
  27. 4
      app/models/admin.rb
  28. 2
      app/models/admin_ability.rb
  29. 2
      app/models/authentication.rb
  30. 4
      app/models/blacklisted_domain.rb
  31. 2
      app/models/cname.rb
  32. 8
      app/models/concerns/stampable.rb
  33. 32
      app/models/domain.rb
  34. 8
      app/models/domain/name_change_records.rb
  35. 18
      app/models/domain/name_change_subdomains.rb
  36. 34
      app/models/domain/tree_structure.rb
  37. 10
      app/models/mx.rb
  38. 2
      app/models/ns.rb
  39. 14
      app/models/permission.rb
  40. 30
      app/models/record.rb
  41. 18
      app/models/soa.rb
  42. 14
      app/models/srv.rb
  43. 8
      app/models/tld.rb
  44. 12
      app/models/txt.rb
  45. 40
      app/models/user.rb
  46. 22
      app/models/user_ability.rb
  47. 12
      app/validators/hostname2_validator.rb
  48. 10
      app/validators/ip_validator.rb
  49. 10
      app/validators/zone_validator.rb
  50. 8
      config/application.rb
  51. 6
      config/deploy.rb
  52. 2
      config/deploy/production.rb
  53. 2
      config/deploy/staging.rb
  54. 4
      config/environments/development.rb
  55. 8
      config/environments/production.rb
  56. 2
      config/environments/test.rb
  57. 20
      config/initializers/cancan.rb
  58. 2
      config/initializers/devise.rb
  59. 8
      config/initializers/navigasmic.rb
  60. 2
      config/initializers/paper_trail.rb
  61. 444
      config/initializers/rails_admin.rb
  62. 2
      config/initializers/rails_config.rb
  63. 2
      config/initializers/session_store.rb
  64. 14
      config/initializers/simple_form.rb
  65. 14
      config/routes.rb
  66. 8
      spec/controllers/users/domains_controller_spec.rb
  67. 4
      spec/controllers/users/hosts_controller_spec.rb
  68. 10
      spec/controllers/users/records_controller_spec.rb
  69. 14
      spec/factories.rb
  70. 30
      spec/features/devise_spec.rb
  71. 2
      spec/features/simple_api_spec.rb
  72. 4
      spec/lib/dnsbl_spec.rb
  73. 2
      spec/mailers/users/permission_mailer_spec.rb
  74. 2
      spec/models/admin_spec.rb
  75. 42
      spec/models/domain_spec.rb
  76. 4
      spec/models/permission_spec.rb
  77. 38
      spec/models/record_spec.rb
  78. 2
      spec/models/tld_spec.rb
  79. 12
      spec/models/user_ability_spec.rb
  80. 4
      spec/models/user_spec.rb
  81. 4
      spec/support/application.rb
  82. 2
      spec/support/database_rewinder.rb
  83. 1
      spec/support/factory_girl.rb
  84. 8
      spec/support/rspec.rb
  85. 14
      spec/support/shared_context/data.rb
  86. 16
      spec/support/shared_examples/wiring_controller.rb

32
app/controllers/application_controller.rb

@ -1,17 +1,17 @@
class ApplicationController < ActionController::Base class ApplicationController < ActionController::Base
protect_from_forgery protect_from_forgery
before_filter :check_honeypot before_filter :check_honeypot
around_filter :set_timezone around_filter :set_timezone
helper_method :client_remote_ip helper_method :client_remote_ip
layout :scoped_layout layout :scoped_layout
rescue_from ActiveScaffold::ActionNotAllowed do |exception| rescue_from ActiveScaffold::ActionNotAllowed do |exception|
flash.now[:error] = I18n.t("errors.action_not_allowed") flash.now[:error] = I18n.t("errors.action_not_allowed")
render_access_denied render_access_denied
end end
protected protected
def set_timezone def set_timezone
old_time_zone = Time.zone old_time_zone = Time.zone
Time.zone = cookies[:time_zone] if cookies[:time_zone].present? Time.zone = cookies[:time_zone] if cookies[:time_zone].present?
@ -19,13 +19,13 @@ class ApplicationController < ActionController::Base
ensure ensure
Time.zone = old_time_zone Time.zone = old_time_zone
end end
def scoped_layout def scoped_layout
return false if request.xhr? return false if request.xhr?
return 'admin' if devise_controller? && resource_name == :admin return 'admin' if devise_controller? && resource_name == :admin
user_signed_in? ? 'users' : 'public' user_signed_in? ? 'users' : 'public'
end end
def render_access_denied def render_access_denied
layout = request.xhr? ? false : 'errors' layout = request.xhr? ? false : 'errors'
render :template => 'errors/access_denied', :layout => layout render :template => 'errors/access_denied', :layout => layout
@ -34,36 +34,36 @@ class ApplicationController < ActionController::Base
def client_remote_ip def client_remote_ip
@client_remote_ip ||= Settings.uses_proxy ? request.remote_ip : request.ip @client_remote_ip ||= Settings.uses_proxy ? request.remote_ip : request.ip
end end
def check_honeypot def check_honeypot
render :nothing => true if params[Settings.honeypot].present? render :nothing => true if params[Settings.honeypot].present?
end end
def after_sign_out_path_for(resource_or_scope) def after_sign_out_path_for(resource_or_scope)
page_path('signed_out') page_path('signed_out')
end end
def current_ability def current_ability
@current_ability ||= ::UserAbility.new(current_user) @current_ability ||= ::UserAbility.new(current_user)
end end
class UserParameterSanitizer < Devise::ParameterSanitizer class UserParameterSanitizer < Devise::ParameterSanitizer
def sign_up def sign_up
default_params.permit(:full_name, :email, :password) default_params.permit(:full_name, :email, :password)
end end
def account_update def account_update
default_params.permit(:full_name, :email, :password, :current_password) default_params.permit(:full_name, :email, :password, :current_password)
end end
end end
def devise_parameter_sanitizer def devise_parameter_sanitizer
super unless resource_class == User super unless resource_class == User
UserParameterSanitizer.new(User, :user, params) UserParameterSanitizer.new(User, :user, params)
end end
def user_for_paper_trail def user_for_paper_trail
if user_signed_in? if user_signed_in?
current_user.to_paper_trail current_user.to_paper_trail
@ -71,5 +71,5 @@ class ApplicationController < ActionController::Base
"Public ip:#{client_remote_ip}" "Public ip:#{client_remote_ip}"
end end
end end
end end

14
app/controllers/concerns/records_controller_common.rb

@ -1,26 +1,26 @@
# some common bits of code for records related controllers # some common bits of code for records related controllers
module RecordsControllerCommon module RecordsControllerCommon
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
before_filter :ensure_nested_under_domain before_filter :ensure_nested_under_domain
end end
protected protected
def before_create_save(record) def before_create_save(record)
record.domain = nested_parent_record record.domain = nested_parent_record
record.user = record.domain_user record.user = record.domain_user
end end
def nested_via_records? def nested_via_records?
nested? && nested.association && nested.association.collection? && nested? && nested.association && nested.association.collection? &&
nested.association.name == :records nested.association.name == :records
end end
# override to close create form after success # override to close create form after success
# RecordsController is the only one that does not really need this # RecordsController is the only one that does not really need this
def render_parent? def render_parent?
nested_singular_association? # || params[:parent_sti] nested_singular_association? # || params[:parent_sti]
end end
end end

16
app/controllers/public/pages_controller.rb

@ -1,5 +1,5 @@
class Public::PagesController < PublicController class Public::PagesController < PublicController
rescue_from ActionView::MissingTemplate do |exception| rescue_from ActionView::MissingTemplate do |exception|
if exception.message =~ %r{Missing template pages/} if exception.message =~ %r{Missing template pages/}
raise ActionController::RoutingError, "No such page: #{params[:id]}" raise ActionController::RoutingError, "No such page: #{params[:id]}"
@ -10,7 +10,7 @@ class Public::PagesController < PublicController
def show def show
return redirect_to(domains_path) if user_signed_in? && params[:id] == "home" return redirect_to(domains_path) if user_signed_in? && params[:id] == "home"
options = {template: current_page} options = {template: current_page}
case params[:id] case params[:id]
when "contact" when "contact"
@ -24,10 +24,10 @@ class Public::PagesController < PublicController
redirect_to after_sign_in_path_for(current_user) and return redirect_to after_sign_in_path_for(current_user) and return
end end
end end
render options render options
end end
def contact def contact
@contact_form = ContactForm.new(params[:contact_form]) @contact_form = ContactForm.new(params[:contact_form])
if !@contact_form.deliver if !@contact_form.deliver
@ -38,19 +38,19 @@ class Public::PagesController < PublicController
end end
protected protected
def current_page def current_page
@current_page ||= "public/pages/#{clean_path}" @current_page ||= "public/pages/#{clean_path}"
end end
def clean_path def clean_path
Pathname.new("/#{params[:id]}").cleanpath.to_s[1..-1] Pathname.new("/#{params[:id]}").cleanpath.to_s[1..-1]
end end
def resource; User.new end def resource; User.new end
helper_method :resource helper_method :resource
def resource_name; :user end def resource_name; :user end
helper_method :resource_name helper_method :resource_name
end end

8
app/controllers/users/aaaas_controller.rb

@ -10,13 +10,13 @@ class Users::AaaasController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.aaaa_records : super).readonly(false) (nested_via_records? ? nested_parent_record.aaaa_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -24,4 +24,4 @@ class Users::AaaasController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
end end

10
app/controllers/users/as_controller.rb

@ -12,7 +12,7 @@ class Users::AsController < UsersController
type: :member, position: false, confirm: 'Are you sure?' type: :member, position: false, confirm: 'Are you sure?'
end end
include RecordsControllerCommon include RecordsControllerCommon
def new_token def new_token
process_action_link_action do |record| process_action_link_action do |record|
record.instance_variable_set(:@readonly, false) record.instance_variable_set(:@readonly, false)
@ -23,13 +23,13 @@ class Users::AsController < UsersController
end end
end end
end end
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.a_records : super).readonly(false) (nested_via_records? ? nested_parent_record.a_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -38,4 +38,4 @@ class Users::AsController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
end end

10
app/controllers/users/cnames_controller.rb

@ -11,18 +11,18 @@ class Users::CnamesController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.cname_records : super).readonly(false) (nested_via_records? ? nested_parent_record.cname_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
before_create_save(record) before_create_save(record)
record record
end end
end end

20
app/controllers/users/domains_controller.rb

@ -21,28 +21,28 @@ class Users::DomainsController < UsersController
end end
conf.list.sorting = [{rgt: :desc}, {lftp: :asc}] # preorder conf.list.sorting = [{rgt: :desc}, {lftp: :asc}] # preorder
conf.columns[:name].css_class = 'sorted' conf.columns[:name].css_class = 'sorted'
# conf.columns[:records].label = 'All Records' # conf.columns[:records].label = 'All Records'
end end
protected protected
def beginning_of_chain def beginning_of_chain
super.readonly(false) super.readonly(false)
end end
def do_new def do_new
super super
@record.setup(current_user.email) @record.setup(current_user.email)
end end
def do_create def do_create
super super
if !successful? && @record.domain_ownership_failed if !successful? && @record.domain_ownership_failed
@record.user = current_user @record.user = current_user
end end
end end
def do_destroy def do_destroy
@record ||= destroy_find_record @record ||= destroy_find_record
begin begin
@ -57,13 +57,13 @@ class Users::DomainsController < UsersController
self.successful = false self.successful = false
end end
end end
def new_model def new_model
record = super record = super
before_create_save(record) before_create_save(record)
record record
end end
# override to add locking # override to add locking
def update_save(options = {}) def update_save(options = {})
attributes = options[:attributes] || params[:record] attributes = options[:attributes] || params[:record]
@ -95,7 +95,7 @@ class Users::DomainsController < UsersController
ActiveRecord::Base.connection.execute("UNLOCK TABLES") if @name_changed ActiveRecord::Base.connection.execute("UNLOCK TABLES") if @name_changed
end end
end end
def before_create_save(record) def before_create_save(record)
record.type = 'NATIVE' record.type = 'NATIVE'
record.user = record.parent_domain.present? ? record.parent_domain.user : current_user record.user = record.parent_domain.present? ? record.parent_domain.user : current_user
@ -118,5 +118,5 @@ class Users::DomainsController < UsersController
end end
@record.reload @record.reload
end end
end end

10
app/controllers/users/hosts_controller.rb

@ -19,7 +19,7 @@ class Users::HostsController < UsersController
conf.action_links.add 'new_token', label: 'New Token', method: :put, conf.action_links.add 'new_token', label: 'New Token', method: :put,
type: :member, position: false, confirm: 'Are you sure?' type: :member, position: false, confirm: 'Are you sure?'
end end
def new_token def new_token
process_action_link_action do |record| process_action_link_action do |record|
record.instance_variable_set(:@readonly, false) record.instance_variable_set(:@readonly, false)
@ -30,22 +30,22 @@ class Users::HostsController < UsersController
end end
end end
end end
protected protected
def new_model def new_model
record = super record = super
record.content = client_remote_ip record.content = client_remote_ip
before_create_save(record) before_create_save(record)
record record
end end
def beginning_of_chain def beginning_of_chain
super.includes(:domain). super.includes(:domain).
where(:domains => {:name => Settings.host_domains}). where(:domains => {:name => Settings.host_domains}).
readonly(false) readonly(false)
end end
def before_create_save(record) def before_create_save(record)
record.user = current_user record.user = current_user
end end

10
app/controllers/users/mxes_controller.rb

@ -10,9 +10,9 @@ class Users::MxesController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def do_new def do_new
super super
@record.prio ||= begin @record.prio ||= begin
@ -20,11 +20,11 @@ class Users::MxesController < UsersController
maximum.nil? ? Settings.default_prio : maximum + 10 maximum.nil? ? Settings.default_prio : maximum + 10
end end
end end
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.mx_records : super).readonly(false) (nested_via_records? ? nested_parent_record.mx_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -32,4 +32,4 @@ class Users::MxesController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
end end

12
app/controllers/users/ns_controller.rb

@ -10,13 +10,13 @@ class Users::NsController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.ns_records : super).readonly(false) (nested_via_records? ? nested_parent_record.ns_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -25,7 +25,7 @@ class Users::NsController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
def after_update_save(record) def after_update_save(record)
domain = @record.domain domain = @record.domain
soa_record = domain.soa_record soa_record = domain.soa_record
@ -33,7 +33,7 @@ class Users::NsController < UsersController
flash.now[:warning] = "SOA record's primary NS is no longer among this domain's NS records" flash.now[:warning] = "SOA record's primary NS is no longer among this domain's NS records"
end end
end end
def do_destroy def do_destroy
if nested_parent_record.ns_records.count > 1 if nested_parent_record.ns_records.count > 1
@record ||= destroy_find_record @record ||= destroy_find_record
@ -50,4 +50,4 @@ class Users::NsController < UsersController
flash[:error] = "Cannot delete it, the domain must have at least one nameserver!" flash[:error] = "Cannot delete it, the domain must have at least one nameserver!"
end end
end end
end end

16
app/controllers/users/omniauth_callbacks_controller.rb

@ -15,34 +15,34 @@ class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
@user.remember_me! if session.delete(:user_remember_me) == "1" @user.remember_me! if session.delete(:user_remember_me) == "1"
sign_in_and_redirect @user, event: :authentication sign_in_and_redirect @user, event: :authentication
end end
def find_or_create_user(provider) def find_or_create_user(provider)
user = if resource then resource user = if resource then resource
elsif email then User.where(email: email).first elsif email then User.where(email: email).first
elsif uid then Authentication.where(uid: uid).first.try(:user) elsif uid then Authentication.where(uid: uid).first.try(:user)
else raise "Bad provider data: #{auth.inspect}" else raise "Bad provider data: #{auth.inspect}"
end end
if user.nil? if user.nil?
user = User.new(user_attrs.merge(password: Devise.friendly_token[0,20])) user = User.new(user_attrs.merge(password: Devise.friendly_token[0,20]))
user.skip_confirmation! user.skip_confirmation!
user.save!(validate: false) user.save!(validate: false)
end end
authentication = user.authentications.where(provider: provider).first authentication = user.authentications.where(provider: provider).first
if authentication.nil? if authentication.nil?
authentication_attrs = authorization_attrs.merge(provider: provider) authentication_attrs = authorization_attrs.merge(provider: provider)
authentication = user.authentications.build(authentication_attrs) authentication = user.authentications.build(authentication_attrs)
user.authentications << authentication user.authentications << authentication
end end
return user return user
end end
def auth; env["omniauth.auth"] end def auth; env["omniauth.auth"] end
def uid; @uid ||= auth['uid'] rescue nil end def uid; @uid ||= auth['uid'] rescue nil end
def email; @email ||= auth['info']['email'] rescue nil end def email; @email ||= auth['info']['email'] rescue nil end
def authorization_attrs def authorization_attrs
@authorization_attrs ||= { @authorization_attrs ||= {
uid: uid, uid: uid,
@ -51,11 +51,11 @@ class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
name: auth['info']['name'] name: auth['info']['name']
} }
end end
def user_attrs def user_attrs
@user_attrs ||= { email: email, full_name: auth['info']['name'] } @user_attrs ||= { email: email, full_name: auth['info']['name'] }
end end
def handle_unverified_request; true end def handle_unverified_request; true end
end end

8
app/controllers/users/permissions_controller.rb

@ -12,15 +12,15 @@ class Users::PermissionsController < UsersController
including it's records, it's subdomains and their records. including it's records, it's subdomains and their records.
DOC DOC
conf.create.link.label = 'Share Domain' conf.create.link.label = 'Share Domain'
# conf.columns[:user_email].search_sql = 'user.email' # conf.columns[:user_email].search_sql = 'user.email'
# conf.columns[:user].search_sql = 'full_name' # conf.columns[:user].search_sql = 'full_name'
end end
before_filter :ensure_nested_under_domain before_filter :ensure_nested_under_domain
protected protected
def beginning_of_chain def beginning_of_chain
super.readonly(false) super.readonly(false)
end end
end end

16
app/controllers/users/records_controller.rb

@ -15,9 +15,9 @@ class Users::RecordsController < UsersController
active_scaffold_config.action_links.collection.create.name = "Add Record" active_scaffold_config.action_links.collection.create.name = "Add Record"
end end
end end
respond_to :html, :xml, :json respond_to :html, :xml, :json
active_scaffold :record do |conf| active_scaffold :record do |conf|
conf.sti_children = [:SOA, :NS, :MX, :A, :CNAME, :TXT, :AAAA, :SRV] conf.sti_children = [:SOA, :NS, :MX, :A, :CNAME, :TXT, :AAAA, :SRV]
conf.columns = [:name, :type, :content, :ttl, :prio, :change_date, :authentication_token] conf.columns = [:name, :type, :content, :ttl, :prio, :change_date, :authentication_token]
@ -36,10 +36,10 @@ class Users::RecordsController < UsersController
c.skip_authorize_resource c.skip_authorize_resource
end end
protect_from_forgery :except => 'modify' protect_from_forgery :except => 'modify'
MODIFY_ERROR = 'ERROR: only A records can be modified with this API' MODIFY_ERROR = 'ERROR: only A records can be modified with this API'
MODIFY_OK = 'OK' MODIFY_OK = 'OK'
# TODO: externalize # TODO: externalize
def modify def modify
@record = Record.where(:authentication_token => params[:authentication_token]).first! @record = Record.where(:authentication_token => params[:authentication_token]).first!
@ -48,17 +48,17 @@ class Users::RecordsController < UsersController
@record.save! @record.save!
render(:text => MODIFY_OK) render(:text => MODIFY_OK)
end end
protected protected
def new_model def new_model
record = super record = super
before_create_save(record) before_create_save(record)
record record
end end
# just to limit the action to A type records # just to limit the action to A type records
def a_record?(record) def a_record?(record)
record.class == A record.class == A
end end
end end

2
app/controllers/users/registrations_controller.rb

@ -1,6 +1,6 @@
class Users::RegistrationsController < Devise::RegistrationsController class Users::RegistrationsController < Devise::RegistrationsController
protected protected
def after_inactive_sign_up_path_for(resource_or_scope) def after_inactive_sign_up_path_for(resource_or_scope)
page_path('notice') page_path('notice')
end end

10
app/controllers/users/soas_controller.rb

@ -8,21 +8,21 @@ class Users::SoasController < UsersController
conf.actions.exclude :delete, :show conf.actions.exclude :delete, :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.soa_records : super).readonly(false) (nested_via_records? ? nested_parent_record.soa_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
before_create_save(record) before_create_save(record)
record record
end end
def after_update_save(record) def after_update_save(record)
flash.now[:warning] = "SOA record's primary NS is no longer among this domain's NS records" unless record.ns? flash.now[:warning] = "SOA record's primary NS is no longer among this domain's NS records" unless record.ns?
end end
end end

12
app/controllers/users/srvs_controller.rb

@ -10,18 +10,18 @@ class Users::SrvsController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def do_new def do_new
super super
@record.prio ||= 0 @record.prio ||= 0
end end
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.srv_records : super).readonly(false) (nested_via_records? ? nested_parent_record.srv_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -29,5 +29,5 @@ class Users::SrvsController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
end end

8
app/controllers/users/txts_controller.rb

@ -10,13 +10,13 @@ class Users::TxtsController < UsersController
conf.actions.exclude :show conf.actions.exclude :show
end end
include RecordsControllerCommon include RecordsControllerCommon
protected protected
def beginning_of_chain def beginning_of_chain
(nested_via_records? ? nested_parent_record.txt_records : super).readonly(false) (nested_via_records? ? nested_parent_record.txt_records : super).readonly(false)
end end
# override, we make our own sti logic # override, we make our own sti logic
def new_model def new_model
record = beginning_of_chain.new record = beginning_of_chain.new
@ -24,4 +24,4 @@ class Users::TxtsController < UsersController
before_create_save(record) before_create_save(record)
record record
end end
end end

4
app/controllers/users_controller.rb

@ -10,11 +10,11 @@ class UsersController < ApplicationController
end end
protected protected
def set_user_current def set_user_current
User.current = current_user User.current = current_user
end end
def unset_user_current def unset_user_current
User.current = nil User.current = nil
end end

12
app/helpers/application_helper.rb

@ -7,7 +7,7 @@ module ApplicationHelper
alert: :warning, warning: :warning, warn: :warning, alert: :warning, warning: :warning, warn: :warning,
info: :info, notice: :info info: :info, notice: :info
) )
# for each record in the rails flash this # for each record in the rails flash this
# function wraps the message in an appropriate div # function wraps the message in an appropriate div
# and displays it # and displays it
@ -18,7 +18,7 @@ module ApplicationHelper
}.join }.join
flashes.present? ? content_tag(:div, flashes.html_safe, :class => clazz) : nil flashes.present? ? content_tag(:div, flashes.html_safe, :class => clazz) : nil
end end
def error_messages_for(resource) def error_messages_for(resource)
return "" if resource.errors.empty? return "" if resource.errors.empty?
@ -36,18 +36,18 @@ module ApplicationHelper
html.html_safe html.html_safe
end end
def honeypot def honeypot
content_tag('div', :style => 'position: absolute; left: -2000px;') do content_tag('div', :style => 'position: absolute; left: -2000px;') do
text_field_tag("#{Settings.honeypot}", nil, :tabindex => 900) text_field_tag("#{Settings.honeypot}", nil, :tabindex => 900)
end end
end end
# ActiveScaffold # ActiveScaffold
def active_scaffold_column_timestamp(record, column) def active_scaffold_column_timestamp(record, column)
value = record.send(column.name) value = record.send(column.name)
value.nil? ? nil : Time.at(value) value.nil? ? nil : Time.at(value)
end end
end end

2
app/helpers/users/authentications_helper.rb

@ -12,4 +12,4 @@ module Users::AuthenticationsHelper
record.provider.camelcase record.provider.camelcase
end end
end end
end end

4
app/helpers/users/domains_helper.rb

@ -2,7 +2,7 @@ module Users::DomainsHelper
def domain_list_row_class(record) def domain_list_row_class(record)
cannot?(:crud_permissions, record) ? "shared-domain" : '' cannot?(:crud_permissions, record) ? "shared-domain" : ''
end end
# Indents and dedents to create a tree structure, # Indents and dedents to create a tree structure,
# assuming that the records are sorted in preorder. # assuming that the records are sorted in preorder.
# Adds a visual cue if the record is shared via permissions feature. # Adds a visual cue if the record is shared via permissions feature.
@ -26,4 +26,4 @@ module Users::DomainsHelper
@previous_record = record @previous_record = record
elements.join.html_safe elements.join.html_safe
end end
end end

2
app/helpers/users/records_helper.rb

@ -2,4 +2,4 @@ module Users::RecordsHelper
def record_authentication_token_column(record, column) def record_authentication_token_column(record, column)
record.type == 'A' ? record.authentication_token : '-' record.type == 'A' ? record.authentication_token : '-'
end end
end end

4
app/mailers/contact_form.rb

@ -4,9 +4,9 @@ class ContactForm < MailForm::Base
attribute :message, :validate => true attribute :message, :validate => true
attribute :file, :attachment => true, :allow_blank => true attribute :file, :attachment => true, :allow_blank => true
attribute :nickname, :captcha => true # antispam attribute :nickname, :captcha => true # antispam
validates :email, email: true validates :email, email: true
# Declare the e-mail headers. It accepts anything the mail method # Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts. # in ActionMailer accepts.
def headers def headers

2
app/mailers/users/permission_mailer.rb

@ -1,7 +1,7 @@
class Users::PermissionMailer < ActionMailer::Base class Users::PermissionMailer < ActionMailer::Base
layout "emails" layout "emails"
default from: Settings.support_mail default from: Settings.support_mail
def created(permission) def created(permission)
@permission = permission @permission = permission
mail( mail(

8
app/models/a.rb

@ -12,7 +12,7 @@
# #
class A < Record class A < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :presence => true, :ip => {:ip_type => :v4} # Only accept valid IPv4 addresses validates :content, :presence => true, :ip => {:ip_type => :v4} # Only accept valid IPv4 addresses
@ -23,18 +23,18 @@ class A < Record
:length => {:minimum => 4}, :length => {:minimum => 4},
:uniqueness => {:scope => [:domain_id, :type]}, :uniqueness => {:scope => [:domain_id, :type]},
:if => :host? :if => :host?
validate do validate do
if host? && Settings.protected_hostnames.any? {|hn| name =~ /^#{hn}/i} if host? && Settings.protected_hostnames.any? {|hn| name =~ /^#{hn}/i}
errors[:name] << "cannot be used, please try another" errors[:name] << "cannot be used, please try another"
end end
end end
before_validation do before_validation do
if host_domain.present? && Settings.host_domains.include?(host_domain) if host_domain.present? && Settings.host_domains.include?(host_domain)
self.domain_id = Domain.find_by_name(host_domain).try(:id) self.domain_id = Domain.find_by_name(host_domain).try(:id)
end end
end end
def host?; domain.present? && Settings.host_domains.include?(domain.name) end def host?; domain.present? && Settings.host_domains.include?(domain.name) end
end end

4
app/models/aaaa.rb

@ -7,10 +7,10 @@
# @see http://www.zytrax.com/books/dns/ch8/aaaa.html # @see http://www.zytrax.com/books/dns/ch8/aaaa.html
class AAAA < Record class AAAA < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :presence => true, :ip => {:ip_type => :v6} validates :content, :presence => true, :ip => {:ip_type => :v6}
end end
Aaaa = AAAA Aaaa = AAAA

4
app/models/admin.rb

@ -7,7 +7,7 @@ class Admin < ActiveRecord::Base
# Setup accessible (or protected) attributes for your model # Setup accessible (or protected) attributes for your model
# attr_accessible :email, :password, :password_confirmation, :remember_me # attr_accessible :email, :password, :password_confirmation, :remember_me
# Called by Devise to see if an user can currently be signed in # Called by Devise to see if an user can currently be signed in
def active_for_authentication? def active_for_authentication?
active? && super active? && super
@ -17,5 +17,5 @@ class Admin < ActiveRecord::Base
def inactive_message def inactive_message
!active? ? :deactivated : super !active? ? :deactivated : super
end end
end end

2
app/models/admin_ability.rb

@ -7,4 +7,4 @@ class AdminAbility
cannot [:ban, :unban], :all cannot [:ban, :unban], :all
can [:ban, :unban], User can [:ban, :unban], User
end end
end end

2
app/models/authentication.rb

@ -1,5 +1,5 @@
class Authentication < ActiveRecord::Base class Authentication < ActiveRecord::Base
has_paper_trail has_paper_trail
belongs_to :user, :inverse_of => :authentications belongs_to :user, :inverse_of => :authentications
end end

4
app/models/blacklisted_domain.rb

@ -1,6 +1,6 @@
class BlacklistedDomain < ActiveRecord::Base class BlacklistedDomain < ActiveRecord::Base
# attr_accessible :name # attr_accessible :name
scope :of, ->(domain_name) { scope :of, ->(domain_name) {
domain_name_quoted = connection.quote(domain_name) domain_name_quoted = connection.quote(domain_name)
where{ where{
@ -8,7 +8,7 @@ class BlacklistedDomain < ActiveRecord::Base
(`#{domain_name_quoted}` =~ CONCAT('%.', name)) (`#{domain_name_quoted}` =~ CONCAT('%.', name))
} }
} }
def self.include?(domain_name) def self.include?(domain_name)
of(domain_name).exists? # || Dnsbl.include?(domain_name) of(domain_name).exists? # || Dnsbl.include?(domain_name)
end end

2
app/models/cname.rb

@ -9,7 +9,7 @@
# #
class CNAME < Record class CNAME < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :presence => true, :length => { :maximum => 20000 }, :hostname2 => true validates :content, :presence => true, :length => { :maximum => 20000 }, :hostname2 => true

8
app/models/concerns/stampable.rb

@ -1,14 +1,14 @@
module Stampable module Stampable
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
belongs_to :creator, :class_name => 'User' belongs_to :creator, :class_name => 'User'
belongs_to :updator, :class_name => 'User' belongs_to :updator, :class_name => 'User'
before_create :set_creator_attribute before_create :set_creator_attribute
before_save :set_updator_attribute before_save :set_updator_attribute
end end
def set_creator_attribute def set_creator_attribute
self.creator = User.current unless creator_id? self.creator = User.current unless creator_id?
end end
@ -16,4 +16,4 @@ module Stampable
def set_updator_attribute def set_updator_attribute
self.updator = User.current unless updator_id? && updator_id_changed? self.updator = User.current unless updator_id? && updator_id_changed?
end end
end end

32
app/models/domain.rb

@ -7,9 +7,9 @@ class Domain < ActiveRecord::Base
# optional IP for create form, results in a type A record # optional IP for create form, results in a type A record
attr_accessor :ip attr_accessor :ip
attr_accessor :domain_ownership_failed attr_accessor :domain_ownership_failed
# attr_accessible :name, :ip, :soa_record, :ns_records, :apply_subdomains # attr_accessible :name, :ip, :soa_record, :ns_records, :apply_subdomains
belongs_to :user, :inverse_of => :domain belongs_to :user, :inverse_of => :domain
has_many :records, :inverse_of => :domain, :dependent => :destroy has_many :records, :inverse_of => :domain, :dependent => :destroy
has_many :permissions, :inverse_of => :domain, :dependent => :destroy has_many :permissions, :inverse_of => :domain, :dependent => :destroy
@ -17,20 +17,20 @@ class Domain < ActiveRecord::Base
cattr_reader :types cattr_reader :types
@@types = ['NATIVE', 'MASTER', 'SLAVE', 'SUPERSLAVE'] @@types = ['NATIVE', 'MASTER', 'SLAVE', 'SUPERSLAVE']
has_one :soa_record, has_one :soa_record,
-> { where(type: 'SOA') }, -> { where(type: 'SOA') },
:class_name => 'SOA', :class_name => 'SOA',
:inverse_of => :domain :inverse_of => :domain
Record.types.each do |type| Record.types.each do |type|
has_many :"#{type.downcase}_records", has_many :"#{type.downcase}_records",
:class_name => type, :class_name => type,
:inverse_of => :domain :inverse_of => :domain
validates_associated :"#{type.downcase}_records" validates_associated :"#{type.downcase}_records"
end end
validates :name, :presence => true, :uniqueness => true, validates :name, :presence => true, :uniqueness => true,
:domainname => {:require_valid_tld => false}, :domainname => {:require_valid_tld => false},
:exclusion => {:in => BlacklistedDomain} :exclusion => {:in => BlacklistedDomain}
validates :master, :presence => true, :if => :slave? validates :master, :presence => true, :if => :slave?
@ -42,7 +42,7 @@ class Domain < ActiveRecord::Base
:minimum => 2, :maximum => 10, :message => "must have be at least 2, at most 10"} :minimum => 2, :maximum => 10, :message => "must have be at least 2, at most 10"}
validates_associated :records validates_associated :records
validates :user_id, :presence => true validates :user_id, :presence => true
validate :max_domains_per_user, :on => :create validate :max_domains_per_user, :on => :create
delegate :domains_exceeding?, :to => :user delegate :domains_exceeding?, :to => :user
def max_domains_per_user def max_domains_per_user
@ -59,25 +59,25 @@ class Domain < ActiveRecord::Base
end end
concerned_with :tree_structure, :name_change_subdomains, :name_change_records concerned_with :tree_structure, :name_change_subdomains, :name_change_records
scope :host_domains, -> { where(:name => Settings.host_domains) } scope :host_domains, -> { where(:name => Settings.host_domains) }
def host_domain? def host_domain?
Settings.host_domains.include?(name) Settings.host_domains.include?(name)
end end
# domains per user limit for DOS protection # domains per user limit for DOS protection
def records_exceeding? def records_exceeding?
records.count >= Settings.max_records_per_domain.to_i records.count >= Settings.max_records_per_domain.to_i
end end
# domain.has_ns?('129.168.0.1') # domain.has_ns?('129.168.0.1')
def has_ns?(ns) def has_ns?(ns)
ns_records.any? {|ns_record| ns_record.content == ns} ns_records.any? {|ns_record| ns_record.content == ns}
end end
def slave?; self.type == 'SLAVE' end def slave?; self.type == 'SLAVE' end
def setup(email) def setup(email)
build_soa_record build_soa_record
soa = soa_record soa = soa_record
@ -91,5 +91,5 @@ class Domain < ActiveRecord::Base
ns2.content = Settings.ns.second ns2.content = Settings.ns.second
ns3.content = Settings.ns.third ns3.content = Settings.ns.third
end end
end end

8
app/models/domain/name_change_records.rb

@ -1,5 +1,5 @@
class Domain < ActiveRecord::Base class Domain < ActiveRecord::Base
before_validation(:on => :update) do before_validation(:on => :update) do
if name_changed? if name_changed?
name_was_pattern = /#{Regexp.escape(name_was)}$/ name_was_pattern = /#{Regexp.escape(name_was)}$/
@ -24,11 +24,11 @@ class Domain < ActiveRecord::Base
end end
end end
end end
def each_update_involved_record def each_update_involved_record
yield soa_record yield soa_record
soa_records.each { |record| yield record } soa_records.each { |record| yield record }
records.each { |record| yield record } records.each { |record| yield record }
end end
end end

18
app/models/domain/name_change_subdomains.rb

@ -4,34 +4,34 @@ class Domain < ActiveRecord::Base
def apply_subdomains=(v) def apply_subdomains=(v)
@apply_subdomains = ActiveRecord::ConnectionAdapters::Column.value_to_boolean(v) @apply_subdomains = ActiveRecord::ConnectionAdapters::Column.value_to_boolean(v)
end end
before_update do before_update do
self.parent = parent_domain if name_changed? # recompute parent self.parent = parent_domain if name_changed? # recompute parent
end end
after_update do after_update do
(apply_subdomains ? chain_rename : sync_orphan_children) if name_changed? (apply_subdomains ? chain_rename : sync_orphan_children) if name_changed?
end end
protected protected
# previous subdomains in the system for the previous domain name # previous subdomains in the system for the previous domain name
# in case of domain name change # in case of domain name change
def previous_subdomains def previous_subdomains
Domain.where(:name_reversed.matches => "#{name_reversed_was}.%") Domain.where(:name_reversed.matches => "#{name_reversed_was}.%")
end end
# only immediate children # only immediate children
def previous_children_subdomains def previous_children_subdomains
descendants = previous_subdomains.preorder.all descendants = previous_subdomains.preorder.all
first = descendants.first first = descendants.first
return [] unless first.present? return [] unless first.present?
# only immediate children # only immediate children
depth = first.depth depth = first.depth
descendants.select { |d| d.depth == depth } descendants.select { |d| d.depth == depth }
end end
# Syncs with nested interval when the parent is added later than the children # Syncs with nested interval when the parent is added later than the children
def sync_orphan_children def sync_orphan_children
previous_children_subdomains.each do |subdomain| previous_children_subdomains.each do |subdomain|
@ -39,7 +39,7 @@ class Domain < ActiveRecord::Base
subdomain.save! subdomain.save!
end end
end end
# applies the tail rename to children # applies the tail rename to children
def chain_rename def chain_rename
name_was_pattern = /#{Regexp.escape(name_was)}$/ name_was_pattern = /#{Regexp.escape(name_was)}$/
@ -49,5 +49,5 @@ class Domain < ActiveRecord::Base
subdomain.save! # rest will chain recursively subdomain.save! # rest will chain recursively
end end
end end
end end

34
app/models/domain/tree_structure.rb

@ -1,19 +1,19 @@
class Domain < ActiveRecord::Base class Domain < ActiveRecord::Base
include ActsAsNestedInterval include ActsAsNestedInterval
attr_accessor :parent_synced attr_accessor :parent_synced
# this goes before acts_as_nested_interval call # this goes before acts_as_nested_interval call
before_save do before_save do
self.name_reversed = name.reverse if name_changed? self.name_reversed = name.reverse if name_changed?
sync_parent sync_parent
end end
after_save :sync_children after_save :sync_children
# this goes after sync_parent, to order callbacks correctly # this goes after sync_parent, to order callbacks correctly
acts_as_nested_interval virtual_root: true, dependent: :restrict_with_error acts_as_nested_interval virtual_root: true, dependent: :restrict_with_error
validate :domain_ownership validate :domain_ownership
def domain_ownership def domain_ownership
# non-TLD validation # non-TLD validation
@ -26,14 +26,14 @@ class Domain < ActiveRecord::Base
errors[:name] = "issue, the parent domain `#{parent_domain.name}` is registered to another user" errors[:name] = "issue, the parent domain `#{parent_domain.name}` is registered to another user"
end end
end end
# If current user present authorize it # If current user present authorize it
# If current user not present, just allow (rake tasks etc) # If current user not present, just allow (rake tasks etc)
def can_be_managed_by_current_user? def can_be_managed_by_current_user?
return true if User.current.nil? return true if User.current.nil?
UserAbility::CRUD.all?{|operation| User.current.can?(operation, self)} UserAbility::CRUD.all?{|operation| User.current.can?(operation, self)}
end end
# Returns the first immediate parent, if exists (and caches the search) # Returns the first immediate parent, if exists (and caches the search)
def parent_domain def parent_domain
return nil if name.nil? return nil if name.nil?
@ -45,23 +45,23 @@ class Domain < ActiveRecord::Base
def subdomains def subdomains
Domain.where(:name_reversed.matches => "#{name_reversed}.%") Domain.where(:name_reversed.matches => "#{name_reversed}.%")
end end
def subdomain_of?(domain) def subdomain_of?(domain)
name.end_with?('.' + domain.name) name.end_with?('.' + domain.name)
end end
# override # override
def self.rebuild_nested_interval_tree! def self.rebuild_nested_interval_tree!
skip_callback :update, :before, :sync_children skip_callback :update, :before, :sync_children
super super
set_callback :update, :before, :sync_children set_callback :update, :before, :sync_children
end end
# Syncs with nested interval when a child is added and parent exists # Syncs with nested interval when a child is added and parent exists
def sync_parent def sync_parent
self.parent = parent_domain if !@parent_synced && new_parent? self.parent = parent_domain if !@parent_synced && new_parent?
end end
# acts_as_nested_interval monkeypatch for lock # acts_as_nested_interval monkeypatch for lock
def update_nested_interval def update_nested_interval
changed = send(:"#{nested_interval_foreign_key}_changed?") changed = send(:"#{nested_interval_foreign_key}_changed?")
@ -75,9 +75,9 @@ class Domain < ActiveRecord::Base
end end
end end
def connection; self.class.connection end def connection; self.class.connection end
protected protected
def new_parent? def new_parent?
parent_domain.present? && self.parent_id != parent_domain.id parent_domain.present? && self.parent_id != parent_domain.id
end end
@ -93,13 +93,13 @@ class Domain < ActiveRecord::Base
end end
return nil return nil
end end
# only immediate children # only immediate children
def children_subdomains def children_subdomains
descendants = subdomains.preorder.to_a descendants = subdomains.preorder.to_a
first = descendants.first first = descendants.first
return [] unless first.present? return [] unless first.present?
# only immediate children # only immediate children
depth = first.depth depth = first.depth
descendants.select { |d| d.depth == depth } descendants.select { |d| d.depth == depth }
@ -113,5 +113,5 @@ class Domain < ActiveRecord::Base
subdomain.save! # rest will chain recursively subdomain.save! # rest will chain recursively
end end
end end
end end

10
app/models/mx.rb

@ -8,16 +8,16 @@
# #
class MX < Record class MX < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :presence => true, :hostname2 => {:allow_wildcard_hostname => true} validates :content, :presence => true, :hostname2 => {:allow_wildcard_hostname => true}
validates :prio, :presence => true, :numericality => { validates :prio, :presence => true, :numericality => {
:greater_than_or_equal_to => 0, :greater_than_or_equal_to => 0,
:less_than_or_equal_to => 65535, :less_than_or_equal_to => 65535,
:only_integer => true :only_integer => true
} }
def supports_priority?; true end def supports_priority?; true end
end end
Mx = MX Mx = MX

2
app/models/ns.rb

@ -21,7 +21,7 @@
# #
class NS < Record class NS < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => true validates :name, :hostname2 => true
validates :content, :presence => true, :hostname2 => true #, :inclusion => {:in => Settings.ns} validates :content, :presence => true, :hostname2 => true #, :inclusion => {:in => Settings.ns}

14
app/models/permission.rb

@ -1,10 +1,10 @@
class Permission < ActiveRecord::Base class Permission < ActiveRecord::Base
include Stampable include Stampable
has_paper_trail has_paper_trail
belongs_to :domain, :inverse_of => :permissions belongs_to :domain, :inverse_of => :permissions
belongs_to :user, :inverse_of => :permissions belongs_to :user, :inverse_of => :permissions
validates :domain_id, :presence => true validates :domain_id, :presence => true
validates :user_id, :presence => true, :uniqueness => { validates :user_id, :presence => true, :uniqueness => {
:scope => :domain_id, :scope => :domain_id,
@ -17,7 +17,7 @@ class Permission < ActiveRecord::Base
validate do validate do
errors[:user] = 'cannot be yourself' if user_id == domain.user_id errors[:user] = 'cannot be yourself' if user_id == domain.user_id
end end
after_create do after_create do
Users::PermissionMailer.created(self).deliver Users::PermissionMailer.created(self).deliver
end end
@ -27,19 +27,19 @@ class Permission < ActiveRecord::Base
after_destroy do after_destroy do
Users::PermissionMailer.destroyed(self).deliver Users::PermissionMailer.destroyed(self).deliver
end end
def user_email def user_email
@user_email || user.try(:email) @user_email || user.try(:email)
end end
def user_email=(email) def user_email=(email)
@user_email = email @user_email = email
self.user = User.find_by_email(email) self.user = User.find_by_email(email)
end end
def to_label def to_label
user.try(:email) || @user_email || '-' user.try(:email) || @user_email || '-'
end end
def as_marked=(v); end #shim def as_marked=(v); end #shim
end end

30
app/models/record.rb

@ -1,19 +1,19 @@
class Record < ActiveRecord::Base class Record < ActiveRecord::Base
include Stampable include Stampable
belongs_to :domain, :inverse_of => :records belongs_to :domain, :inverse_of => :records
belongs_to :user, :inverse_of => :records belongs_to :user, :inverse_of => :records
cattr_reader :types cattr_reader :types
@@types = %w(SOA NS A MX TXT CNAME AAAA SRV) @@types = %w(SOA NS A MX TXT CNAME AAAA SRV)
# attr_accessible :name, :content, :ttl, :prio # attr_accessible :name, :content, :ttl, :prio
validates :domain, :name, :presence => true validates :domain, :name, :presence => true
validates :type, :inclusion => {:in => @@types, :message => "Unknown record type"} validates :type, :inclusion => {:in => @@types, :message => "Unknown record type"}
validates :content, :uniqueness => {:scope => [:domain_id, :type, :name]} validates :content, :uniqueness => {:scope => [:domain_id, :type, :name]}
# RFC 2181, 8 # RFC 2181, 8
validates :ttl, :numericality => { validates :ttl, :numericality => {
# :greater_than_or_equal_to => 0, # :greater_than_or_equal_to => 0,
:greater_than_or_equal_to => Settings.min_ttl.to_i, :greater_than_or_equal_to => Settings.min_ttl.to_i,
:less_than => 2**31, :less_than => 2**31,
:only_integer => true :only_integer => true
@ -25,7 +25,7 @@ class Record < ActiveRecord::Base
errors.add :base, "as a security measure, you cannot have more than #{Settings.max_records_per_domain} records on one domain" errors.add :base, "as a security measure, you cannot have more than #{Settings.max_records_per_domain} records on one domain"
end end
end end
before_validation :generate_token, :on => :create before_validation :generate_token, :on => :create
before_validation :prepare_name! before_validation :prepare_name!
before_save :update_change_date before_save :update_change_date
@ -33,16 +33,16 @@ class Record < ActiveRecord::Base
after_initialize do after_initialize do
self.ttl ||= Settings.default_ttl self.ttl ||= Settings.default_ttl
end end
# By default records don't support priorities. # By default records don't support priorities.
# Those who do can overwrite this in their own classes. # Those who do can overwrite this in their own classes.
def supports_priority?; false end def supports_priority?; false end
def shortname; name.gsub(/\.?#{self.domain.name}$/, '') end def shortname; name.gsub(/\.?#{self.domain.name}$/, '') end
def shortname=(value); self.name = value end def shortname=(value); self.name = value end
def to_label; "#{type} #{content}" end def to_label; "#{type} #{content}" end
# Generate a token by looping and ensuring does not already exist. # Generate a token by looping and ensuring does not already exist.
# stolen from Devise # stolen from Devise
def generate_token def generate_token
@ -51,10 +51,10 @@ class Record < ActiveRecord::Base
break token unless Record.exists?(authentication_token: token) break token unless Record.exists?(authentication_token: token)
end end
end end
delegate :host_domain?, :records_exceeding?, :to => :domain delegate :host_domain?, :records_exceeding?, :to => :domain
delegate :user, :to => :domain, :prefix => :domain delegate :user, :to => :domain, :prefix => :domain
protected protected
def prepare_name! def prepare_name!
@ -62,19 +62,19 @@ class Record < ActiveRecord::Base
self.name = domain.name if name.blank? or name == '@' self.name = domain.name if name.blank? or name == '@'
self.name << ".#{domain.name}" unless name =~ /#{Regexp.escape(domain.name)}$/ self.name << ".#{domain.name}" unless name =~ /#{Regexp.escape(domain.name)}$/
end end
# Update the change date for automatic serial number generation # Update the change date for automatic serial number generation
def update_change_date; self.change_date = Time.now.to_i end def update_change_date; self.change_date = Time.now.to_i end
def update_soa_serial #:nodoc: def update_soa_serial #:nodoc:
unless type == 'SOA' || @serial_updated || domain.slave? unless type == 'SOA' || @serial_updated || domain.slave?
domain.soa_record.update_serial! domain.soa_record.update_serial!
@serial_updated = true @serial_updated = true
end end
end end
def name_equals_domain_name def name_equals_domain_name
errors.add :name, "must be equal to domain's name" unless name == domain.name errors.add :name, "must be equal to domain's name" unless name == domain.name
end end
end end

18
app/models/soa.rb

@ -8,7 +8,7 @@
# #
class SOA < Record class SOA < Record
has_paper_trail has_paper_trail
validates :domain, :presence => true validates :domain, :presence => true
validates :domain_id, :uniqueness => true # one SOA per domain validates :domain_id, :uniqueness => true # one SOA per domain
validates :name, :presence => true, :hostname2 => true validates :name, :presence => true, :hostname2 => true
@ -21,7 +21,7 @@ class SOA < Record
before_validation :assemble_content before_validation :assemble_content
before_update :update_serial before_update :update_serial
after_initialize :disassemble_content after_initialize :disassemble_content
before_validation do before_validation do
self.primary_ns ||= domain.ns_records.first.try(:content) self.primary_ns ||= domain.ns_records.first.try(:content)
end end
@ -54,7 +54,7 @@ class SOA < Record
return if content_changed? return if content_changed?
compute_serial compute_serial
end end
def reset_serial def reset_serial
@serial = nil @serial = nil
compute_serial compute_serial
@ -65,16 +65,16 @@ class SOA < Record
update_serial update_serial
save! save!
end end
# if SOA record's primary NS is among it's domain's NS records # if SOA record's primary NS is among it's domain's NS records
def ns? def ns?
domain.has_ns?(primary_ns) domain.has_ns?(primary_ns)
end end
def to_label; "#{primary_ns} #{contact}" end def to_label; "#{primary_ns} #{contact}" end
private private
def assemble_content def assemble_content
self.content = "#{@primary_ns} #{@contact} #{@serial}".strip self.content = "#{@primary_ns} #{@contact} #{@serial}".strip
end end
@ -85,12 +85,12 @@ class SOA < Record
@serial = @serial.to_i unless @serial.nil? @serial = @serial.to_i unless @serial.nil?
update_serial if @serial.nil? || @serial.zero? update_serial if @serial.nil? || @serial.zero?
end end
def compute_serial def compute_serial
date_serial = Time.now.strftime( "%Y%m%d00" ).to_i date_serial = Time.now.strftime( "%Y%m%d00" ).to_i
@serial = (@serial.nil? || date_serial > @serial) ? date_serial : @serial + 1 @serial = (@serial.nil? || date_serial > @serial) ? date_serial : @serial + 1
end end
end end
Soa = SOA Soa = SOA

14
app/models/srv.rb

@ -6,7 +6,7 @@
# @see http://www.zytrax.com/books/dns/ch8/srv.html # @see http://www.zytrax.com/books/dns/ch8/srv.html
class SRV < Record class SRV < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :format => /\A\d+ \d+ [A-Za-z0-9\-_.]+\z/ validates :content, :format => /\A\d+ \d+ [A-Za-z0-9\-_.]+\z/
# RFC 2872 # RFC 2872
@ -26,16 +26,16 @@ class SRV < Record
:only_integer => true :only_integer => true
} }
validates :host, :presence => true, :hostname2 => {:allow_wildcard_hostname => true} validates :host, :presence => true, :hostname2 => {:allow_wildcard_hostname => true}
attr_accessor :weight, :port, :host attr_accessor :weight, :port, :host
before_validation :assemble_content before_validation :assemble_content
after_initialize :disassemble_content after_initialize :disassemble_content
def supports_priority?; true end def supports_priority?; true end
protected protected
def assemble_content def assemble_content
self.content = "#{@weight} #{@port} #{@host}".strip self.content = "#{@weight} #{@port} #{@host}".strip
end end
@ -44,7 +44,7 @@ class SRV < Record
def disassemble_content def disassemble_content
@weight, @port, @host = content.split(/\s+/) unless content.blank? @weight, @port, @host = content.split(/\s+/) unless content.blank?
end end
end end
Srv = SRV Srv = SRV

8
app/models/tld.rb

@ -1,8 +1,8 @@
class Tld class Tld
@@lines = [] @@lines = []
cattr_accessor :lines cattr_accessor :lines
File.open(Rails.root.join('db', 'data', 'tlds.txt').to_s) do |fd| File.open(Rails.root.join('db', 'data', 'tlds.txt').to_s) do |fd|
fd.each do |line| fd.each do |line|
unless line[0..1] == '//' || line =~ /^\s$/ # neither comment neither blank unless line[0..1] == '//' || line =~ /^\s$/ # neither comment neither blank
@ -14,12 +14,12 @@ class Tld
end end
end end
end end
def self.include?(name) def self.include?(name)
for line in @@lines for line in @@lines
return true if name =~ line return true if name =~ line
end end
return false return false
end end
end end

12
app/models/txt.rb

@ -2,18 +2,18 @@
# = Text Record (TXT) # = Text Record (TXT)
# Provides the ability to associate some text with a host or other name. The TXT # Provides the ability to associate some text with a host or other name. The TXT
# record is used to define the Sender Policy Framework (SPF) information record # record is used to define the Sender Policy Framework (SPF) information record
# which may be used to validate legitimate email sources from a domain. The SPF # which may be used to validate legitimate email sources from a domain. The SPF
# record while being increasing deployed is not (July 2004) a formal IETF RFC # record while being increasing deployed is not (July 2004) a formal IETF RFC
# standard. # standard.
# #
# Obtained from http://www.zytrax.com/books/dns/ch8/txt.html # Obtained from http://www.zytrax.com/books/dns/ch8/txt.html
class TXT < Record class TXT < Record
has_paper_trail has_paper_trail
validates :name, :hostname2 => {:allow_wildcard_hostname => true} validates :name, :hostname2 => {:allow_wildcard_hostname => true}
validates :content, :presence => true, :length => { :maximum => 255 } validates :content, :presence => true, :length => { :maximum => 255 }
def to_label; type end def to_label; type end
end end

40
app/models/user.rb

@ -2,41 +2,41 @@ class User < ActiveRecord::Base
include SentientModel include SentientModel
include Stampable include Stampable
has_paper_trail has_paper_trail
# Include default devise modules. Others available are: # Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :timeoutable and :omniauthable # :token_authenticatable, :encryptable, :timeoutable and :omniauthable
devise :database_authenticatable, devise :database_authenticatable,
:registerable, :registerable,
:recoverable, :recoverable,
:rememberable, :rememberable,
:trackable, :trackable,
:validatable, :validatable,
:confirmable, :confirmable,
:lockable, :lockable,
:omniauthable, :omniauthable,
:omniauth_providers => [:google_oauth2] :omniauth_providers => [:google_oauth2]
validates :full_name, :presence => true validates :full_name, :presence => true
# Setup accessible (or protected) attributes for your model # Setup accessible (or protected) attributes for your model
# attr_accessible :email, :password, :password_confirmation, :remember_me, # attr_accessible :email, :password, :password_confirmation, :remember_me,
# :full_name # :full_name
has_many :authentications, :inverse_of => :user, :dependent => :destroy has_many :authentications, :inverse_of => :user, :dependent => :destroy
has_many :domains, :inverse_of => :user, :dependent => :destroy has_many :domains, :inverse_of => :user, :dependent => :destroy
has_many :records, :inverse_of => :user, :dependent => :destroy has_many :records, :inverse_of => :user, :dependent => :destroy
has_many :permissions, :inverse_of => :user, :dependent => :destroy has_many :permissions, :inverse_of => :user, :dependent => :destroy
has_many :permitted_domains, :through => :permissions, :source => :domain has_many :permitted_domains, :through => :permissions, :source => :domain
def name def name
full_name.blank? ? email : full_name full_name.blank? ? email : full_name
end end
# domains per user limit for DOS protection # domains per user limit for DOS protection
def domains_exceeding? def domains_exceeding?
domains.count >= Settings.max_domains_per_user.to_i domains.count >= Settings.max_domains_per_user.to_i
end end
# Called by Devise to see if an user can currently be signed in # Called by Devise to see if an user can currently be signed in
def active_for_authentication? def active_for_authentication?
active? && super active? && super
@ -46,7 +46,7 @@ class User < ActiveRecord::Base
def inactive_message def inactive_message
!active? ? :deactivated : super !active? ? :deactivated : super
end end
def ban! def ban!
self.class.transaction do self.class.transaction do
update_column :active, false update_column :active, false
@ -55,38 +55,38 @@ class User < ActiveRecord::Base
permissions.each &:destroy permissions.each &:destroy
end end
end end
def unban! def unban!
update_column :active, true update_column :active, true
end end
def to_paper_trail def to_paper_trail
"#{id} #{email} name:#{full_name} ip:#{current_sign_in_ip} last_ip:#{last_sign_in_ip}" "#{id} #{email} name:#{full_name} ip:#{current_sign_in_ip} last_ip:#{last_sign_in_ip}"
end end
# @override # @override
def update_tracked_fields!(*) def update_tracked_fields!(*)
self.paper_trail_event = "sign_in" self.paper_trail_event = "sign_in"
PaperTrail.whodunnit = to_paper_trail PaperTrail.whodunnit = to_paper_trail
super super
end end
delegate :can?, :cannot?, :to => :ability delegate :can?, :cannot?, :to => :ability
def ability(options = {:reload => false}) def ability(options = {:reload => false})
options[:reload] ? _ability : (@ability ||= _ability) options[:reload] ? _ability : (@ability ||= _ability)
end end
def self.do_as(user) def self.do_as(user)
self.current = user self.current = user
yield yield
self.current = nil self.current = nil
end end
protected protected
def _ability def _ability
UserAbility.new(self) UserAbility.new(self)
end end
end end

22
app/models/user_ability.rb

@ -1,6 +1,6 @@
class UserAbility class UserAbility
CRUD = [:read, :create, :update, :destroy] CRUD = [:read, :create, :update, :destroy]
include CanCan::Ability include CanCan::Ability
attr_accessor :user attr_accessor :user
attr_accessor :context attr_accessor :context
@ -9,7 +9,7 @@ class UserAbility
def initialize(user, options = {}) def initialize(user, options = {})
@user = user || User.new @user = user || User.new
@context = options[:context] || :application @context = options[:context] || :application
as_action_aliases as_action_aliases
action_aliases action_aliases
if @user.persisted? if @user.persisted?
@ -17,40 +17,40 @@ class UserAbility
sharing_abilities sharing_abilities
end end
end end
protected protected
def owner_abilities def owner_abilities
# can manage his domains and records # can manage his domains and records
can CRUD, Domain, :user_id => user.id can CRUD, Domain, :user_id => user.id
can CRUD, Record, :domain => {:user_id => user.id} can CRUD, Record, :domain => {:user_id => user.id}
cannot :delete, SOA # it's deleted with the parent domain cannot :delete, SOA # it's deleted with the parent domain
# can manage his hosts # can manage his hosts
can CRUD, A, :user_id => user.id #, :domain => {:name => Settings.host_domains} can CRUD, A, :user_id => user.id #, :domain => {:name => Settings.host_domains}
# can manage permissions for his domains # can manage permissions for his domains
can CRUD, Permission, :domain => {:user_id => user.id} can CRUD, Permission, :domain => {:user_id => user.id}
can :crud_permissions, Domain, :user_id => user.id can :crud_permissions, Domain, :user_id => user.id
# can manage his authentications # can manage his authentications
can CRUD, Authentication, :user_id => user.id can CRUD, Authentication, :user_id => user.id
end end
def sharing_abilities def sharing_abilities
# can manage shared domains and records # can manage shared domains and records
can CRUD, Domain, :permissions.outer => {:user_id => user.id} can CRUD, Domain, :permissions.outer => {:user_id => user.id}
can CRUD, Record, :domain => {:permissions.outer => {:user_id => user.id}} can CRUD, Record, :domain => {:permissions.outer => {:user_id => user.id}}
# can manage shared domains and records descendants # can manage shared domains and records descendants
for domain in user.permitted_domains for domain in user.permitted_domains
can CRUD, Domain, :name_reversed.matches => "#{domain.name_reversed}.%" # descendants can CRUD, Domain, :name_reversed.matches => "#{domain.name_reversed}.%" # descendants
can CRUD, Record, :domain => {:name_reversed.matches => "#{domain.name_reversed}.%"} # descendants can CRUD, Record, :domain => {:name_reversed.matches => "#{domain.name_reversed}.%"} # descendants
end end
end end
def action_aliases def action_aliases
alias_action :new_token, :to => :update alias_action :new_token, :to => :update
end end
end end

12
app/validators/hostname2_validator.rb

@ -1,6 +1,6 @@
# skips length validations, more permissive defaults # skips length validations, more permissive defaults
class Hostname2Validator < PAK::ValidatesHostname::HostnameValidator class Hostname2Validator < PAK::ValidatesHostname::HostnameValidator
def initialize(options) def initialize(options)
opts = { opts = {
:allow_underscore => true, :allow_underscore => true,
@ -14,7 +14,7 @@ class Hostname2Validator < PAK::ValidatesHostname::HostnameValidator
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
value ||= '' value ||= ''
# split each hostname into labels and do various checks # split each hostname into labels and do various checks
if value.is_a?(String) if value.is_a?(String)
labels = value.split '.' labels = value.split '.'
@ -26,14 +26,14 @@ class Hostname2Validator < PAK::ValidatesHostname::HostnameValidator
# Take care of wildcard first label # Take care of wildcard first label
next if options[:allow_wildcard_hostname] and label == '*' and index == 0 next if options[:allow_wildcard_hostname] and label == '*' and index == 0
# CHECK 3: hostname can only contain characters: # CHECK 3: hostname can only contain characters:
# a-z, 0-9, hyphen, optional underscore, optional asterisk # a-z, 0-9, hyphen, optional underscore, optional asterisk
valid_chars = 'a-z0-9\-' valid_chars = 'a-z0-9\-'
valid_chars << '_' if options[:allow_underscore] == true valid_chars << '_' if options[:allow_underscore] == true
add_error(record, attribute, :label_contains_invalid_characters, :valid_chars => valid_chars) unless label =~ /^[#{valid_chars}]+$/i add_error(record, attribute, :label_contains_invalid_characters, :valid_chars => valid_chars) unless label =~ /^[#{valid_chars}]+$/i
end end
# CHECK 4: the unqualified hostname portion cannot consist of # CHECK 4: the unqualified hostname portion cannot consist of
# numeric values only # numeric values only
if options[:allow_numeric_hostname] == false if options[:allow_numeric_hostname] == false
is_numeric_only = ( is_numeric_only = (
@ -54,5 +54,5 @@ class Hostname2Validator < PAK::ValidatesHostname::HostnameValidator
end end
end end
end end
end end

10
app/validators/ip_validator.rb

@ -7,7 +7,7 @@ class IpValidator < ActiveModel::EachValidator
(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3} (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
$/x $/x
IPV6_REGEX = /^ IPV6_REGEX = /^
( (
(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) (([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})
@ -23,7 +23,7 @@ class IpValidator < ActiveModel::EachValidator
|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) |(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})
|(([0-9A-Fa-f]{1,4}:){1,7}:) |(([0-9A-Fa-f]{1,4}:){1,7}:)
)$/x )$/x
# @param [Hash] options Options for validation # @param [Hash] options Options for validation
# @option options [Symbol] :ip_type (:any) The IP address type (:any, :v4 or :v6) # @option options [Symbol] :ip_type (:any) The IP address type (:any, :v4 or :v6)
# @see ActiveModel::EachValidator#new # @see ActiveModel::EachValidator#new
@ -31,7 +31,7 @@ class IpValidator < ActiveModel::EachValidator
options[:ip_type] ||= :any options[:ip_type] ||= :any
super super
end end
def validate_each(record, attribute, value) def validate_each(record, attribute, value)
case options[:ip_type] case options[:ip_type]
when :v4 when :v4
@ -49,14 +49,14 @@ private
def ipv4?(address) def ipv4?(address)
address =~ IPV4_REGEX address =~ IPV4_REGEX
end end
# Validates IPv6 address # Validates IPv6 address
# @param [String] address the ipv6 address # @param [String] address the ipv6 address
# @return [Boolean] the validation result # @return [Boolean] the validation result
def ipv6?(address) def ipv6?(address)
address =~ IPV6_REGEX address =~ IPV6_REGEX
end end
# Validates IP (v4 or v6) address # Validates IP (v4 or v6) address
# @param [String] address the ip address # @param [String] address the ip address
# @return [Boolean] the validation result # @return [Boolean] the validation result

10
app/validators/zone_validator.rb

@ -6,9 +6,9 @@ class ZoneValidator < ActiveModel::Validator
record.errors.add(:mname, options[:message] || :mname) if mname_is_zone_name?(record) record.errors.add(:mname, options[:message] || :mname) if mname_is_zone_name?(record)
record.errors.add(:base, options[:message] || :missing_ns_record) unless has_two_ns_rr?(record) record.errors.add(:base, options[:message] || :missing_ns_record) unless has_two_ns_rr?(record)
record.errors.add(:mname, options[:message] || :not_a_defined_nameserver) unless mname_is_a_defined_nameserver?(record) record.errors.add(:mname, options[:message] || :not_a_defined_nameserver) unless mname_is_a_defined_nameserver?(record)
record.errors.add(:base, options[:message] || :duplicate_nameservers_found) unless nameservers_are_unique?(record) record.errors.add(:base, options[:message] || :duplicate_nameservers_found) unless nameservers_are_unique?(record)
end end
private private
# Check if the zone name equals the primary nameserver # Check if the zone name equals the primary nameserver
# @param [Zone] record The Zone to check # @param [Zone] record The Zone to check
@ -16,14 +16,14 @@ private
def mname_is_zone_name?(zone) def mname_is_zone_name?(zone)
zone.name == zone.mname zone.name == zone.mname
end end
# Check if the zone has at least two associated NS resource records # Check if the zone has at least two associated NS resource records
# @param [Zone] zone The Zone to check # @param [Zone] zone The Zone to check
# @return [Boolean] True if the zone has at least two associated NS resource records # @return [Boolean] True if the zone has at least two associated NS resource records
def has_two_ns_rr?(zone) def has_two_ns_rr?(zone)
zone.ns_resource_records.length >= 2 zone.ns_resource_records.length >= 2
end end
# Check if the primary nameserver of the zone is defined as one of the # Check if the primary nameserver of the zone is defined as one of the
# associated NS resource records # associated NS resource records
# @param [Zone] zone The Zone to check # @param [Zone] zone The Zone to check
@ -43,4 +43,4 @@ private
nameserver_data_fields = zone.ns_resource_records.map(&:rdata) nameserver_data_fields = zone.ns_resource_records.map(&:rdata)
nameserver_data_fields.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys.empty? nameserver_data_fields.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys.empty?
end end
end end

8
config/application.rb

@ -41,9 +41,9 @@ module Entrydns
# Version of your assets, change this if you want to expire all your assets # Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0' config.assets.version = '1.0'
config.to_prepare do config.to_prepare do
layout = proc { |c| layout = proc { |c|
return false if request.xhr? return false if request.xhr?
return 'admin' if devise_controller? && resource_name == :admin return 'admin' if devise_controller? && resource_name == :admin
user_signed_in? ? 'users' : 'public' user_signed_in? ? 'users' : 'public'
@ -53,9 +53,9 @@ module Entrydns
Devise::ConfirmationsController.layout layout Devise::ConfirmationsController.layout layout
Devise::UnlocksController.layout layout Devise::UnlocksController.layout layout
Devise::PasswordsController.layout layout Devise::PasswordsController.layout layout
Devise::Mailer.layout "emails" Devise::Mailer.layout "emails"
end end
end end
end end

6
config/deploy.rb

@ -15,7 +15,7 @@ set :ssh_options, :forward_agent => true
set :deploy_via, :remote_cache set :deploy_via, :remote_cache
# set :branch, "master" # set :branch, "master"
# set :scm_verbose, true # set :scm_verbose, true
# set :git_enable_submodules, # set :git_enable_submodules,
# set :scm_passphrase, "passwd0" # the deploy user's password # set :scm_passphrase, "passwd0" # the deploy user's password
after 'deploy:update_code', 'deploy:symlink_database_yml' after 'deploy:update_code', 'deploy:symlink_database_yml'
@ -44,7 +44,7 @@ namespace :deploy do
task :restart, :roles => :app, :except => { :no_release => true } do task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{current_release}/tmp/restart.txt" run "touch #{current_release}/tmp/restart.txt"
end end
desc "Symlinks the database.yml" desc "Symlinks the database.yml"
task :symlink_database_yml, :roles => :app do task :symlink_database_yml, :roles => :app do
run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml" run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml"
@ -54,7 +54,7 @@ namespace :deploy do
task :symlink_settings_yml, :roles => :app do task :symlink_settings_yml, :roles => :app do
run "ln -nfs #{deploy_to}/shared/config/settings.yml #{release_path}/config/settings.yml" run "ln -nfs #{deploy_to}/shared/config/settings.yml #{release_path}/config/settings.yml"
end end
desc "Populates the Production Database" desc "Populates the Production Database"
task :seed do task :seed do
run "cd #{current_path}; #{rake} db:seed RAILS_ENV=production" run "cd #{current_path}; #{rake} db:seed RAILS_ENV=production"

2
config/deploy/production.rb

@ -3,4 +3,4 @@ set :domain, 'n0.entrydns.net'
role :web, domain # Your HTTP server, Apache/etc role :web, domain # Your HTTP server, Apache/etc
role :app, domain # This may be the same as your `Web` server role :app, domain # This may be the same as your `Web` server
role :db, domain, :primary => true # This is where Rails migrations will run role :db, domain, :primary => true # This is where Rails migrations will run
# role :db, "your slave db-server here" # role :db, "your slave db-server here"

2
config/deploy/staging.rb

@ -4,4 +4,4 @@ set :port, 2212
role :web, domain # Your HTTP server, Apache/etc role :web, domain # Your HTTP server, Apache/etc
role :app, domain # This may be the same as your `Web` server role :app, domain # This may be the same as your `Web` server
role :db, domain, :primary => true # This is where Rails migrations will run role :db, domain, :primary => true # This is where Rails migrations will run
# role :db, "your slave db-server here" # role :db, "your slave db-server here"

4
config/environments/development.rb

@ -28,9 +28,9 @@ Entrydns::Application.configure do
config.action_mailer.delivery_method = :letter_opener config.action_mailer.delivery_method = :letter_opener
# config.action_mailer.delivery_method = :smtp # config.action_mailer.delivery_method = :smtp
# config.action_mailer.smtp_settings = { address: "localhost", port: 1025 } # config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }
config.eager_load = false config.eager_load = false
config.after_initialize do config.after_initialize do
Bullet.enable = true Bullet.enable = true
Bullet.alert = true Bullet.alert = true

8
config/environments/production.rb

@ -49,7 +49,7 @@ Entrydns::Application.configure do
:expires_in => 1.day, :expires_in => 1.day,
:compress => true :compress => true
} }
# Enable serving of images, stylesheets, and JavaScripts from an asset server # Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com" # config.action_controller.asset_host = "http://assets.example.com"
@ -68,7 +68,7 @@ Entrydns::Application.configure do
# Send deprecation notices to registered listeners # Send deprecation notices to registered listeners
config.active_support.deprecation = :notify config.active_support.deprecation = :notify
ActionMailer::Base.add_delivery_method :ses, AWS::SES::Base, ActionMailer::Base.add_delivery_method :ses, AWS::SES::Base,
:access_key_id => Settings.ses_access_key_id, :access_key_id => Settings.ses_access_key_id,
:secret_access_key => Settings.ses_secret_access_key :secret_access_key => Settings.ses_secret_access_key
@ -80,10 +80,10 @@ Entrydns::Application.configure do
# :domain => 'entrydns.net' # :domain => 'entrydns.net'
# } # }
config.action_mailer.delivery_method = :ses config.action_mailer.delivery_method = :ses
# Compress JavaScripts and CSS # Compress JavaScripts and CSS
config.assets.js_compressor = :uglifier config.assets.js_compressor = :uglifier
# disable paper-trail in production # disable paper-trail in production
config.after_initialize do config.after_initialize do
PaperTrail.enabled = false PaperTrail.enabled = false

2
config/environments/test.rb

@ -36,7 +36,7 @@ Entrydns::Application.configure do
# Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
config.assets.allow_debugging = true config.assets.allow_debugging = true
config.action_mailer.default_url_options = {:host => 'entrydns.net'} config.action_mailer.default_url_options = {:host => 'entrydns.net'}
config.eager_load = false config.eager_load = false

20
config/initializers/cancan.rb

@ -9,20 +9,20 @@ module Squeel
class PredicateVisitor < Visitor class PredicateVisitor < Visitor
def visit_String(o, parent) def visit_String(o, parent)
Arel::Nodes::SqlLiteral.new(o) Arel::Nodes::SqlLiteral.new(o)
end end
end end
end end
end end
module CanCan module CanCan
module ModelAdapters module ModelAdapters
class ActiveRecordAdapter < AbstractAdapter class ActiveRecordAdapter < AbstractAdapter
def self.override_condition_matching?(subject, name, value) def self.override_condition_matching?(subject, name, value)
name.kind_of?(Squeel::Nodes::Predicate) if defined? Squeel name.kind_of?(Squeel::Nodes::Predicate) if defined? Squeel
end end
def self.matches_condition?(subject, name, value) def self.matches_condition?(subject, name, value)
subject_value = subject.send(name.expr) subject_value = subject.send(name.expr)
method_name = name.method_name.to_s method_name = name.method_name.to_s
@ -34,7 +34,7 @@ module CanCan
squeel_match? subject_value, name.method_name, value squeel_match? subject_value, name.method_name, value
end end
end end
def self.squeel_match?(subject_value, method, value) def self.squeel_match?(subject_value, method, value)
case method.to_sym case method.to_sym
when :eq then subject_value == value when :eq then subject_value == value
@ -67,9 +67,9 @@ module CanCan
end end
end end
end end
private private
# override to fix overwrites # override to fix overwrites
# do not write existing hashes using empty hashes # do not write existing hashes using empty hashes
def merge_joins(base, add) def merge_joins(base, add)
@ -84,7 +84,7 @@ module CanCan
end end
end end
class Rule # allow Squeel class Rule # allow Squeel
def matches_conditions_hash?(subject, conditions = @conditions) def matches_conditions_hash?(subject, conditions = @conditions)
return true if conditions.empty? return true if conditions.empty?
@ -114,7 +114,7 @@ module CanCan
end end
end end
end end
end end
end end

2
config/initializers/devise.rb

@ -184,7 +184,7 @@ Devise.setup do |config|
# The default HTTP method used to sign out a resource. Default is :delete. # The default HTTP method used to sign out a resource. Default is :delete.
# config.sign_out_via = :delete # config.sign_out_via = :delete
config.sign_out_via = :get config.sign_out_via = :get
# http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/ # http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/
config.allow_insecure_sign_in_after_confirmation = true config.allow_insecure_sign_in_after_confirmation = true
config.secret_key = '0db2fbf12dd3a0c5f1512b4ab4301bb5362772f664981abe167faa185203eaa491e037e9f0e66153184e498560b0509f234fa201f667f010014ae77f5fb4a7cf' config.secret_key = '0db2fbf12dd3a0c5f1512b4ab4301bb5362772f664981abe167faa185203eaa491e037e9f0e66153184e498560b0509f234fa201f667f010014ae77f5fb4a7cf'

8
config/initializers/navigasmic.rb

@ -6,7 +6,7 @@ end
module Navigasmic module Navigasmic
# lazy monkey patch, makes it work with twitter bootstrap # lazy monkey patch, makes it work with twitter bootstrap
class HtmlNavigationBuilder class HtmlNavigationBuilder
def item(label = '', options = {}, &proc) def item(label = '', options = {}, &proc)
buffer = block_given? ? template.capture(self, &proc) : '' buffer = block_given? ? template.capture(self, &proc) : ''
label = (label + buffer).html_safe label = (label + buffer).html_safe
@ -24,7 +24,7 @@ module Navigasmic
item.hidden? ? '' : template.content_tag(Navigasmic.item_tag, label, options.delete(:html)) item.hidden? ? '' : template.content_tag(Navigasmic.item_tag, label, options.delete(:html))
end end
def group(options = {}, &proc) def group(options = {}, &proc)
raise ArgumentError, "Missing block" unless block_given? raise ArgumentError, "Missing block" unless block_given?
@ -37,6 +37,6 @@ module Navigasmic
visible = options[:hidden_unless].nil? ? true : options[:hidden_unless].is_a?(Proc) ? template.instance_eval(&options[:hidden_unless]) : options[:hidden_unless] visible = options[:hidden_unless].nil? ? true : options[:hidden_unless].is_a?(Proc) ? template.instance_eval(&options[:hidden_unless]) : options[:hidden_unless]
visible ? group.html_safe : '' visible ? group.html_safe : ''
end end
end end
end end

2
config/initializers/paper_trail.rb

@ -1 +1 @@
PaperTrail::Version.send :include, Stampable PaperTrail::Version.send :include, Stampable

444
config/initializers/rails_admin.rb

@ -41,7 +41,7 @@ RailsAdmin.config do |config|
# config.excluded_models = [A, AAAA, Admin, CNAME, Domain, MX, NS, Permission, Record, SOA, SRV, TXT, User] # config.excluded_models = [A, AAAA, Admin, CNAME, Domain, MX, NS, Permission, Record, SOA, SRV, TXT, User]
# Add models here if you want to go 'whitelist mode': # Add models here if you want to go 'whitelist mode':
config.included_models = [A, AAAA, Admin, CNAME, Domain, MX, NS, Permission, config.included_models = [A, AAAA, Admin, CNAME, Domain, MX, NS, Permission,
Record, SOA, SRV, TXT, User, Authentication, BlacklistedDomain, PaperTrail::Version] Record, SOA, SRV, TXT, User, Authentication, BlacklistedDomain, PaperTrail::Version]
config.model Authentication do |conf| config.model Authentication do |conf|
@ -51,15 +51,15 @@ RailsAdmin.config do |config|
config.model Permission do |conf| config.model Permission do |conf|
parent User parent User
end end
config.model Record do |conf| config.model Record do |conf|
parent Domain parent Domain
end end
config.actions do config.actions do
# root actions # root actions
dashboard # mandatory dashboard # mandatory
# collection actions # collection actions
index # mandatory index # mandatory
new new
export export
@ -74,7 +74,7 @@ RailsAdmin.config do |config|
ban ban
unban unban
end end
# Application wide tried label methods for models' instances # Application wide tried label methods for models' instances
# config.label_methods << :description # Default is [:name, :title] # config.label_methods << :description # Default is [:name, :title]
@ -121,25 +121,25 @@ RailsAdmin.config do |config|
config.model Setting do config.model Setting do
configure :value, :text configure :value, :text
end end
# config.model A do # config.model A do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -150,22 +150,22 @@ RailsAdmin.config do |config|
# end # end
# config.model AAAA do # config.model AAAA do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -177,19 +177,19 @@ RailsAdmin.config do |config|
# config.model Admin do # config.model Admin do
# # Found associations: # # Found associations:
# # Found columns: # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :email, :string # configure :email, :string
# configure :password, :password # Hidden # configure :password, :password # Hidden
# configure :password_confirmation, :password # Hidden # configure :password_confirmation, :password # Hidden
# configure :reset_password_token, :string # Hidden # configure :reset_password_token, :string # Hidden
# configure :reset_password_sent_at, :datetime # configure :reset_password_sent_at, :datetime
# configure :remember_created_at, :datetime # configure :remember_created_at, :datetime
# configure :sign_in_count, :integer # configure :sign_in_count, :integer
# configure :current_sign_in_at, :datetime # configure :current_sign_in_at, :datetime
# configure :last_sign_in_at, :datetime # configure :last_sign_in_at, :datetime
# configure :current_sign_in_ip, :string # configure :current_sign_in_ip, :string
# configure :last_sign_in_ip, :string # configure :last_sign_in_ip, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # # Sections: # configure :updated_at, :datetime # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -200,22 +200,22 @@ RailsAdmin.config do |config|
# end # end
# config.model CNAME do # config.model CNAME do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -226,41 +226,41 @@ RailsAdmin.config do |config|
# end # end
# config.model Domain do # config.model Domain do
# # Found associations: # # Found associations:
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # configure :creator, :belongs_to_association
# configure :parent, :belongs_to_association # configure :parent, :belongs_to_association
# configure :records, :has_many_association # configure :records, :has_many_association
# configure :permissions, :has_many_association # configure :permissions, :has_many_association
# configure :permitted_users, :has_many_association # configure :permitted_users, :has_many_association
# configure :soa_record, :has_one_association # configure :soa_record, :has_one_association
# configure :soa_records, :has_many_association # configure :soa_records, :has_many_association
# configure :ns_records, :has_many_association # configure :ns_records, :has_many_association
# configure :a_records, :has_many_association # configure :a_records, :has_many_association
# configure :mx_records, :has_many_association # configure :mx_records, :has_many_association
# configure :txt_records, :has_many_association # configure :txt_records, :has_many_association
# configure :cname_records, :has_many_association # configure :cname_records, :has_many_association
# configure :aaaa_records, :has_many_association # configure :aaaa_records, :has_many_association
# configure :srv_records, :has_many_association # configure :srv_records, :has_many_association
# configure :children, :has_many_association # # Found columns: # configure :children, :has_many_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :master, :string # configure :master, :string
# configure :last_check, :integer # configure :last_check, :integer
# configure :type, :string # configure :type, :string
# configure :notified_serial, :integer # configure :notified_serial, :integer
# configure :account, :string # configure :account, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :name_reversed, :string # configure :name_reversed, :string
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # configure :updator_id, :integer
# configure :parent_id, :integer # Hidden # configure :parent_id, :integer # Hidden
# configure :lftp, :integer # configure :lftp, :integer
# configure :lftq, :integer # configure :lftq, :integer
# configure :rgtp, :integer # configure :rgtp, :integer
# configure :rgtq, :integer # configure :rgtq, :integer
# configure :lft, :float # configure :lft, :float
# configure :rgt, :float # # Sections: # configure :rgt, :float # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -271,22 +271,22 @@ RailsAdmin.config do |config|
# end # end
# config.model MX do # config.model MX do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -297,22 +297,22 @@ RailsAdmin.config do |config|
# end # end
# config.model NS do # config.model NS do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -323,15 +323,15 @@ RailsAdmin.config do |config|
# end # end
# config.model Permission do # config.model Permission do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -342,22 +342,22 @@ RailsAdmin.config do |config|
# end # end
# config.model Record do # config.model Record do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -368,22 +368,22 @@ RailsAdmin.config do |config|
# end # end
# config.model SOA do # config.model SOA do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -394,22 +394,22 @@ RailsAdmin.config do |config|
# end # end
# config.model SRV do # config.model SRV do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -420,22 +420,22 @@ RailsAdmin.config do |config|
# end # end
# config.model TXT do # config.model TXT do
# # Found associations: # # Found associations:
# configure :domain, :belongs_to_association # configure :domain, :belongs_to_association
# configure :user, :belongs_to_association # configure :user, :belongs_to_association
# configure :creator, :belongs_to_association # # Found columns: # configure :creator, :belongs_to_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :domain_id, :integer # Hidden # configure :domain_id, :integer # Hidden
# configure :name, :string # configure :name, :string
# configure :type, :string # configure :type, :string
# configure :content, :string # configure :content, :string
# configure :ttl, :integer # configure :ttl, :integer
# configure :prio, :integer # configure :prio, :integer
# configure :change_date, :integer # configure :change_date, :integer
# configure :authentication_token, :string # configure :authentication_token, :string
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :user_id, :integer # Hidden # configure :user_id, :integer # Hidden
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end
@ -446,34 +446,34 @@ RailsAdmin.config do |config|
# end # end
# config.model User do # config.model User do
# # Found associations: # # Found associations:
# configure :creator, :belongs_to_association # configure :creator, :belongs_to_association
# configure :domains, :has_many_association # configure :domains, :has_many_association
# configure :records, :has_many_association # configure :records, :has_many_association
# configure :permissions, :has_many_association # configure :permissions, :has_many_association
# configure :permitted_domains, :has_many_association # # Found columns: # configure :permitted_domains, :has_many_association # # Found columns:
# configure :id, :integer # configure :id, :integer
# configure :email, :string # configure :email, :string
# configure :password, :password # Hidden # configure :password, :password # Hidden
# configure :password_confirmation, :password # Hidden # configure :password_confirmation, :password # Hidden
# configure :reset_password_token, :string # Hidden # configure :reset_password_token, :string # Hidden
# configure :reset_password_sent_at, :datetime # configure :reset_password_sent_at, :datetime
# configure :remember_created_at, :datetime # configure :remember_created_at, :datetime
# configure :sign_in_count, :integer # configure :sign_in_count, :integer
# configure :current_sign_in_at, :datetime # configure :current_sign_in_at, :datetime
# configure :last_sign_in_at, :datetime # configure :last_sign_in_at, :datetime
# configure :current_sign_in_ip, :string # configure :current_sign_in_ip, :string
# configure :last_sign_in_ip, :string # configure :last_sign_in_ip, :string
# configure :confirmation_token, :string # configure :confirmation_token, :string
# configure :confirmed_at, :datetime # configure :confirmed_at, :datetime
# configure :confirmation_sent_at, :datetime # configure :confirmation_sent_at, :datetime
# configure :unconfirmed_email, :string # configure :unconfirmed_email, :string
# configure :failed_attempts, :integer # configure :failed_attempts, :integer
# configure :unlock_token, :string # configure :unlock_token, :string
# configure :locked_at, :datetime # configure :locked_at, :datetime
# configure :created_at, :datetime # configure :created_at, :datetime
# configure :updated_at, :datetime # configure :updated_at, :datetime
# configure :full_name, :string # configure :full_name, :string
# configure :creator_id, :integer # Hidden # configure :creator_id, :integer # Hidden
# configure :updator_id, :integer # # Sections: # configure :updator_id, :integer # # Sections:
# list do; end # list do; end
# export do; end # export do; end

2
config/initializers/rails_config.rb

@ -1,3 +1,3 @@
RailsConfig.setup do |config| RailsConfig.setup do |config|
config.const_name = "Settings" config.const_name = "Settings"
end end

2
config/initializers/session_store.rb

@ -1,7 +1,7 @@
# Be sure to restart your server when you modify this file. # Be sure to restart your server when you modify this file.
require 'action_dispatch/middleware/session/dalli_store' require 'action_dispatch/middleware/session/dalli_store'
Rails.application.config.session_store :dalli_store, Rails.application.config.session_store :dalli_store,
:memcache_server => ['127.0.0.1'], :memcache_server => ['127.0.0.1'],
:namespace => 'entrydns', :namespace => 'entrydns',
:key => '_entrydns_session', :key => '_entrydns_session',

14
config/initializers/simple_form.rb

@ -30,18 +30,18 @@ end
# Use this setup block to configure all options available in SimpleForm. # Use this setup block to configure all options available in SimpleForm.
SimpleForm.setup do |config| SimpleForm.setup do |config|
config.boolean_style = :nested config.boolean_style = :nested
config.wrappers :bootstrap3, tag: 'div', class: 'form-group', error_class: 'has-error', config.wrappers :bootstrap3, tag: 'div', class: 'form-group', error_class: 'has-error',
defaults: { input_html: { class: 'default_class' } } do |b| defaults: { input_html: { class: 'default_class' } } do |b|
b.use :html5 b.use :html5
b.use :min_max b.use :min_max
b.use :maxlength b.use :maxlength
b.use :placeholder b.use :placeholder
b.optional :pattern b.optional :pattern
b.optional :readonly b.optional :readonly
b.use :label_input b.use :label_input
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' } b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
b.use :error, wrap_with: { tag: 'span', class: 'help-inline' } b.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
@ -49,15 +49,15 @@ SimpleForm.setup do |config|
config.wrappers :inlabel, tag: 'div', class: 'form-group', error_class: 'has-error', config.wrappers :inlabel, tag: 'div', class: 'form-group', error_class: 'has-error',
defaults: { input_html: { class: 'default_class' } } do |b| defaults: { input_html: { class: 'default_class' } } do |b|
b.use :html5 b.use :html5
b.use :min_max b.use :min_max
b.use :maxlength b.use :maxlength
b.use :placeholder b.use :placeholder
b.optional :pattern b.optional :pattern
b.optional :readonly b.optional :readonly
b.use :labeled_input b.use :labeled_input
b.use :input b.use :input
b.use :hint, wrap_with: { tag: 'p', class: 'help-block' } b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }

14
config/routes.rb

@ -1,5 +1,5 @@
Entrydns::Application.routes.draw do Entrydns::Application.routes.draw do
mount RailsAdmin::Engine => '/rails_admin', as: 'rails_admin' mount RailsAdmin::Engine => '/rails_admin', as: 'rails_admin'
devise_for :admins devise_for :admins
@ -8,13 +8,13 @@ Entrydns::Application.routes.draw do
registrations: 'users/registrations', registrations: 'users/registrations',
omniauth_callbacks: 'users/omniauth_callbacks' omniauth_callbacks: 'users/omniauth_callbacks'
} }
scope module: 'users' do scope module: 'users' do
resources :authentications do resources :authentications do
as_routes as_routes
end end
resources :domains do resources :domains do
as_routes as_routes
end end
@ -26,7 +26,7 @@ Entrydns::Application.routes.draw do
end end
end end
match '/records/modify/:authentication_token', to: 'records#modify', match '/records/modify/:authentication_token', to: 'records#modify',
as: :modify_record, via: [:get, :post, :put] as: :modify_record, via: [:get, :post, :put]
resources :records do resources :records do
as_routes as_routes
@ -70,11 +70,11 @@ Entrydns::Application.routes.draw do
resources :permissions do resources :permissions do
as_routes as_routes
end end
end end
scope module: 'public' do scope module: 'public' do
resources :pages, only: :show, path: '' resources :pages, only: :show, path: ''
post 'contact', to: 'pages#contact' post 'contact', to: 'pages#contact'

8
spec/controllers/users/domains_controller_spec.rb

@ -31,26 +31,26 @@ describe Users::DomainsController do
it "is wired with the current user by #new_model" do it "is wired with the current user by #new_model" do
@controller.send(:new_model).user.should == user @controller.send(:new_model).user.should == user
end end
it "is wired with the current user by #before_create_save" do it "is wired with the current user by #before_create_save" do
domain = build(:domain) domain = build(:domain)
@controller.send(:before_create_save, domain) @controller.send(:before_create_save, domain)
domain.user.should == user domain.user.should == user
end end
end end
# a domain who's parent domain is in our system # a domain who's parent domain is in our system
context "subdomain" do context "subdomain" do
before do before do
sign_in user2 sign_in user2
end end
it "is wired with the user of the parent domain by #before_create_save" do it "is wired with the user of the parent domain by #before_create_save" do
subdomain = build(:domain, :user => user2, :name => "x.#{domain.name}") subdomain = build(:domain, :user => user2, :name => "x.#{domain.name}")
@controller.send(:before_create_save, subdomain) @controller.send(:before_create_save, subdomain)
subdomain.user.should == user subdomain.user.should == user
end end
end end
end end
end end

4
spec/controllers/users/hosts_controller_spec.rb

@ -2,7 +2,7 @@ require 'spec_helper'
describe Users::HostsController do describe Users::HostsController do
include_context "data" include_context "data"
before do before do
sign_in user sign_in user
@controller.stub(:nested_parent_record => host_domain) @controller.stub(:nested_parent_record => host_domain)
@ -11,7 +11,7 @@ describe Users::HostsController do
it "#new_model is wired" do it "#new_model is wired" do
@controller.send(:new_model).user.should == user @controller.send(:new_model).user.should == user
end end
it "#before_create_save wires" do it "#before_create_save wires" do
@controller.send(:before_create_save, host_a_record) @controller.send(:before_create_save, host_a_record)
host_a_record.user.should == user host_a_record.user.should == user

10
spec/controllers/users/records_controller_spec.rb

@ -2,14 +2,14 @@ require 'spec_helper'
describe Users::RecordsController do describe Users::RecordsController do
it_should_behave_like "wiring controller" it_should_behave_like "wiring controller"
describe "GET modify" do describe "GET modify" do
include_context "data" include_context "data"
before do before do
sign_in user sign_in user
end end
it "modifies @record when IP given" do it "modifies @record when IP given" do
ip = '127.0.0.2' ip = '127.0.0.2'
get :modify, :authentication_token => a_record.authentication_token, :ip => ip get :modify, :authentication_token => a_record.authentication_token, :ip => ip
@ -18,7 +18,7 @@ describe Users::RecordsController do
assigns(:record).should == a_record assigns(:record).should == a_record
assigns(:record).content.should == ip assigns(:record).content.should == ip
end end
it "modifies @record with remote IP" do it "modifies @record with remote IP" do
ip = '127.0.0.3' ip = '127.0.0.3'
@request.env['REMOTE_ADDR'] = ip @request.env['REMOTE_ADDR'] = ip
@ -36,7 +36,7 @@ describe Users::RecordsController do
response.should be_success response.should be_success
response.body.should == Users::RecordsController::MODIFY_ERROR response.body.should == Users::RecordsController::MODIFY_ERROR
end end
end end
end end

14
spec/factories.rb

@ -1,10 +1,10 @@
FactoryGirl.define do FactoryGirl.define do
sequence(:email){|n| "#{Faker::Internet.user_name}#{n}@example.com"} sequence(:email){|n| "#{Faker::Internet.user_name}#{n}@example.com"}
sequence(:password){|n| "password#{n}"} sequence(:password){|n| "password#{n}"}
sequence(:domain_name){|n| "#{n}#{Faker::Internet.domain_name}"} sequence(:domain_name){|n| "#{n}#{Faker::Internet.domain_name}"}
sequence(:domain_word){|n| "#{n}#{Faker::Internet.domain_word}"} sequence(:domain_word){|n| "#{n}#{Faker::Internet.domain_word}"}
factory :user do factory :user do
full_name {Faker::Name.first_name + ' ' + Faker::Name.last_name} full_name {Faker::Name.first_name + ' ' + Faker::Name.last_name}
email email
@ -14,7 +14,7 @@ FactoryGirl.define do
u.confirm! u.confirm!
end end
end end
factory :domain do factory :domain do
name {FactoryGirl.generate(:domain_name)} name {FactoryGirl.generate(:domain_name)}
type 'NATIVE' type 'NATIVE'
@ -35,18 +35,18 @@ FactoryGirl.define do
name {FactoryGirl.generate(:domain_name)} name {FactoryGirl.generate(:domain_name)}
content {Faker::Internet.ip_v4_address} content {Faker::Internet.ip_v4_address}
end end
factory :permission do factory :permission do
end end
factory :admin do factory :admin do
email email
password password
password_confirmation {password} password_confirmation {password}
end end
factory :blacklisted_domain do factory :blacklisted_domain do
name {FactoryGirl.generate(:domain_name)} name {FactoryGirl.generate(:domain_name)}
end end
end end

30
spec/features/devise_spec.rb

@ -3,7 +3,7 @@ require 'spec_helper'
feature "devise" do feature "devise" do
include_context "data" include_context "data"
let(:new_user) { build(:user) } let(:new_user) { build(:user) }
def sign_up_user def sign_up_user
visit new_user_registration_path visit new_user_registration_path
within('#new_user') do within('#new_user') do
@ -16,39 +16,39 @@ feature "devise" do
scenario "sign up" do scenario "sign up" do
sign_up_user sign_up_user
# was success # was success
current_path.should == page_path('notice') current_path.should == page_path('notice')
expect(page).to have_content I18n.t('devise.registrations.signed_up_but_unconfirmed') expect(page).to have_content I18n.t('devise.registrations.signed_up_but_unconfirmed')
# sent mail # sent mail
assert_equal [new_user.email], ActionMailer::Base.deliveries.last.to assert_equal [new_user.email], ActionMailer::Base.deliveries.last.to
# saved user # saved user
user = User.order(:id).last user = User.order(:id).last
assert_equal user.email, new_user.email assert_equal user.email, new_user.email
end end
scenario "sign in" do scenario "sign in" do
user user
visit new_user_session_path visit new_user_session_path
within('#new_user') do within('#new_user') do
fill_in 'Email', with: user.email fill_in 'Email', with: user.email
fill_in 'Password', with: user.password fill_in 'Password', with: user.password
click_link_or_button 'Sign in' click_link_or_button 'Sign in'
end end
# was success # was success
current_path.should == domains_path current_path.should == domains_path
find('.navbar-main').should have_content user.email find('.navbar-main').should have_content user.email
# sent mail # sent mail
assert_equal [user.email], ActionMailer::Base.deliveries.last.to assert_equal [user.email], ActionMailer::Base.deliveries.last.to
end end
let(:friendly_token) { 'abcdef' } let(:friendly_token) { 'abcdef' }
def forgot_password def forgot_password
Devise.stub(:friendly_token).and_return(friendly_token) Devise.stub(:friendly_token).and_return(friendly_token)
visit new_user_password_path visit new_user_password_path
@ -57,20 +57,20 @@ feature "devise" do
click_link_or_button 'Send reset password instructions' click_link_or_button 'Send reset password instructions'
end end
end end
scenario "forgot password" do scenario "forgot password" do
user user
forgot_password forgot_password
# was success # was success
current_path.should == new_user_session_path current_path.should == new_user_session_path
expect(page).to have_content I18n.t('devise.passwords.send_instructions') expect(page).to have_content I18n.t('devise.passwords.send_instructions')
end end
scenario "reset password" do scenario "reset password" do
user user
forgot_password forgot_password
visit edit_user_password_path(:reset_password_token => friendly_token) visit edit_user_password_path(:reset_password_token => friendly_token)
within('#new_user') do within('#new_user') do

2
spec/features/simple_api_spec.rb

@ -7,4 +7,4 @@ feature "devise" do
visit modify_record_path(:authentication_token => a_record.authentication_token) visit modify_record_path(:authentication_token => a_record.authentication_token)
expect(page).to have_content Users::RecordsController::MODIFY_OK expect(page).to have_content Users::RecordsController::MODIFY_OK
end end
end end

4
spec/lib/dnsbl_spec.rb

@ -8,10 +8,10 @@ describe Dnsbl do
it "queries correctly" do it "queries correctly" do
Dnsbl.query('does-not-exist-domain-1234567890.net') == nil Dnsbl.query('does-not-exist-domain-1234567890.net') == nil
end end
it "distinguishes bad domains from good ones" do it "distinguishes bad domains from good ones" do
Dnsbl.include?('place4porn.net').should == true Dnsbl.include?('place4porn.net').should == true
Dnsbl.include?('entrydns.net').should == false Dnsbl.include?('entrydns.net').should == false
end end
end end

2
spec/mailers/users/permission_mailer_spec.rb

@ -2,7 +2,7 @@ require "spec_helper"
describe Users::PermissionMailer do describe Users::PermissionMailer do
include_context "data" include_context "data"
it "has sends to the right email" do it "has sends to the right email" do
created_mail = Users::PermissionMailer.created(permission) created_mail = Users::PermissionMailer.created(permission)
created_mail.to.should == [permission.user.email] created_mail.to.should == [permission.user.email]

2
spec/models/admin_spec.rb

@ -2,7 +2,7 @@ require 'spec_helper'
describe Admin do describe Admin do
include_context "data" include_context "data"
it "is inactive by default" do it "is inactive by default" do
admin_admin.should_not be_active admin_admin.should_not be_active
end end

42
spec/models/domain_spec.rb

@ -2,7 +2,7 @@ require 'spec_helper'
describe Domain do describe Domain do
include_context "data" include_context "data"
it "has correct soa record" do it "has correct soa record" do
domain.soa_record.should be_present domain.soa_record.should be_present
end end
@ -21,7 +21,7 @@ describe Domain do
it "has a soa serial updated" do it "has a soa serial updated" do
(domain.soa_record.serial % 100).should_not == 0 (domain.soa_record.serial % 100).should_not == 0
end end
it "updates name to records when name changed" do it "updates name to records when name changed" do
domain.update_attributes(:name => "changed#{domain.name}") domain.update_attributes(:name => "changed#{domain.name}")
domain.soa_record.name.should == domain.name domain.soa_record.name.should == domain.name
@ -31,7 +31,7 @@ describe Domain do
end end
(domain.soa_record.serial % 10).should == 0 (domain.soa_record.serial % 10).should == 0
end end
it "protects DOS on more Settings.max_domains_per_user+ domains" do it "protects DOS on more Settings.max_domains_per_user+ domains" do
max = Settings.max_domains_per_user.to_i max = Settings.max_domains_per_user.to_i
domain.user.stub_chain('domains.count').and_return(max) domain.user.stub_chain('domains.count').and_return(max)
@ -52,12 +52,12 @@ describe Domain do
host_domain.max_domains_per_user host_domain.max_domains_per_user
host_domain.should be_valid host_domain.should be_valid
end end
it "has parent_domain" do it "has parent_domain" do
subdomain = build(:domain, :user => user2, :name => "x.#{domain.name}") subdomain = build(:domain, :user => user2, :name => "x.#{domain.name}")
subdomain.parent_domain.should == domain subdomain.parent_domain.should == domain
end end
it "validates ownership" do it "validates ownership" do
domain.name = 'co.uk' domain.name = 'co.uk'
domain.should have(1).errors_on(:name) domain.should have(1).errors_on(:name)
@ -68,8 +68,8 @@ describe Domain do
User.do_as(user) do User.do_as(user) do
# stub a parent domain on another user account, with no permissions present # stub a parent domain on another user account, with no permissions present
mock_domain = double( mock_domain = double(
:user_id => user3.id, :user_id => user3.id,
:user => user3, :user => user3,
:name => 'x', :name => 'x',
:can_be_managed_by_current_user? => false :can_be_managed_by_current_user? => false
) )
@ -77,7 +77,7 @@ describe Domain do
domain.should have(1).errors_on(:name) domain.should have(1).errors_on(:name)
end end
end end
it "validates blacklist" do it "validates blacklist" do
blacklisted_domain blacklisted_domain
@ -95,21 +95,21 @@ describe Domain do
permission3 permission3
query = Domain.accessible_by(user.ability(:reload => true)) query = Domain.accessible_by(user.ability(:reload => true))
expected = <<-SQL expected = <<-SQL
SELECT `domains`.* FROM `domains` SELECT `domains`.* FROM `domains`
LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id` LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id`
WHERE ((((1=0 OR WHERE ((((1=0 OR
`domains`.`user_id` = #{user.id}) OR `domains`.`user_id` = #{user.id}) OR
`permissions`.`user_id` = #{user.id}) OR `permissions`.`user_id` = #{user.id}) OR
`domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%')) `domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%'))
SQL SQL
query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip
end end
it "has reversed name" do it "has reversed name" do
domain.name_reversed.should be_present domain.name_reversed.should be_present
domain.name_reversed.should == domain.name.reverse domain.name_reversed.should == domain.name.reverse
end end
it "nests root's interval corectly" do it "nests root's interval corectly" do
User.current = nil User.current = nil
hosts_domain = make_domain(:name => "hosts.com", :user => admin) hosts_domain = make_domain(:name => "hosts.com", :user => admin)
@ -125,14 +125,14 @@ describe Domain do
[other.id, 0.2, 0.25] [other.id, 0.2, 0.25]
] ]
end end
it "chains rename to children" do it "chains rename to children" do
domain domain
subdomain subdomain
subsubdomain subsubdomain
domain.apply_subdomains = true domain.apply_subdomains = true
domain.update_attributes(:name => "changed#{domain.name}") domain.update_attributes(:name => "changed#{domain.name}")
subdomain.reload.name.should =~ /#{domain.name}$/ subdomain.reload.name.should =~ /#{domain.name}$/
subsubdomain.reload.name.should =~ /#{domain.name}$/ subsubdomain.reload.name.should =~ /#{domain.name}$/
end end
@ -145,23 +145,23 @@ describe Domain do
domain.update_attributes(:name => "changed#{domain.name}") domain.update_attributes(:name => "changed#{domain.name}")
s = subdomain.reload s = subdomain.reload
ss = subsubdomain.reload ss = subsubdomain.reload
s.name.should_not =~ /#{domain.name}$/ s.name.should_not =~ /#{domain.name}$/
s.parent.should be_nil s.parent.should be_nil
ss.name.should_not =~ /#{domain.name}$/ ss.name.should_not =~ /#{domain.name}$/
ss.parent.should_not be_nil ss.parent.should_not be_nil
end end
it "recomputes parent" do it "recomputes parent" do
domain domain
subdomain subdomain
subsubdomain subsubdomain
subdomain.update_attributes(:name => "sub.changed#{domain.name}") subdomain.update_attributes(:name => "sub.changed#{domain.name}")
subdomain.reload.parent.should be_nil subdomain.reload.parent.should be_nil
subsubdomain.reload.depth.should == 2 subsubdomain.reload.depth.should == 2
end end
it "audits creations" do it "audits creations" do
PaperTrail.enabled = true PaperTrail.enabled = true
User.current = user User.current = user
@ -171,5 +171,5 @@ describe Domain do
User.current = nil User.current = nil
PaperTrail.enabled = false PaperTrail.enabled = false
end end
end end

4
spec/models/permission_spec.rb

@ -2,12 +2,12 @@ require 'spec_helper'
describe Permission do describe Permission do
include_context "data" include_context "data"
it "validates selfness" do it "validates selfness" do
permission.user_id = permission.domain.user_id permission.user_id = permission.domain.user_id
permission.should have(1).error_on(:user) permission.should have(1).error_on(:user)
end end
it "validates unexsisting email" do it "validates unexsisting email" do
permission.user_email = "does.not@exist.in.db" permission.user_email = "does.not@exist.in.db"
permission.should have(1).error_on(:user) permission.should have(1).error_on(:user)

38
spec/models/record_spec.rb

@ -2,7 +2,7 @@ require 'spec_helper'
describe Record do describe Record do
include_context "data" include_context "data"
it "protects DOS on more Settings.max_records_per_domain+ domains" do it "protects DOS on more Settings.max_records_per_domain+ domains" do
max = Settings.max_records_per_domain.to_i max = Settings.max_records_per_domain.to_i
a_record.domain.stub_chain(:records, :count).and_return(max) a_record.domain.stub_chain(:records, :count).and_return(max)
@ -16,44 +16,44 @@ describe Record do
a_record.max_records_per_domain a_record.max_records_per_domain
a_record.should be_valid a_record.should be_valid
end end
it "queries records corectly in index" do it "queries records corectly in index" do
permission3 permission3
query = Record.accessible_by(user.ability) query = Record.accessible_by(user.ability)
expected = <<-SQL expected = <<-SQL
SELECT `records`.* FROM `records` SELECT `records`.* FROM `records`
INNER JOIN `domains` ON `domains`.`id` = `records`.`domain_id` INNER JOIN `domains` ON `domains`.`id` = `records`.`domain_id`
LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id` LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id`
WHERE ((((1=0 OR WHERE ((((1=0 OR
`domains`.`user_id` = #{user.id}) OR `domains`.`user_id` = #{user.id}) OR
`permissions`.`user_id` = #{user.id}) OR `permissions`.`user_id` = #{user.id}) OR
`domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%')) `domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%'))
SQL SQL
query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip
end end
it "queries A records corectly in index" do it "queries A records corectly in index" do
permission3 permission3
query = A.accessible_by(user.ability(:reload => true)) query = A.accessible_by(user.ability(:reload => true))
expected = <<-SQL expected = <<-SQL
SELECT `records`.* FROM `records` SELECT `records`.* FROM `records`
INNER JOIN `domains` ON `domains`.`id` = `records`.`domain_id` INNER JOIN `domains` ON `domains`.`id` = `records`.`domain_id`
LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id` LEFT OUTER JOIN `permissions` ON `permissions`.`domain_id` = `domains`.`id`
WHERE `records`.`type` IN ('A') AND (((((1=0 OR WHERE `records`.`type` IN ('A') AND (((((1=0 OR
`domains`.`user_id` = #{user.id}) OR `domains`.`user_id` = #{user.id}) OR
`records`.`user_id` = #{user.id}) OR `records`.`user_id` = #{user.id}) OR
`permissions`.`user_id` = #{user.id}) OR `permissions`.`user_id` = #{user.id}) OR
`domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%')) `domains`.`name_reversed` LIKE '#{permission3.domain.name_reversed}.%'))
SQL SQL
query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip query.to_sql.should == expected.gsub("\n", '').gsub(/\s+/, ' ').strip
end end
it "validates host a records dubles" do it "validates host a records dubles" do
host_a_record host_a_record
host_a_record2 = build(:a, name: host_a_record.name, content: '127.0.0.2', domain: host_domain, user: user2) host_a_record2 = build(:a, name: host_a_record.name, content: '127.0.0.2', domain: host_domain, user: user2)
host_a_record2.should have(1).errors_on(:name) host_a_record2.should have(1).errors_on(:name)
end end
it "audits creations" do it "audits creations" do
PaperTrail.enabled = true PaperTrail.enabled = true
expect { a_record }.to change(PaperTrail::Version, :count) expect { a_record }.to change(PaperTrail::Version, :count)
@ -61,5 +61,5 @@ describe Record do
# expect { a_record.update!(content: "127.0.0.2") }.to_not change(PaperTrail::Version, :count) # expect { a_record.update!(content: "127.0.0.2") }.to_not change(PaperTrail::Version, :count)
PaperTrail.enabled = false PaperTrail.enabled = false
end end
end end

2
spec/models/tld_spec.rb

@ -14,7 +14,7 @@ describe Tld do
Tld.include?('ANYTHING.ar').should be_truthy Tld.include?('ANYTHING.ar').should be_truthy
Tld.include?('pref.fukuoka.jp').should be_truthy Tld.include?('pref.fukuoka.jp').should be_truthy
Tld.include?('any.toyama.jp').should be_truthy Tld.include?('any.toyama.jp').should be_truthy
Tld.include?('clyfe.ro').should be_falsey Tld.include?('clyfe.ro').should be_falsey
Tld.include?('clyfe.zooz.lt').should be_falsey Tld.include?('clyfe.zooz.lt').should be_falsey
end end

12
spec/models/user_ability_spec.rb

@ -14,19 +14,19 @@ describe UserAbility do
user.should_not be_able_to(:delete, soa_record) # SOA deleted only via parent user.should_not be_able_to(:delete, soa_record) # SOA deleted only via parent
user.should be_able_to(crud, host_a_record) user.should be_able_to(crud, host_a_record)
end end
it "denies other user to manage my domains and their records, and my hosts" do it "denies other user to manage my domains and their records, and my hosts" do
user2.should_not be_able_to(crud, domain) user2.should_not be_able_to(crud, domain)
user2.should_not be_able_to(crud, a_record) user2.should_not be_able_to(crud, a_record)
user2.should_not be_able_to(crud, soa_record) user2.should_not be_able_to(crud, soa_record)
user2.should_not be_able_to(crud, host_a_record) user2.should_not be_able_to(crud, host_a_record)
end end
it "allows admin to manage other user's hosts" do it "allows admin to manage other user's hosts" do
admin.should be_able_to(crud, host_a_record) admin.should be_able_to(crud, host_a_record)
end end
end end
context "permitted" do context "permitted" do
before do before do
User.do_as(user) do User.do_as(user) do
@ -36,7 +36,7 @@ describe UserAbility do
permission # ensure permission to domain permission # ensure permission to domain
end end
end end
it "allows other user to manage user's domains and records, if permitted" do it "allows other user to manage user's domains and records, if permitted" do
User.do_as(user2) do User.do_as(user2) do
user2.should be_able_to(crud, domain) user2.should be_able_to(crud, domain)
@ -44,7 +44,7 @@ describe UserAbility do
user2.should be_able_to(crud, soa_record) user2.should be_able_to(crud, soa_record)
end end
end end
it "denies third user to manage user's permitted domains and records" do it "denies third user to manage user's permitted domains and records" do
User.do_as(user3) do User.do_as(user3) do
user3.should_not be_able_to(crud, domain) user3.should_not be_able_to(crud, domain)
@ -67,7 +67,7 @@ describe UserAbility do
end end
end end
end end
context "permission" do context "permission" do
it "allows me to manage my domain's permissions" do it "allows me to manage my domain's permissions" do
user.should be_able_to(crud, permission) user.should be_able_to(crud, permission)

4
spec/models/user_spec.rb

@ -2,11 +2,11 @@ require 'spec_helper'
describe User do describe User do
include_context "data" include_context "data"
it "is valid" do it "is valid" do
user.should be_valid user.should be_valid
end end
it "audits creations" do it "audits creations" do
PaperTrail.enabled = true PaperTrail.enabled = true
expect { user }.to change(PaperTrail::Version, :count) expect { user }.to change(PaperTrail::Version, :count)

4
spec/support/application.rb

@ -1,9 +1,9 @@
module Entrydns module Entrydns
module TestHelpers module TestHelpers
# def make_user # def make_user
# end # end
end end
end end

2
spec/support/database_rewinder.rb

@ -6,4 +6,4 @@ RSpec.configure do |config|
config.after do config.after do
DatabaseRewinder.clean DatabaseRewinder.clean
end end
end end

1
spec/support/factory_girl.rb

@ -1,4 +1,3 @@
RSpec.configure do |config| RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods config.include FactoryGirl::Syntax::Methods
end end

8
spec/support/rspec.rb

@ -1,16 +1,16 @@
RSpec.configure do |config| RSpec.configure do |config|
config.mock_with :rspec config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures" config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = false config.infer_base_class_for_anonymous_controllers = false
config.filter_run :focus => true config.filter_run :focus => true
config.run_all_when_everything_filtered = true config.run_all_when_everything_filtered = true
config.order = "random" config.order = "random"
config.infer_spec_type_from_file_location! config.infer_spec_type_from_file_location!
config.expect_with :rspec do |c| config.expect_with :rspec do |c|
c.syntax = [:should, :expect] c.syntax = [:should, :expect]
end end

14
spec/support/shared_context/data.rb

@ -3,7 +3,7 @@ shared_context "data" do
let(:user){create(:user)} # a regular user let(:user){create(:user)} # a regular user
let(:user2){create(:user)} let(:user2){create(:user)}
let(:user3){create(:user)} let(:user3){create(:user)}
def make_domain(options) def make_domain(options)
domain = build(:domain, options) domain = build(:domain, options)
domain.setup(FactoryGirl.generate(:email)) domain.setup(FactoryGirl.generate(:email))
@ -11,7 +11,7 @@ shared_context "data" do
domain.soa_record.update_serial! domain.soa_record.update_serial!
domain domain
end end
# user's domains # user's domains
let(:domain){make_domain(:user => user)} let(:domain){make_domain(:user => user)}
let(:subdomain){make_domain(:name => "sub.#{domain.name}", :user => user)} let(:subdomain){make_domain(:name => "sub.#{domain.name}", :user => user)}
@ -21,20 +21,20 @@ shared_context "data" do
let(:domain3){make_domain(:user => user3)} let(:domain3){make_domain(:user => user3)}
let(:subdomain3){make_domain(:name => "sub.#{domain.name}", :user => user3)} let(:subdomain3){make_domain(:name => "sub.#{domain.name}", :user => user3)}
let(:subsubdomain3){make_domain(:name => "sub.#{subdomain.name}", :user => user3)} let(:subsubdomain3){make_domain(:name => "sub.#{subdomain.name}", :user => user3)}
# admin's host domain (like entrydns.org) # admin's host domain (like entrydns.org)
let(:host_domain){make_domain(:user => admin, :name => Settings.host_domains.first)} let(:host_domain){make_domain(:user => admin, :name => Settings.host_domains.first)}
let(:a_record){create(:a, :content => '127.0.0.1', :domain => domain)} let(:a_record){create(:a, :content => '127.0.0.1', :domain => domain)}
let(:soa_record){domain.soa_record} let(:soa_record){domain.soa_record}
let(:host_a_record){create(:a, :content => '127.0.0.1', :domain => host_domain, :user => user)} let(:host_a_record){create(:a, :content => '127.0.0.1', :domain => host_domain, :user => user)}
let(:permission){create(:permission, :domain => domain, :user => user2)} let(:permission){create(:permission, :domain => domain, :user => user2)}
let(:permission3){create(:permission, :domain => domain3, :user => user)} let(:permission3){create(:permission, :domain => domain3, :user => user)}
let(:blacklisted_domain){create(:blacklisted_domain)} let(:blacklisted_domain){create(:blacklisted_domain)}
# admin model # admin model
let(:admin_admin){create(:admin)} let(:admin_admin){create(:admin)}
end end

16
spec/support/shared_examples/wiring_controller.rb

@ -2,39 +2,39 @@ shared_examples_for "wiring controller" do
context "wiring" do context "wiring" do
include_context "data" include_context "data"
let(:record){Record.new} let(:record){Record.new}
context "on owned domain" do context "on owned domain" do
before do before do
sign_in user sign_in user
@controller.stub(:nested_parent_record => domain) @controller.stub(:nested_parent_record => domain)
end end
it "#new_model is wired" do it "#new_model is wired" do
@controller.send(:new_model).user.should == domain.user @controller.send(:new_model).user.should == domain.user
end end
it "#before_create_save wires" do it "#before_create_save wires" do
@controller.send(:before_create_save, record) @controller.send(:before_create_save, record)
record.user.should == domain.user record.user.should == domain.user
end end
end end
context "on permitted domain" do context "on permitted domain" do
before do before do
sign_in user2 sign_in user2
permission # touch to ensure creation permission # touch to ensure creation
@controller.stub(:nested_parent_record => domain) @controller.stub(:nested_parent_record => domain)
end end
it "#new_model is wired" do it "#new_model is wired" do
@controller.send(:new_model).user.should == domain.user @controller.send(:new_model).user.should == domain.user
end end
it "#before_create_save wires" do it "#before_create_save wires" do
@controller.send(:before_create_save, record) @controller.send(:before_create_save, record)
record.user.should == domain.user record.user.should == domain.user
end end
end end
end end
end end

Loading…
Cancel
Save