diff --git a/Gemfile b/Gemfile index 78c803d..7031993 100644 --- a/Gemfile +++ b/Gemfile @@ -3,13 +3,18 @@ source 'https://rubygems.org' gem 'rails', '3.2.8' gem 'sqlite3' +gem 'devise' group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' + # See https://github.com/sstephenson/execjs#readme for more supported runtimes + gem 'therubyracer', :platforms => :ruby + gem 'jquery-ui-rails' gem 'uglifier', '>= 1.0.3' end +gem 'jquery-rails' group :development, :test do gem 'debugger' diff --git a/Gemfile.lock b/Gemfile.lock index 5a5eab4..35ecf74 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -30,6 +30,7 @@ GEM multi_json (~> 1.0) addressable (2.3.2) arel (3.0.2) + bcrypt-ruby (3.0.1) builder (3.0.3) capybara (1.1.2) mime-types (>= 1.16) @@ -70,6 +71,11 @@ GEM debugger-linecache (1.1.2) debugger-ruby_core_source (>= 1.1.1) debugger-ruby_core_source (1.1.3) + devise (2.1.2) + bcrypt-ruby (~> 3.0) + orm_adapter (~> 0.1) + railties (~> 3.1) + warden (~> 1.2.1) diff-lcs (1.1.3) erubis (2.7.0) execjs (1.4.0) @@ -80,9 +86,16 @@ GEM hike (1.2.1) i18n (0.6.1) journey (1.0.4) + jquery-rails (2.1.3) + railties (>= 3.1.0, < 5.0) + thor (~> 0.14) + jquery-ui-rails (2.0.2) + jquery-rails + railties (>= 3.1.0) json (1.7.5) launchy (2.1.2) addressable (~> 2.3) + libv8 (3.3.10.4) libwebsocket (0.1.5) addressable mail (2.4.4) @@ -92,6 +105,7 @@ GEM mime-types (1.19) multi_json (1.3.6) nokogiri (1.5.5) + orm_adapter (0.4.0) polyglot (0.3.3) rack (1.4.1) rack-cache (1.2) @@ -150,6 +164,8 @@ GEM steak (2.0.0) capybara (>= 1.0.0) rspec-rails (>= 2.5.0) + therubyracer (0.10.2) + libv8 (~> 3.3.10) thor (0.16.0) tilt (1.3.3) treetop (1.4.10) @@ -159,6 +175,8 @@ GEM uglifier (1.3.0) execjs (>= 0.3.0) multi_json (~> 1.0, >= 1.0.2) + warden (1.2.1) + rack (>= 1.0) xpath (0.1.4) nokogiri (~> 1.3) @@ -172,10 +190,14 @@ DEPENDENCIES cucumber-rails-training-wheels database_cleaner debugger + devise + jquery-rails + jquery-ui-rails launchy rails (= 3.2.8) rspec-rails sass-rails (~> 3.2.3) sqlite3 steak + therubyracer uglifier (>= 1.0.3) diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 0000000..9ec3adc --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,4 @@ +class HomeController < ApplicationController + def index + end +end \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000..02543cc --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,11 @@ +class User < ActiveRecord::Base + # Include default devise modules. Others available are: + # :token_authenticatable, :confirmable, + # :lockable, :timeoutable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :trackable, :validatable + + # Setup accessible (or protected) attributes for your model + attr_accessible :email, :password, :password_confirmation, :remember_me + # attr_accessible :title, :body +end diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 0000000..166c635 --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,25 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.label :password, "Пароль" %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, :autocomplete => "off" %>
+ +
<%= f.label :password_confirmation, "Подтверждение" %>
+ <%= f.password_field :password_confirmation %>
+ +
<%= f.label :current_password, "Текущий пароль" %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password %>
+ +
<%= f.submit "Update" %>
+<% end %> + +

Cancel my account

+ +

Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %>.

+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 0000000..8c49758 --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,18 @@ +

Sign up

+ +<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.label :password, "Пароль" %>
+ <%= f.password_field :password %>
+ +
<%= f.label :password_confirmation, "Подтверждение" %>
+ <%= f.password_field :password_confirmation %>
+ +
<%= f.submit "Зарегистрироваться" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 0000000..e54ff35 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,17 @@ +

Sign in

+ +<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %> +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.label :password_field, "Пароль" %>
+ <%= f.password_field :password %>
+ + <% if devise_mapping.rememberable? -%> +
<%= f.check_box :remember_me %> <%= f.label :remember_me %>
+ <% end -%> + +
<%= f.submit "Sign in" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb new file mode 100644 index 0000000..4f4c951 --- /dev/null +++ b/app/views/home/index.html.erb @@ -0,0 +1 @@ +Hello vrot! \ No newline at end of file diff --git a/app/views/layouts/_notices.html.erb b/app/views/layouts/_notices.html.erb new file mode 100644 index 0000000..f88e558 --- /dev/null +++ b/app/views/layouts/_notices.html.erb @@ -0,0 +1,3 @@ +<%- flash.each do |name, msg| -%> + <%= content_tag :div, msg, id: "flash_#{name}", class: "flash" if msg.is_a?(String) %> +<%- end -%> \ No newline at end of file diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 94dbe1a..cf75cbb 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -7,8 +7,13 @@ <%= csrf_meta_tags %> + <%= render 'layouts/notices' %> + -<%= yield %> + <%= yield %> diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb new file mode 100644 index 0000000..b001602 --- /dev/null +++ b/app/views/sessions/new.html.erb @@ -0,0 +1,17 @@ +

Sign in

+ +<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %> +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.label :password_field, "Пароль" %>
+ <%= f.password_field :password %>
+ + <% if devise_mapping.rememberable? -%> +
<%= f.check_box :remember_me, "Запомнить меня" %> <%= f.label :remember_me %>
+ <% end -%> + +
<%= f.submit "Sign in" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/users/confirmations/new.html.erb b/app/views/users/confirmations/new.html.erb new file mode 100644 index 0000000..81e4472 --- /dev/null +++ b/app/views/users/confirmations/new.html.erb @@ -0,0 +1,12 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, :as => resource_name, :url => confirmation_path(resource_name), :html => { :method => :post }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.submit "Resend confirmation instructions" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/users/mailer/confirmation_instructions.html.erb b/app/views/users/mailer/confirmation_instructions.html.erb new file mode 100644 index 0000000..a5c4585 --- /dev/null +++ b/app/views/users/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @resource.email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token) %>

diff --git a/app/views/users/mailer/reset_password_instructions.html.erb b/app/views/users/mailer/reset_password_instructions.html.erb new file mode 100644 index 0000000..ae9e888 --- /dev/null +++ b/app/views/users/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password, and you can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, :reset_password_token => @resource.reset_password_token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/users/mailer/unlock_instructions.html.erb b/app/views/users/mailer/unlock_instructions.html.erb new file mode 100644 index 0000000..2263c21 --- /dev/null +++ b/app/views/users/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive amount of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token) %>

diff --git a/app/views/users/passwords/edit.html.erb b/app/views/users/passwords/edit.html.erb new file mode 100644 index 0000000..fe620ef --- /dev/null +++ b/app/views/users/passwords/edit.html.erb @@ -0,0 +1,16 @@ +

Change your password

+ +<%= form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :put }) do |f| %> + <%= devise_error_messages! %> + <%= f.hidden_field :reset_password_token %> + +
<%= f.label :password, "New password" %>
+ <%= f.password_field :password %>
+ +
<%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation %>
+ +
<%= f.submit "Change my password" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/users/passwords/new.html.erb b/app/views/users/passwords/new.html.erb new file mode 100644 index 0000000..2350164 --- /dev/null +++ b/app/views/users/passwords/new.html.erb @@ -0,0 +1,12 @@ +

Forgot your password?

+ +<%= form_for(resource, :as => resource_name, :url => password_path(resource_name), :html => { :method => :post }) do |f| %> + <%= devise_error_messages! %> + +
<%= f.label :email %>
+ <%= f.email_field :email %>
+ +
<%= f.submit "Send me reset password instructions" %>
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/users/shared/_links.erb b/app/views/users/shared/_links.erb new file mode 100644 index 0000000..e3ae6f6 --- /dev/null +++ b/app/views/users/shared/_links.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Войти", new_session_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Регистрация", new_registration_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' %> + <%= link_to "Забыл пароль?", new_password_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Не получал инструкий для подтверждения?", new_confirmation_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Не получал инструкций для разблокирования?", new_unlock_path(resource_name) %>
+<% end -%> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
+ <% end -%> +<% end -%> \ No newline at end of file diff --git a/app/views/users/shared/_login_links.html.erb b/app/views/users/shared/_login_links.html.erb new file mode 100644 index 0000000..014349e --- /dev/null +++ b/app/views/users/shared/_login_links.html.erb @@ -0,0 +1,9 @@ +<% if user_signed_in? %> +
  • + <%= link_to('Выход', destroy_user_session_path, :method => :delete) %> +
  • +<% else %> +
  • + <%= link_to('Войти', new_user_session_path) %> +
  • +<% end %> \ No newline at end of file diff --git a/app/views/users/shared/_signup_links.html.erb b/app/views/users/shared/_signup_links.html.erb new file mode 100644 index 0000000..f634379 --- /dev/null +++ b/app/views/users/shared/_signup_links.html.erb @@ -0,0 +1,9 @@ +<% if user_signed_in? %> +
  • + <%= link_to('Изменить профиль', edit_user_registration_path) %> +
  • +<% else %> +
  • + <%= link_to('Регистрация', new_user_registration_path) %> +
  • +<% end %> \ No newline at end of file diff --git a/app/views/users/unlocks/new.html.erb b/app/views/users/unlocks/new.html.erb new file mode 100644 index 0000000..e55e82e --- /dev/null +++ b/app/views/users/unlocks/new.html.erb @@ -0,0 +1,12 @@ +

    Resend unlock instructions

    + +<%= form_for(resource, :as => resource_name, :url => unlock_path(resource_name), :html => { :method => :post }) do |f| %> + <%= devise_error_messages! %> + +
    <%= f.label :email %>
    + <%= f.email_field :email %>
    + +
    <%= f.submit "Resend unlock instructions" %>
    +<% end %> + +<%= render "devise/shared/links" %> diff --git a/config/application.rb b/config/application.rb index 5e4b784..f242a36 100644 --- a/config/application.rb +++ b/config/application.rb @@ -31,7 +31,7 @@ class Application < Rails::Application # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] - # config.i18n.default_locale = :de + config.i18n.default_locale = :ru # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..cf32125 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,232 @@ +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class with default "from" parameter. + config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com" + + # Configure the class responsible to send e-mails. + # config.mailer = "Devise::Mailer" + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [ :email ] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [ :email ] + + # Configure which authentication keys should have whitespace stripped. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [ :email ] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable it only for database (email + password) authentication. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Basic Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:token]` will + # enable it only for token authentication. + # config.http_authenticatable = false + + # If http headers should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. "Application" by default. + # config.http_authentication_realm = "Application" + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # :http_auth and :token_auth by adding those symbols to the array below. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing :skip => :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 10. If + # using other encryptors, it sets how many times you want the password re-encrypted. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. + config.stretches = Rails.env.test? ? 1 : 10 + + # Setup a pepper to generate the encrypted password. + # config.pepper = "ad6202ba92ee1f98b2fdef459c73702ab972a99057d87ab99f1d41f16ff42497d5ace70b9955303eb918e20ea80c316ff506e5c55f2d2818ddf327ec174b2d1c" + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming his account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming his account, + # access will be blocked just in the third day. Default is 0.days, meaning + # the user cannot access the website without confirming his account. + # config.allow_unconfirmed_access_for = 2.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed new email is stored in + # unconfirmed email column, and copied to email column on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [ :email ] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # :secure => true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. Default is 6..128. + # config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # an one (and only one) @ exists in the given string. This is mainly + # to give user feedback and not to assert the e-mail validity. + # config.email_regexp = /\A[^@]+@[^@]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. + # config.timeout_in = 30.minutes + + # If true, expires auth token on session timeout. + # config.expire_auth_token_on_timeout = false + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [ :email ] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. + # config.unlock_in = 1.hour + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.reset_password_keys = [ :email ] + + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # ==> Configuration for :encryptable + # Allow you to use another encryption algorithm besides bcrypt (default). You can use + # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, + # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) + # and :restful_authentication_sha1 (then you should set stretches to 10, and copy + # REST_AUTH_SITE_KEY to pepper) + # config.encryptor = :sha512 + + # ==> Configuration for :token_authenticatable + # Defines name of the authentication token params key + # config.token_authentication_key = :auth_token + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # The "*/*" below is required to match Internet Explorer requests. + # config.navigational_formats = ["*/*", :html] + + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(:scope => :user).unshift :some_external_strategy + # end + + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: "/my_engine" + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using omniauth, Devise cannot automatically set Omniauth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = "/my_engine/users/auth" +end \ No newline at end of file diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 0000000..7783a74 --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,58 @@ +# Additional translations at https://github.com/plataformatec/devise/wiki/I18n + +en: + errors: + messages: + expired: "has expired, please request a new one" + not_found: "not found" + already_confirmed: "was already confirmed, please try signing in" + not_locked: "was not locked" + not_saved: + one: "1 error prohibited this %{resource} from being saved:" + other: "%{count} errors prohibited this %{resource} from being saved:" + + devise: + failure: + already_authenticated: 'You are already signed in.' + unauthenticated: 'You need to sign in or sign up before continuing.' + unconfirmed: 'You have to confirm your account before continuing.' + locked: 'Your account is locked.' + invalid: 'Invalid email or password.' + invalid_token: 'Invalid authentication token.' + timeout: 'Your session expired, please sign in again to continue.' + inactive: 'Your account was not activated yet.' + sessions: + signed_in: 'Signed in successfully.' + signed_out: 'Signed out successfully.' + passwords: + send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' + updated: 'Your password was changed successfully. You are now signed in.' + updated_not_active: 'Your password was changed successfully.' + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + confirmations: + send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.' + send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes.' + confirmed: 'Your account was successfully confirmed. You are now signed in.' + registrations: + signed_up: 'Welcome! You have signed up successfully.' + signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.' + signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.' + signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.' + updated: 'You updated your account successfully.' + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." + destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' + unlocks: + send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' + unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' + send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.' + omniauth_callbacks: + success: 'Successfully authenticated from %{kind} account.' + failure: 'Could not authenticate you from %{kind} because "%{reason}".' + mailer: + confirmation_instructions: + subject: 'Confirmation instructions' + reset_password_instructions: + subject: 'Reset password instructions' + unlock_instructions: + subject: 'Unlock Instructions' diff --git a/config/locales/devise.ru.yml b/config/locales/devise.ru.yml new file mode 100644 index 0000000..1afdb91 --- /dev/null +++ b/config/locales/devise.ru.yml @@ -0,0 +1,75 @@ +ru: + errors: + messages: + expired: "устарела. Пожалуйста, запросите новую" + not_found: "не найдена" + already_confirmed: "уже подтверждена. Пожалуйста, попробуйте войти в систему" + not_locked: "не заблокирована" + not_saved: + one: "%{resource}: сохранение не удалось из-за %{count} ошибки" + few: "%{resource}: сохранение не удалось из-за %{count} ошибок" + many: "%{resource}: сохранение не удалось из-за %{count} ошибок" + other: "%{resource}: сохранение не удалось из-за %{count} ошибки" + + devise: + failure: + already_authenticated: "Вы уже вошли в систему." + unauthenticated: "Вам необходимо войти в систему или зарегистрироваться." + unconfirmed: "Вы должны подтвердить вашу учётную запись." + locked: "Ваша учётная запись заблокирована." + invalid: "Неверный адрес e-mail или пароль." + invalid_token: "Неверный ключ аутентификации." + timeout: "Ваш сеанс закончился. Пожалуйста, войдите в систему снова." + inactive: "Ваша учётная запись ещё не активирована." + sessions: + signed_in: "Вход в систему выполнен." + signed_out: "Выход из системы выполнен." + passwords: + send_instructions: "В течение нескольких минут вы получите письмо с инструкциями по восстановлению вашего пароля." + updated: "Ваш пароль изменён. Теперь вы вошли в систему." + updated_not_active: 'Ваш пароль изменен.' + send_paranoid_instructions: "Если ваш адрес e-mail есть в нашей базе данных, то в течение нескольких минут вы получите письмо с инструкциями по восстановлению вашего пароля." + confirmations: + send_instructions: "В течение нескольких минут вы получите письмо с инструкциями по подтверждению вашей учётной записи." + send_paranoid_instructions: "Если ваш адрес e-mail есть в нашей базе данных, то в течение нескольких минут вы получите письмо с инструкциями по подтверждению вашей учётной записи." + confirmed: "Ваша учётная запись подтверждена. Теперь вы вошли в систему." + registrations: + signed_up: "Спасибо за регистрацию" + inactive_signed_up: "Добро пожаловать! Вы успешно зарегистрировались. Но пока вы не можете войти в систему, т.к. ваша учётная запись %{reason}." + updated: "Ваша учётная запись изменена." + destroyed: "До свидания! Ваша учётная запись удалена. Надеемся снова увидеть вас." + reasons: + inactive: 'неактивна' + unconfirmed: 'не подтверждена' + locked: 'заблокирована' + unlocks: + send_instructions: "В течение нескольких минут вы получите письмо с инструкциями по разблокировке вашей учётной записи." + unlocked: "Ваша учётная запись разблокирована. Теперь вы вошли в систему." + send_paranoid_instructions: "Если ваша учётная запись существует, то в течение нескольких минут вы получите письмо с инструкциями по её разблокировке." + omniauth_callbacks: + success: "Вход в систему выполнен с учётной записью из %{kind}." + failure: "Вы не можете войти в систему с учётной записью из %{kind}, т.к. \"%{reason}\"." + mailer: + confirmation_instructions: + subject: "Инструкции по подтверждению учётной записи" + reset_password_instructions: + subject: "Инструкции по восстановлению пароля" + unlock_instructions: + subject: "Инструкции по разблокировке учётной записи" + +ru: + activerecord: + errors: + models: + user: + attributes: + email: + taken: 'Пользователь с таким адресом уже зарегистрирован' + + errors: + messages: + not_saved: 'Какая досада, сохранить не удалось :(' + devise: + registrations: + user: + signed_up: "Спасибо за регистрацию" \ No newline at end of file diff --git a/config/locales/ru.yml b/config/locales/ru.yml new file mode 100644 index 0000000..f5701bd --- /dev/null +++ b/config/locales/ru.yml @@ -0,0 +1,257 @@ +ru: + date: + abbr_day_names: + - Вс + - Пн + - Вт + - Ср + - Чт + - Пт + - Сб + abbr_month_names: + - + - янв. + - февр. + - марта + - апр. + - мая + - июня + - июля + - авг. + - сент. + - окт. + - нояб. + - дек. + day_names: + - воскресенье + - понедельник + - вторник + - среда + - четверг + - пятница + - суббота + formats: + default: ! '%d.%m.%Y' + long: ! '%d %B %Y' + short: ! '%d %b' + month_names: + - + - января + - февраля + - марта + - апреля + - мая + - июня + - июля + - августа + - сентября + - октября + - ноября + - декабря + order: + - :day + - :month + - :year + datetime: + distance_in_words: + about_x_hours: + few: около %{count} часов + many: около %{count} часов + one: около %{count} часа + other: около %{count} часа + about_x_months: + few: около %{count} месяцев + many: около %{count} месяцев + one: около %{count} месяца + other: около %{count} месяца + about_x_years: + few: около %{count} лет + many: около %{count} лет + one: около %{count} года + other: около %{count} лет + almost_x_years: + one: почти 1 год + few: почти %{count} года + many: почти %{count} лет + other: почти %{count} лет + half_a_minute: меньше минуты + less_than_x_minutes: + few: меньше %{count} минут + many: меньше %{count} минут + one: меньше %{count} минуты + other: меньше %{count} минуты + less_than_x_seconds: + few: меньше %{count} секунд + many: меньше %{count} секунд + one: меньше %{count} секунды + other: меньше %{count} секунды + over_x_years: + few: больше %{count} лет + many: больше %{count} лет + one: больше %{count} года + other: больше %{count} лет + x_days: + few: ! '%{count} дня' + many: ! '%{count} дней' + one: ! '%{count} день' + other: ! '%{count} дня' + x_minutes: + few: ! '%{count} минуты' + many: ! '%{count} минут' + one: ! '%{count} минуту' + other: ! '%{count} минуты' + x_months: + few: ! '%{count} месяца' + many: ! '%{count} месяцев' + one: ! '%{count} месяц' + other: ! '%{count} месяца' + x_seconds: + few: ! '%{count} секунды' + many: ! '%{count} секунд' + one: ! '%{count} секунда' + other: ! '%{count} секунды' + prompts: + day: День + hour: Часов + minute: Минут + month: Месяц + second: Секунд + year: Год + errors: &errors + format: ! '%{attribute}: %{message}' + messages: + accepted: нужно подтвердить + blank: не может быть пустым + confirmation: не совпадает с подтверждением + empty: не может быть пустым + equal_to: может иметь лишь значение, равное %{count} + even: может иметь лишь нечетное значение + exclusion: имеет зарезервированное значение + greater_than: может иметь значение большее %{count} + greater_than_or_equal_to: может иметь значение большее или равное %{count} + inclusion: имеет непредусмотренное значение + invalid: имеет неверное значение + less_than: может иметь значение меньшее чем %{count} + less_than_or_equal_to: может иметь значение меньшее или равное %{count} + not_a_number: не является числом + not_an_integer: не является целым числом + odd: может иметь лишь четное значение + record_invalid: ! 'Возникли ошибки: %{errors}' + taken: уже существует + too_long: + few: слишком большой длины (не может быть больше чем %{count} символа) + many: слишком большой длины (не может быть больше чем %{count} символов) + one: слишком большой длины (не может быть больше чем %{count} символ) + other: слишком большой длины (не может быть больше чем %{count} символа) + too_short: + few: недостаточной длины (не может быть меньше %{count} символов) + many: недостаточной длины (не может быть меньше %{count} символов) + one: недостаточной длины (не может быть меньше %{count} символа) + other: недостаточной длины (не может быть меньше %{count} символа) + wrong_length: + few: неверной длины (может быть длиной ровно %{count} символа) + many: неверной длины (может быть длиной ровно %{count} символов) + one: неверной длины (может быть длиной ровно %{count} символ) + other: неверной длины (может быть длиной ровно %{count} символа) + template: + body: ! 'Проблемы возникли со следующими полями:' + header: + few: ! '%{model}: сохранение не удалось из-за %{count} ошибок' + many: ! '%{model}: сохранение не удалось из-за %{count} ошибок' + one: ! '%{model}: сохранение не удалось из-за %{count} ошибки' + other: ! '%{model}: сохранение не удалось из-за %{count} ошибки' + helpers: + select: + prompt: ! 'Выберите: ' + submit: + create: Создать %{model} + submit: Сохранить %{model} + update: Сохранить %{model} + number: + currency: + format: + delimiter: ! ' ' + format: ! '%n %u' + precision: 2 + separator: . + significant: false + strip_insignificant_zeros: false + unit: руб. + format: + delimiter: ! ' ' + precision: 3 + separator: . + significant: false + strip_insignificant_zeros: false + human: + decimal_units: + format: ! '%n %u' + units: + billion: + few: миллиардов + many: миллиардов + one: миллиард + other: миллиардов + million: + few: миллионов + many: миллионов + one: миллион + other: миллионов + quadrillion: + few: квадриллионов + many: квадриллионов + one: квадриллион + other: квадриллионов + thousand: + few: тысяч + many: тысяч + one: тысяча + other: тысяч + trillion: + few: триллионов + many: триллионов + one: триллион + other: триллионов + unit: '' + format: + delimiter: '' + precision: 1 + significant: false + strip_insignificant_zeros: false + storage_units: + format: ! '%n %u' + units: + byte: + few: байта + many: байт + one: байт + other: байта + gb: ГБ + kb: КБ + mb: МБ + tb: ТБ + percentage: + format: + delimiter: '' + precision: + format: + delimiter: '' + support: + array: + last_word_connector: ! ' и ' + two_words_connector: ! ' и ' + words_connector: ! ', ' + time: + am: утра + formats: + default: ! '%a, %d %b %Y, %H:%M:%S %z' + long: ! '%d %B %Y, %H:%M' + short: ! '%d %b, %H:%M' + pm: вечера + # remove these aliases after 'activemodel' and 'activerecord' namespaces are removed from Rails repository + activemodel: + errors: + <<: *errors + activerecord: + errors: + <<: *errors \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 1877402..7cbb7c8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,8 @@ BarcampKg2012AcceptanceTestsDemo::Application.routes.draw do + devise_for :users + + root :to => 'home#index' + # The priority is based upon order of creation: # first created -> highest priority. diff --git a/db/migrate/20121007025500_devise_create_users.rb b/db/migrate/20121007025500_devise_create_users.rb new file mode 100644 index 0000000..2099d99 --- /dev/null +++ b/db/migrate/20121007025500_devise_create_users.rb @@ -0,0 +1,46 @@ +class DeviseCreateUsers < ActiveRecord::Migration + def change + create_table(:users) do |t| + ## Database authenticatable + t.string :email, :null => false, :default => "" + t.string :encrypted_password, :null => false, :default => "" + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## Trackable + t.integer :sign_in_count, :default => 0 + t.datetime :current_sign_in_at + t.datetime :last_sign_in_at + t.string :current_sign_in_ip + t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + ## Token authenticatable + # t.string :authentication_token + + + t.timestamps + end + + add_index :users, :email, :unique => true + add_index :users, :reset_password_token, :unique => true + # add_index :users, :confirmation_token, :unique => true + # add_index :users, :unlock_token, :unique => true + # add_index :users, :authentication_token, :unique => true + end +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..6e2d3f7 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,34 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended to check this file into your version control system. + +ActiveRecord::Schema.define(:version => 20121007025500) do + + create_table "users", :force => true do |t| + t.string "email", :default => "", :null => false + t.string "encrypted_password", :default => "", :null => false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.integer "sign_in_count", :default => 0 + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.string "current_sign_in_ip" + t.string "last_sign_in_ip" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + + add_index "users", ["email"], :name => "index_users_on_email", :unique => true + add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true + +end diff --git a/features/signup.feature b/features/signup.feature index 257e09f..3e58b45 100644 --- a/features/signup.feature +++ b/features/signup.feature @@ -22,7 +22,7 @@ И ввожу "654321" в поле "Подтверждение" И нажимаю "Зарегистрироваться" - То я должен увидеть "Подтверждение пароля не совпадает" + То я должен увидеть "Password: не совпадает с подтверждением" Сценарий: Пользователь пытается зарегистрироваться с уже занятым адресом Допустим я нахожусь на странице регистрации @@ -30,6 +30,8 @@ И ввожу "123456" в поле "Пароль" И ввожу "123456" в поле "Подтверждение" И нажимаю "Зарегистрироваться" + И перехожу по ссылке "Выход" + И я нахожусь на странице регистрации Если я ввожу "daniel.vartanov@gmail.com" в поле "Email" И ввожу "123456" в поле "Пароль" diff --git a/features/step_definitions/navigation_steps.rb b/features/step_definitions/navigation_steps.rb index c86cf7a..3e50d88 100644 --- a/features/step_definitions/navigation_steps.rb +++ b/features/step_definitions/navigation_steps.rb @@ -5,7 +5,8 @@ end Given /я нахожусь на странице регистрации/ do - visit '/signup' + visit '/' + click_link('Регистрация') end When /ввожу "(.*)" в поле "(.*)"$/ do |value, field| diff --git a/features/support/paths.rb b/features/support/paths.rb index 290543c..69c0c9b 100644 --- a/features/support/paths.rb +++ b/features/support/paths.rb @@ -15,6 +15,7 @@ def path_to(page_name) when /^the home\s?page$/ '/' + # Add more mappings here. # Here is an example that pulls values out of the Regexp: diff --git a/public/index.html b/public/index.html deleted file mode 100644 index a1d5099..0000000 --- a/public/index.html +++ /dev/null @@ -1,241 +0,0 @@ - - - - Ruby on Rails: Welcome aboard - - - - -
    - - -
    - - - - -
    -

    Getting started

    -

    Here’s how to get rolling:

    - -
      -
    1. -

      Use rails generate to create your models and controllers

      -

      To see all available options, run it without parameters.

      -
    2. - -
    3. -

      Set up a default route and remove public/index.html

      -

      Routes are set up in config/routes.rb.

      -
    4. - -
    5. -

      Create your database

      -

      Run rake db:create to create your database. If you're not using SQLite (the default), edit config/database.yml with your username and password.

      -
    6. -
    -
    -
    - - -
    - - diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 0000000..c63aac0 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html + +# This model initially had no columns defined. If you add columns to the +# model remove the '{}' from the fixture names and add the columns immediately +# below each fixture, per the syntax in the comments below +# +one: {} +# column: value +# +two: {} +# column: value diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb new file mode 100644 index 0000000..82f61e0 --- /dev/null +++ b/test/unit/user_test.rb @@ -0,0 +1,7 @@ +require 'test_helper' + +class UserTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end