diff --git a/.gitignore b/.gitignore index d619f77..d510f30 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ config/database.yml # Docker .docker-custom.yml + +# Gemfile.lock +.Gemfile.lock diff --git a/Gemfile b/Gemfile index 2536463..13daac9 100644 --- a/Gemfile +++ b/Gemfile @@ -18,6 +18,9 @@ gem "rails_admin" gem "dotenv-rails" gem "pg" gem "sqlite3", require: true +gem 'omniauth-twitter' +gem 'omniauth-google-oauth2' +gem 'devise' group :assets do gem "sass-rails" @@ -33,15 +36,19 @@ end group :development, :test do gem "rspec-rails" gem "database_cleaner" - gem "capybara" + # gem "capybara" gem "shoulda-matchers" gem "launchy" end group :test do gem "factory_girl_rails" - gem "rspec-instafail" +# gem "rspec-instafail" gem "codeclimate-test-reporter", require: nil + gem 'capybara' +# gem 'selenium-webdriver' + gem 'webrick' + gem 'capybara-webkit' end group :production do diff --git a/Gemfile.lock b/Gemfile.lock deleted file mode 100644 index 470ca31..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,291 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - actionmailer (4.2.4) - actionpack (= 4.2.4) - actionview (= 4.2.4) - activejob (= 4.2.4) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 1.0, >= 1.0.5) - actionpack (4.2.4) - actionview (= 4.2.4) - activesupport (= 4.2.4) - rack (~> 1.6) - rack-test (~> 0.6.2) - rails-dom-testing (~> 1.0, >= 1.0.5) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - actionview (4.2.4) - activesupport (= 4.2.4) - builder (~> 3.1) - erubis (~> 2.7.0) - rails-dom-testing (~> 1.0, >= 1.0.5) - rails-html-sanitizer (~> 1.0, >= 1.0.2) - activejob (4.2.4) - activesupport (= 4.2.4) - globalid (>= 0.3.0) - activemodel (4.2.4) - activesupport (= 4.2.4) - builder (~> 3.1) - activerecord (4.2.4) - activemodel (= 4.2.4) - activesupport (= 4.2.4) - arel (~> 6.0) - activesupport (4.2.4) - i18n (~> 0.7) - json (~> 1.7, >= 1.7.7) - minitest (~> 5.1) - thread_safe (~> 0.3, >= 0.3.4) - tzinfo (~> 1.1) - addressable (2.3.8) - annotate (2.6.10) - activerecord (>= 3.2, <= 4.3) - rake (~> 10.4) - arel (6.0.3) - autoprefixer-rails (5.2.1.1) - execjs - json - bootstrap-sass (3.3.5.1) - autoprefixer-rails (>= 5.0.0.1) - sass (>= 3.3.0) - builder (3.2.2) - capybara (2.4.4) - mime-types (>= 1.16) - nokogiri (>= 1.3.3) - rack (>= 1.0.0) - rack-test (>= 0.5.4) - xpath (~> 2.0) - codeclimate-test-reporter (0.4.7) - simplecov (>= 0.7.1, < 1.0.0) - coffee-rails (4.1.0) - coffee-script (>= 2.2.0) - railties (>= 4.0.0, < 5.0) - coffee-script (2.4.1) - coffee-script-source - execjs - coffee-script-source (1.9.1.1) - database_cleaner (1.4.1) - diff-lcs (1.2.5) - dim (1.2.7) - docile (1.1.5) - domino (0.7.0) - capybara (>= 0.4.0) - dotenv (2.0.2) - dotenv-rails (2.0.2) - dotenv (= 2.0.2) - railties (~> 4.0) - erubis (2.7.0) - exception_notification (4.1.1) - actionmailer (>= 3.0.4) - activesupport (>= 3.0.4) - execjs (2.5.2) - factory_girl (4.5.0) - activesupport (>= 3.0.0) - factory_girl_rails (4.5.0) - factory_girl (~> 4.5.0) - railties (>= 3.0.0) - filepicker-rails (2.0.0) - rails (>= 3.2) - font-awesome-rails (4.3.0.0) - railties (>= 3.2, < 5.0) - foreigner (1.7.4) - activerecord (>= 3.0.0) - foreman (0.78.0) - thor (~> 0.19.1) - globalid (0.3.6) - activesupport (>= 4.1.0) - haml (4.0.6) - tilt - haml-rails (0.9.0) - actionpack (>= 4.0.1) - activesupport (>= 4.0.1) - haml (>= 4.0.6, < 5.0) - html2haml (>= 1.0.1) - railties (>= 4.0.1) - html2haml (2.0.0) - erubis (~> 2.7.0) - haml (~> 4.0.0) - nokogiri (~> 1.6.0) - ruby_parser (~> 3.5) - i18n (0.7.0) - jquery-rails (3.1.3) - railties (>= 3.0, < 5.0) - thor (>= 0.14, < 2.0) - jquery-ui-rails (5.0.5) - railties (>= 3.2.16) - json (1.8.3) - kaminari (0.16.3) - actionpack (>= 3.0.0) - activesupport (>= 3.0.0) - kgio (2.9.3) - launchy (2.4.3) - addressable (~> 2.3) - loofah (2.0.3) - nokogiri (>= 1.5.9) - mail (2.6.3) - mime-types (>= 1.16, < 3) - mime-types (2.6.2) - mini_portile (0.6.2) - minitest (5.8.0) - nested_form (0.3.2) - nokogiri (1.6.6.2) - mini_portile (~> 0.6.0) - pg (0.18.2) - rack (1.6.4) - rack-pjax (0.8.0) - nokogiri (~> 1.5) - rack (~> 1.1) - rack-test (0.6.3) - rack (>= 1.0) - rails (4.2.4) - actionmailer (= 4.2.4) - actionpack (= 4.2.4) - actionview (= 4.2.4) - activejob (= 4.2.4) - activemodel (= 4.2.4) - activerecord (= 4.2.4) - activesupport (= 4.2.4) - bundler (>= 1.3.0, < 2.0) - railties (= 4.2.4) - sprockets-rails - rails-deprecated_sanitizer (1.0.3) - activesupport (>= 4.2.0.alpha) - rails-dom-testing (1.0.7) - activesupport (>= 4.2.0.beta, < 5.0) - nokogiri (~> 1.6.0) - rails-deprecated_sanitizer (>= 1.0.1) - rails-html-sanitizer (1.0.2) - loofah (~> 2.0) - rails_12factor (0.0.3) - rails_serve_static_assets - rails_stdout_logging - rails_admin (0.6.8) - builder (~> 3.1) - coffee-rails (~> 4.0) - font-awesome-rails (>= 3.0, < 5) - haml (~> 4.0) - jquery-rails (>= 3.0, < 5) - jquery-ui-rails (~> 5.0) - kaminari (~> 0.14) - nested_form (~> 0.3) - rack-pjax (~> 0.7) - rails (~> 4.0) - remotipart (~> 1.0) - safe_yaml (~> 1.0) - sass-rails (>= 4.0, < 6) - rails_serve_static_assets (0.0.4) - rails_stdout_logging (0.0.4) - railties (4.2.4) - actionpack (= 4.2.4) - activesupport (= 4.2.4) - rake (>= 0.8.7) - thor (>= 0.18.1, < 2.0) - raindrops (0.14.0) - rake (10.4.2) - remotipart (1.2.1) - rspec (3.3.0) - rspec-core (~> 3.3.0) - rspec-expectations (~> 3.3.0) - rspec-mocks (~> 3.3.0) - rspec-core (3.3.2) - rspec-support (~> 3.3.0) - rspec-expectations (3.3.1) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.3.0) - rspec-instafail (0.2.6) - rspec - rspec-mocks (3.3.2) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.3.0) - rspec-rails (3.3.3) - actionpack (>= 3.0, < 4.3) - activesupport (>= 3.0, < 4.3) - railties (>= 3.0, < 4.3) - rspec-core (~> 3.3.0) - rspec-expectations (~> 3.3.0) - rspec-mocks (~> 3.3.0) - rspec-support (~> 3.3.0) - rspec-support (3.3.0) - ruby_parser (3.7.0) - sexp_processor (~> 4.1) - safe_yaml (1.0.4) - sass (3.4.16) - sass-rails (5.0.3) - railties (>= 4.0.0, < 5.0) - sass (~> 3.1) - sprockets (>= 2.8, < 4.0) - sprockets-rails (>= 2.0, < 4.0) - tilt (~> 1.1) - sexp_processor (4.6.0) - shoulda-matchers (2.8.0) - activesupport (>= 3.0.0) - simple_form (3.1.0) - actionpack (~> 4.0) - activemodel (~> 4.0) - simplecov (0.10.0) - docile (~> 1.1.0) - json (~> 1.8) - simplecov-html (~> 0.10.0) - simplecov-html (0.10.0) - sprockets (3.3.4) - rack (~> 1.0) - sprockets-rails (2.3.3) - actionpack (>= 3.0) - activesupport (>= 3.0) - sprockets (>= 2.8, < 4.0) - sqlite3 (1.3.10) - subelsky_power_tools (1.4.0) - table_for_collection (1.0.7) - actionpack - thor (0.19.1) - thread_safe (0.3.5) - tilt (1.4.1) - tzinfo (1.2.2) - thread_safe (~> 0.1) - uglifier (2.7.1) - execjs (>= 0.3.0) - json (>= 1.8.0) - unicorn (4.9.0) - kgio (~> 2.6) - rack - raindrops (~> 0.7) - xpath (2.0.0) - nokogiri (~> 1.3) - -PLATFORMS - ruby - -DEPENDENCIES - annotate - bootstrap-sass - capybara - codeclimate-test-reporter - coffee-rails - database_cleaner - dim - domino - dotenv-rails - exception_notification - factory_girl_rails - filepicker-rails - foreigner - foreman - haml-rails - jquery-rails - launchy - pg - rails (= 4.2.4) - rails_12factor - rails_admin - rspec-instafail - rspec-rails - sass-rails - shoulda-matchers - simple_form - sqlite3 - subelsky_power_tools - table_for_collection - uglifier - unicorn - -BUNDLED WITH - 1.10.6 diff --git a/app/assets/javascripts/events.js b/app/assets/javascripts/events.js new file mode 100644 index 0000000..dee720f --- /dev/null +++ b/app/assets/javascripts/events.js @@ -0,0 +1,2 @@ +// Place all the behaviors and hooks related to the matching controller here. +// All this logic will automatically be available in application.js. diff --git a/app/assets/stylesheets/events.sass b/app/assets/stylesheets/events.sass new file mode 100644 index 0000000..3a2033a --- /dev/null +++ b/app/assets/stylesheets/events.sass @@ -0,0 +1,3 @@ +// Place all the styles related to the Events controller here. +// They will automatically be included in application.css. +// You can use Sass here: http://sass-lang.com/ diff --git a/app/assets/stylesheets/scaffolds.sass b/app/assets/stylesheets/scaffolds.sass new file mode 100644 index 0000000..57e885d --- /dev/null +++ b/app/assets/stylesheets/scaffolds.sass @@ -0,0 +1,60 @@ +body + background-color: #fff + color: #333 + font-family: verdana, arial, helvetica, sans-serif + font-size: 13px + line-height: 18px + +p, ol, ul, td + font-family: verdana, arial, helvetica, sans-serif + font-size: 13px + line-height: 18px + +pre + background-color: #eee + padding: 10px + font-size: 11px + +a + color: #000 + + &:visited + color: #666 + + &:hover + color: #fff + background-color: #000 + +div + &.field, &.actions + margin-bottom: 10px + +#notice + color: green + +.field_with_errors + padding: 2px + background-color: red + display: table + +#error_explanation + width: 450px + border: 2px solid red + padding: 7px + padding-bottom: 0 + margin-bottom: 20px + background-color: #f0f0f0 + + h2 + text-align: left + font-weight: bold + padding: 5px 5px 5px 15px + font-size: 12px + margin: -7px + margin-bottom: 0px + background-color: #c00 + color: #fff + + ul li + font-size: 12px + list-style: square diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb new file mode 100644 index 0000000..75acbc6 --- /dev/null +++ b/app/controllers/events_controller.rb @@ -0,0 +1,60 @@ +class EventsController < ApplicationController + before_action :set_event, only: [:show, :edit, :update, :destroy] + + # GET /events + def index + @events = Event.all + Event.scoped + end + + # GET /events/1 + def show + end + + # GET /events/new + def new + @event = Event.new + end + + # GET /events/1/edit + def edit + @title = "Edit #{event.title}" + end + + # POST /events + def create + @event = Event.new(event_params) + + if @event.save + redirect_to @event, notice: 'Event was successfully created.' + else + render :new + end + end + + # PATCH/PUT /events/1 + def update + if @event.update(event_params) + redirect_to @event, notice: 'Event was successfully updated.' + else + render :edit + end + end + + # DELETE /events/1 + def destroy + @event.destroy + redirect_to events_url, notice: 'Event was successfully destroyed.' + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_event + @event = Event.find(params[:id]) + end + + # Only allow a trusted parameter "white list" through. + def event_params + params.require(:event).permit(:title, :time, :tickets_url) + end +end diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb new file mode 100644 index 0000000..56b5cb9 --- /dev/null +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -0,0 +1,50 @@ +class OmniauthCallbacksController < Devise::OmniauthCallbacksController + def twitter + social_callback("twitter") + return + end + + def google + social_callback("google") + return + end + + def social_callback(provider) + auth_det = request.env["omniauth.auth"] + + # if both nickname and email are absent + if auth_det.info.nickname.blank? and auth_det.info.email.blank? + redirect_to root_path + return + end + + # Twitter does not return email so would use nickname instead + if auth_det.info.nickname.present? and !Admin.exists?(:nickname => auth_det.info.nickname) + puts "Nickname not found" + redirect_to root_path + return + end + + if auth_det.info.email.present? and !Admin.exists?(:email => auth_det.info.email) + puts "User not allowed" + redirect_to root_path + return + end + + if auth_det.info.nickname.present? and !Admin.exists?(:nickname => auth_det.info.nickname) and uth_det.info.email.present? and !Admin.exists?(:email => auth_det.info.email) + puts "Email and nickname not allowed" + redirect_to root_path + return + end + + @admin = Admin.do_generic_oauth(auth_det, current_admin, provider) + if @admin.persisted? + flash[:notice] = I18n.t "devise.omniauth_callbacks.success" + sign_in_and_redirect @admin, :event => :authentication + else + session["devise.twitter_uid"] = request.env["omniauth.auth"] + redirect_to new_admin_session_path + end + end + +end diff --git a/app/helpers/events_helper.rb b/app/helpers/events_helper.rb new file mode 100644 index 0000000..8a9a878 --- /dev/null +++ b/app/helpers/events_helper.rb @@ -0,0 +1,2 @@ +module EventsHelper +end diff --git a/app/models/admin.rb b/app/models/admin.rb new file mode 100644 index 0000000..c5e39e0 --- /dev/null +++ b/app/models/admin.rb @@ -0,0 +1,29 @@ +class Admin < ActiveRecord::Base + devise :database_authenticatable, :omniauthable, + :recoverable, :rememberable, :trackable, + :validatable + + def self.do_generic_oauth(auth_hash, signed_in_resource = nil, provider) + admin = Admin.where(:provider => auth_hash.provider, :uid => auth_hash.uid ).first + + return admin if admin + + # twitter's email is nil + if provider == "twitter" + email_provider = auth_hash.uid + "@twitter.com" + else + email_provider = auth_hash.info.email + end + registered_admin = Admin.where(:email => email_provider).first + return registered_admin if registered_admin + # create user + admin = Admin.create!(name: auth_hash.info.name, + provider:auth_hash.provider, + email: email_provider, + uid: auth_hash.uid , + password: Devise.friendly_token[0,20], + nickname:auth_hash.info.nickname + ) + end +end + diff --git a/app/models/event.rb b/app/models/event.rb new file mode 100644 index 0000000..6f503dc --- /dev/null +++ b/app/models/event.rb @@ -0,0 +1,16 @@ +class Event < ActiveRecord::Base + has_many :proposal + + + validates_presence_of :title, allow_blank: false + validates :title,length: { maximum: 254 } + + rails_admin do + #show only these fields for the event + list do + field :title + field :time + field :tickets_url + end + end +end diff --git a/app/models/proposal.rb b/app/models/proposal.rb index 12748ac..8c558b2 100644 --- a/app/models/proposal.rb +++ b/app/models/proposal.rb @@ -22,6 +22,8 @@ require "digest/sha2" class Proposal < ActiveRecord::Base + belongs_to :event + validates_presence_of :title, :description, :email, :bio, :speaker_name, allow_blank: false validates :description, length: { maximum: 1000 } validates :bio, length: { maximum: 100 } diff --git a/app/views/events/_form.html.haml b/app/views/events/_form.html.haml new file mode 100644 index 0000000..5137317 --- /dev/null +++ b/app/views/events/_form.html.haml @@ -0,0 +1,10 @@ += simple_form_for(@event) do |f| + = f.error_notification + + .form-inputs + = f.input :title + = f.input :time + = f.input :tickets_url + + .form-actions + = f.button :submit diff --git a/app/views/events/edit.html.haml b/app/views/events/edit.html.haml new file mode 100644 index 0000000..5828e7a --- /dev/null +++ b/app/views/events/edit.html.haml @@ -0,0 +1,7 @@ +%h1 Editing event + += render 'form' + += link_to 'Show', @event +\| += link_to 'Back', events_path diff --git a/app/views/events/index.html.haml b/app/views/events/index.html.haml new file mode 100644 index 0000000..3de97ed --- /dev/null +++ b/app/views/events/index.html.haml @@ -0,0 +1,25 @@ +%h1 Listing events + +%table + %thead + %tr + %th Title + %th Time + %th Tickets + %th + %th + %th + + %tbody + - @events.each do |event| + %tr + %td= event.title + %td= event.time + %td= event.tickets_url + %td= link_to 'Show', event + %td= link_to 'Edit', edit_event_path(event) + %td= link_to 'Destroy', event, :method => :delete, :data => { :confirm => 'Are you sure?' } + +%br + += link_to 'New Event', new_event_path diff --git a/app/views/events/new.html.haml b/app/views/events/new.html.haml new file mode 100644 index 0000000..6e0cccf --- /dev/null +++ b/app/views/events/new.html.haml @@ -0,0 +1,5 @@ +%h1 New event + += render 'form' + += link_to 'Back', events_path diff --git a/app/views/events/show.html.haml b/app/views/events/show.html.haml new file mode 100644 index 0000000..ad7af92 --- /dev/null +++ b/app/views/events/show.html.haml @@ -0,0 +1,15 @@ +%p#notice= notice + +%p + %b Title: + = @event.title +%p + %b Time: + = @event.time +%p + %b Tickets: + = @event.tickets_url + += link_to 'Edit', edit_event_path(@event) +\| += link_to 'Back', events_path diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 0000000..69d882c --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,270 @@ +# 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| + # Key and secret for Twitter and Google + config.omniauth :twitter, ENV.fetch("TWITTER_KEY"), ENV.fetch("TWITTER_SECRET") + config.omniauth :google_oauth2, ENV.fetch("GOOGLE_ID"), ENV.fetch("GOOGLE_SECRET"), { access_type: "offline", approval_prompt: "" , skip_jwt: true, name: "google"} + + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = '7ba6db31bd1dc7f05d10903398812b5f83c7a58e7071c7e50b8fbf325ec28ce9b6f62c940eaf80d311dda68c9c6abaaceaa5afe6aa7b117369e03bcdadb25acd' + + # ==> 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 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 = [:database]` will + # enable it only for database authentication. The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code 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 + # particular strategies by setting this option. + # 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] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option at your own risk. + # config.clean_up_csrf_token_on_authentication = true + + # ==> 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. Note that, for bcrypt (the default + # encryptor), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). + config.stretches = Rails.env.test? ? 1 : 10 + + # Setup a pepper to generate the encrypted password. + # config.pepper = '6d9164087ccc5c6e7732dde033c9b5504b37ee8e557045570ab87303a3ffc15f61bb09cfbd4fcd089475064123c6e7f31465eea529602066c4cb0b2ffcf78377' + + # Send a notification email when the user's password is changed + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the third day. Default is 0.days, meaning + # the user cannot access the website without confirming their account. + # config.allow_unconfirmed_access_for = 2.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can't be confirmed with the token any more. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.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 + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # 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. + config.password_length = 8..72 + + # Email regex used to validate email formats. It simply asserts that + # 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 + + # ==> 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 + + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + + # ==> 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 + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true + + # ==> 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). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> 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 diff --git a/config/initializers/rails_admin.rb b/config/initializers/rails_admin.rb index 0da160f..1dcefed 100644 --- a/config/initializers/rails_admin.rb +++ b/config/initializers/rails_admin.rb @@ -1,8 +1,33 @@ # RailsAdmin config file. Generated on January 22, 2013 16:54 # See github.com/sferik/rails_admin for more informations +require Rails.root.join('lib', 'rails_admin_loadevent.rb') + RailsAdmin.config do |config| + config.actions do + # root actions + dashboard + # collection actions + index + new + export + history_index + bulk_delete + # member actions + show + edit + delete + history_show + show_in_app + + loadevent do + visible do + bindings[:abstract_model].model == Event + end + end + end + ################ Global configuration ################ @@ -14,11 +39,15 @@ # RailsAdmin may need a way to know who the current user is] #config.current_user_method { current_user } # auto-generated +# config.authenticate_with do +# authenticate_or_request_with_http_basic do |username, password| +# username == ENV.fetch("ADMIN_USERNAME") && password == ENV.fetch("ADMIN_PASSWORD") +# end +# end config.authenticate_with do - authenticate_or_request_with_http_basic do |username, password| - username == ENV.fetch("ADMIN_USERNAME") && password == ENV.fetch("ADMIN_PASSWORD") - end + warden.authenticate! scope: :admin end + config.current_user_method(&:current_admin) # Other config stuff should go here # If you want to track changes on your models: @@ -37,7 +66,7 @@ # config.excluded_models = ['Proposal'] # Include specific models (exclude the others): - config.included_models = ['Proposal'] + config.included_models = ['Proposal', 'Event'] # Label methods for model instances: # config.label_methods << :description # Default is [:name, :title] diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml index 4572f2e..9c66493 100644 --- a/config/locales/devise.en.yml +++ b/config/locales/devise.en.yml @@ -1,60 +1,62 @@ # Additional translations at https://github.com/plataformatec/devise/wiki/I18n en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your email address before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock instructions" + password_change: + subject: "Password Changed" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated" + passwords: + 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." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + 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." + updated: "Your password has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + 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." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." + updated: "Your account has been updated successfully." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." errors: messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" 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:" - confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" - - 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.' - not_found_in_database: 'Invalid email or password.' - 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/rails_admin.en.yml b/config/locales/rails_admin.en.yml new file mode 100644 index 0000000..56d457c --- /dev/null +++ b/config/locales/rails_admin.en.yml @@ -0,0 +1,155 @@ +en: + admin: + loadevent: "load" + js: + true: True + false: False + is_present: Is present + is_blank: Is blank + date: Date ... + between_and_: Between ... and ... + today: Today + yesterday: Yesterday + this_week: This week + last_week: Last week + number: Number ... + contains: Contains + is_exactly: Is exactly + starts_with: Starts with + ends_with: Ends with + too_many_objects: "Too many objects, use search box above" + no_objects: "No objects found" + loading: "Loading..." + toggle_navigation: Toggle navigation + home: + name: "Home" + pagination: + previous: "« Prev" + next: "Next »" + truncate: "…" + misc: + search: "Search" + filter: "Filter" + refresh: "Refresh" + show_all: "Show all" + add_filter: "Add filter" + bulk_menu_title: "Selected items" + remove: "Remove" + add_new: "Add new" + chosen: "Chosen %{name}" + chose_all: "Choose all" + clear_all: "Clear all" + up: "Up" + down: "Down" + navigation: "Navigation" + navigation_static_label: "Links" + log_out: "Log out" + ago: "ago" + flash: + successful: "%{name} successfully %{action}" + error: "%{name} failed to be %{action}" + noaction: "No actions were taken" + model_not_found: "Model '%{model}' could not be found" + object_not_found: "%{model} with id '%{id}' could not be found" + table_headers: + model_name: "Model name" + last_created: "Last created" + records: "Records" + username: "User" + changes: "Changes" + created_at: "Date/Time" + item: "Item" + message: "Message" + actions: + dashboard: + title: "Site Administration" + menu: "Dashboard" + breadcrumb: "Dashboard" + index: + title: "List of %{model_label_plural}" + menu: "List" + breadcrumb: "%{model_label_plural}" + show: + title: "Details for %{model_label} '%{object_label}'" + menu: "Show" + breadcrumb: "%{object_label}" + show_in_app: + menu: "Show in app" + new: + title: "New %{model_label}" + menu: "Add new" + breadcrumb: "New" + link: "Add a new %{model_label}" + done: "created" + edit: + title: "Edit %{model_label} '%{object_label}'" + menu: "Edit" + breadcrumb: "Edit" + link: "Edit this %{model_label}" + done: "updated" + delete: + title: "Delete %{model_label} '%{object_label}'" + menu: "Delete" + breadcrumb: "Delete" + link: "Delete '%{object_label}'" + done: "deleted" + bulk_delete: + title: "Delete %{model_label_plural}" + menu: "Multiple delete" + breadcrumb: "Multiple delete" + bulk_link: "Delete selected %{model_label_plural}" + export: + title: "Export %{model_label_plural}" + menu: "Export" + breadcrumb: "Export" + link: "Export found %{model_label_plural}" + bulk_link: "Export selected %{model_label_plural}" + done: "exported" + history_index: + title: "History for %{model_label_plural}" + menu: "History" + breadcrumb: "History" + history_show: + title: "History for %{model_label} '%{object_label}'" + menu: "History" + breadcrumb: "History" + loadevent: + title: "load Event for %{model_label} '%{object_label}%'" + menu: "Load From Proposal DB" + breadcrumb: "load" + form: + cancel: "Cancel" + basic_info: "Basic info" + required: "Required" + optional: "Optional" + one_char: "character" + char_length_up_to: "length up to" + char_length_of: "length of" + save: "Save" + save_and_add_another: "Save and add another" + save_and_edit: "Save and edit" + all_of_the_following_related_items_will_be_deleted: "? The following related items may be deleted or orphaned:" + are_you_sure_you_want_to_delete_the_object: "Are you sure you want to delete this %{model_name}" + confirmation: "Yes, I'm sure" + bulk_delete: "The following objects will be deleted, which may delete or orphan some of their related dependencies:" + new_model: "%{name} (new)" + export: + confirmation: "Export to %{name}" + select: "Select fields to export" + select_all_fields: "Select All Fields" + fields_from: "Fields from %{name}" + fields_from_associated: "Fields from associated %{name}" + display: "Display %{name}: %{type}" + options_for: "Options for %{name}" + empty_value_for_associated_objects: "" + click_to_reverse_selection: 'Click to reverse selection' + csv: + header_for_root_methods: "%{name}" # 'model' is available + header_for_association_methods: "%{name} [%{association}]" + encoding_to: "Encode to" + encoding_to_help: "Choose output encoding. Leave empty to let current input encoding untouched: (%{name})" + skip_header: "No header" + skip_header_help: "Do not output a header (no fields description)" + default_col_sep: "," + col_sep: "Column separator" + col_sep_help: "Leave blank for default ('%{value}')" # value is default_col_sep diff --git a/config/routes.rb b/config/routes.rb index 709b801..47f711b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,8 @@ Ignitespeak::Application.routes.draw do + # for authentication using social network + devise_for :admins, :controllers => { omniauth_callbacks: 'omniauth_callbacks' } + + resources :events mount RailsAdmin::Engine => '/admin', :as => 'rails_admin' resources :proposals do diff --git a/db/migrate/20160211082126_create_events.rb b/db/migrate/20160211082126_create_events.rb new file mode 100644 index 0000000..de5e469 --- /dev/null +++ b/db/migrate/20160211082126_create_events.rb @@ -0,0 +1,11 @@ +class CreateEvents < ActiveRecord::Migration + def change + create_table :events do |t| + t.string :title + t.datetime :time + t.string :tickets + + t.timestamps null: false + end + end +end diff --git a/db/migrate/20160229144015_devise_create_admins.rb b/db/migrate/20160229144015_devise_create_admins.rb new file mode 100644 index 0000000..13389f1 --- /dev/null +++ b/db/migrate/20160229144015_devise_create_admins.rb @@ -0,0 +1,43 @@ +class DeviseCreateAdmins < ActiveRecord::Migration + def change + create_table(:admins) do |t| + ## Database authenticatable + t.string :email, null: false, default: "" + t.string :encrypted_password, null: false, default: "" + t.string :name, 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, null: false + 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, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + + t.timestamps null: false + end + + add_index :admins, :email, unique: true + add_index :admins, :reset_password_token, unique: true + # add_index :admins, :confirmation_token, unique: true + # add_index :admins, :unlock_token, unique: true + end +end diff --git a/db/migrate/20160229155901_add_columns_to_admins.rb b/db/migrate/20160229155901_add_columns_to_admins.rb new file mode 100644 index 0000000..197ab8b --- /dev/null +++ b/db/migrate/20160229155901_add_columns_to_admins.rb @@ -0,0 +1,7 @@ +class AddColumnsToAdmins < ActiveRecord::Migration + def change + add_column :admins, :provider, :string + add_column :admins, :uid, :string +# add_column :admins, :name, :string + end +end diff --git a/db/migrate/20160302164052_add_foreign_reference_to_events.rb b/db/migrate/20160302164052_add_foreign_reference_to_events.rb new file mode 100644 index 0000000..1b9a420 --- /dev/null +++ b/db/migrate/20160302164052_add_foreign_reference_to_events.rb @@ -0,0 +1,6 @@ +class AddForeignReferenceToEvents < ActiveRecord::Migration + def change + add_reference :proposals, :event, index: true + add_foreign_key :proposals, :event, on_delete: :cascade + end +end diff --git a/db/migrate/20160321050020_add_nickname_to_admins.rb b/db/migrate/20160321050020_add_nickname_to_admins.rb new file mode 100644 index 0000000..71d2465 --- /dev/null +++ b/db/migrate/20160321050020_add_nickname_to_admins.rb @@ -0,0 +1,5 @@ +class AddNicknameToAdmins < ActiveRecord::Migration + def change + add_column :admins, :nickname, :string + end +end diff --git a/db/seeds.rb b/db/seeds.rb index fe2a543..8839c4d 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -1,5 +1,6 @@ require "factory_girl_rails" +Admin.create! email: 'test@gmail.com', password: '123456789' FactoryGirl.create(:proposal,:selected) FactoryGirl.create(:proposal,:selected,title: "Another Awesome Talk",speaker_name: "Sarah Smith") FactoryGirl.create(:proposal,:archived,title: "This Talk Didn't Get Picked",speaker_name: "David Zhou") diff --git a/lib/rails_admin_loadevent.rb b/lib/rails_admin_loadevent.rb new file mode 100644 index 0000000..6ea244b --- /dev/null +++ b/lib/rails_admin_loadevent.rb @@ -0,0 +1,50 @@ +require 'rails_admin/config/actions' +require 'rails_admin/config/actions/base' + +module RailsAdminLoadevent +end + +module RailsAdmin + module Config + module Actions + class Loadevent < RailsAdmin::Config::Actions::Base + RailsAdmin::Config::Actions.register(self) + register_instance_option :collection do + true + end + register_instance_option :link_icon do + 'icon-fire' + end + #disable jquery pjax + register_instance_option :pjax? do + false + end + register_instance_option :controller do + Proc.new do + # find all the selected and archived records + allSelectedEvents = Proposal.where(selected: "t", archived: "f" ).select("title", "id") + # if records nil do no contnue + unless allSelectedEvents.nil? + allSelectedEvents.each { |eachEvent| + #if records already exist + unless Event.exists?(eachEvent.attributes) + tempAttributes = eachEvent.attributes + tempAttributes[:time] = "" + puts "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1" + tempAttributes.each do |key, array| + puts key + end + recordEvent = Event.create(tempAttributes) + if recordEvent.valid? + recordEvent.save + end + end + } + end + redirect_to back_or_index + end + end + end + end + end +end diff --git a/lib/tasks/adminusers.rake b/lib/tasks/adminusers.rake new file mode 100644 index 0000000..0f9b4ad --- /dev/null +++ b/lib/tasks/adminusers.rake @@ -0,0 +1,50 @@ +include Rails.application.routes.url_helpers + +namespace :admin do + task :adduser => :environment do + puts "Please choose one of the option below (1 or 2) to allow the authenticated app user to be an admin:" + puts " 1 Twitter" + puts " 2 Google" + option = STDIN.gets + + if option.strip == "1" + puts "=================================================================================================" + + puts "Twitter nickname should be exactly as the Twitter app account you want to authorize." + puts "Enter Twitter nickname:" + nickname = STDIN.gets + nickname = nickname.strip + provider = "Twitter" + uid = "Manual" + email = nickname + "@twitter.com" + elsif option.strip == "2" + puts "=================================================================================================" + + puts "Google nickname should be exactly as the Google app account you want to authorize." + puts "Enter Google email:" + + email = STDIN.gets + email = email.strip + nickname = "" + uid = "Manual" + provider = "Google" + else + return + end + + + puts "Enter a secure password:" + password = STDIN.gets + password = password.strip + puts "=================================================================================================" + puts "........................Creating an admin user for an authenticated user........................." + + if (email.present? or nickname.present?) and password.present? + if Admin.create!(:uid => uid, :email => email, :nickname => nickname, :password => password, :provider => provider) + puts "Admin user created!" + else + puts "Failed to create user" + end + end + end +end diff --git a/spec/controllers/events_controller_spec.rb b/spec/controllers/events_controller_spec.rb new file mode 100644 index 0000000..68f3712 --- /dev/null +++ b/spec/controllers/events_controller_spec.rb @@ -0,0 +1,164 @@ +require 'rails_helper' + +# This spec was generated by rspec-rails when you ran the scaffold generator. +# It demonstrates how one might use RSpec to specify the controller code that +# was generated by Rails when you ran the scaffold generator. +# +# It assumes that the implementation code is generated by the rails scaffold +# generator. If you are using any extension libraries to generate different +# controller code, this generated spec may or may not pass. +# +# It only uses APIs available in rails and/or rspec-rails. There are a number +# of tools you can use to make these specs even more expressive, but we're +# sticking to rails and rspec-rails APIs to keep things simple and stable. +# +# Compared to earlier versions of this generator, there is very limited use of +# stubs and message expectations in this spec. Stubs are only used when there +# is no simpler way to get a handle on the object needed for the example. +# Message expectations are only used when there is no simpler way to specify +# that an instance is receiving a specific message. + +RSpec.describe EventsController, type: :controller do + describe "GET #loadevent" do + it "redirects to loadevent" do + post :create, {:event => valid_attributes}, valid_session + expect(response).to redirect_to(Event.last) + end + end + + # This should return the minimal set of attributes required to create a valid + # Event. As you add validations to Event, be sure to + # adjust the attributes here as well. + let(:valid_attributes) { + skip("Add a hash of attributes valid for your model") + } + + let(:invalid_attributes) { + skip("Add a hash of attributes invalid for your model") + } + + # This should return the minimal set of values that should be in the session + # in order to pass any filters (e.g. authentication) defined in + # EventsController. Be sure to keep this updated too. + let(:valid_session) { {} } + + describe "GET #index" do + it "assigns all events as @events" do + event = Event.create! valid_attributes + get :index, {}, valid_session + expect(assigns(:events)).to eq([event]) + end + end + + describe "GET #show" do + it "assigns the requested event as @event" do + event = Event.create! valid_attributes + get :show, {:id => event.to_param}, valid_session + expect(assigns(:event)).to eq(event) + end + end + + describe "GET #new" do + it "assigns a new event as @event" do + get :new, {}, valid_session + expect(assigns(:event)).to be_a_new(Event) + end + end + + describe "GET #edit" do + it "assigns the requested event as @event" do + event = Event.create! valid_attributes + get :edit, {:id => event.to_param}, valid_session + expect(assigns(:event)).to eq(event) + end + end + + describe "POST #create" do + context "with valid params" do + it "creates a new Event" do + expect { + post :create, {:event => valid_attributes}, valid_session + }.to change(Event, :count).by(1) + end + + it "assigns a newly created event as @event" do + post :create, {:event => valid_attributes}, valid_session + expect(assigns(:event)).to be_a(Event) + expect(assigns(:event)).to be_persisted + end + + it "redirects to the created event" do + post :create, {:event => valid_attributes}, valid_session + expect(response).to redirect_to(Event.last) + end + end + + context "with invalid params" do + it "assigns a newly created but unsaved event as @event" do + post :create, {:event => invalid_attributes}, valid_session + expect(assigns(:event)).to be_a_new(Event) + end + + it "re-renders the 'new' template" do + post :create, {:event => invalid_attributes}, valid_session + expect(response).to render_template("new") + end + end + end + + describe "PUT #update" do + context "with valid params" do + let(:new_attributes) { + skip("Add a hash of attributes valid for your model") + } + + it "updates the requested event" do + event = Event.create! valid_attributes + put :update, {:id => event.to_param, :event => new_attributes}, valid_session + event.reload + skip("Add assertions for updated state") + end + + it "assigns the requested event as @event" do + event = Event.create! valid_attributes + put :update, {:id => event.to_param, :event => valid_attributes}, valid_session + expect(assigns(:event)).to eq(event) + end + + it "redirects to the event" do + event = Event.create! valid_attributes + put :update, {:id => event.to_param, :event => valid_attributes}, valid_session + expect(response).to redirect_to(event) + end + end + + context "with invalid params" do + it "assigns the event as @event" do + event = Event.create! valid_attributes + put :update, {:id => event.to_param, :event => invalid_attributes}, valid_session + expect(assigns(:event)).to eq(event) + end + + it "re-renders the 'edit' template" do + event = Event.create! valid_attributes + put :update, {:id => event.to_param, :event => invalid_attributes}, valid_session + expect(response).to render_template("edit") + end + end + end + + describe "DELETE #destroy" do + it "destroys the requested event" do + event = Event.create! valid_attributes + expect { + delete :destroy, {:id => event.to_param}, valid_session + }.to change(Event, :count).by(-1) + end + + it "redirects to the events list" do + event = Event.create! valid_attributes + delete :destroy, {:id => event.to_param}, valid_session + expect(response).to redirect_to(events_url) + end + end +end diff --git a/spec/controllers/events_integration_spec.rb b/spec/controllers/events_integration_spec.rb new file mode 100644 index 0000000..acbf5fa --- /dev/null +++ b/spec/controllers/events_integration_spec.rb @@ -0,0 +1,22 @@ +require 'rails_helper' + +RSpec.describe EventsController, type: :controller do + context "with new title being filled and created" do + it "the count should increase by one" do + expect { + post :create, :event => {:title => "testing" } + }.to change {Event.count}.by(1) + end + end + + context "with not a title field being filled and created" do + it "the count should remain the same" do + expect { + post :create, :event => {:tickets_url => "hello/world" } + }.to_not change {Event.count} + end + end + + +end + diff --git a/spec/factories/admin.rb b/spec/factories/admin.rb new file mode 100644 index 0000000..f23e000 --- /dev/null +++ b/spec/factories/admin.rb @@ -0,0 +1,19 @@ +FactoryGirl.define do + factory :admin do + nickname "A nick" + email "nick@email.com" + password "123456789" + provider "NONE" + uid "Test" + end + + factory :admin2 do + nickname "A" + email "a@email.com" + password "qwrt63876932179" + provider "NONE" + uid "Test" + end + +end + diff --git a/spec/features/authentication_to_admin.rb b/spec/features/authentication_to_admin.rb new file mode 100644 index 0000000..a9710ca --- /dev/null +++ b/spec/features/authentication_to_admin.rb @@ -0,0 +1,17 @@ +require "spec_helper" +require "rails_helper" +require 'support/basic_authentication' + +describe "test authentication", :type => :feature do + describe "with authentication on", :js => true, :type => :controller do + include_context 'basic authentication' + it "access the admin page" do + # go to the admin page + visit rails_admin.dashboard_path + # login to the admin page + http_basic_authentication + # verify if the admin page has been reached + expect(current_path).to eq rails_admin.dashboard_path + end + end +end diff --git a/spec/features/click_spec.rb b/spec/features/click_spec.rb new file mode 100644 index 0000000..7f013e7 --- /dev/null +++ b/spec/features/click_spec.rb @@ -0,0 +1,62 @@ +require "spec_helper" +require "rails_helper" + +require 'support/basic_authentication' + +describe "test event model", :type => :feature do + include_context 'basic authentication' + context "with authentication on", :js => true, :type => :controller do + before(:each) do + # always login before accessing the admin page + http_basic_authentication + end + + it "access the admin page" do + visit rails_admin.dashboard_path + expect(current_path).to eq rails_admin.dashboard_path + end + end + + context "with admin reached", :js => true, :type => :controller do + before(:each) do + # always login before accessing the admin page + http_basic_authentication + end + + it "should have event" do + visit rails_admin.dashboard_path + page.find('[data-model=event] a').click + # if we are in the event model then should have Events somewhere + expect(page.find('[data-model=event]')).to have_content('Events') + end + end + + context "with admin reached", :js => true, :type => :controller do + before(:each) do + # always login before accessing the admin page + http_basic_authentication + end + it "should have the load event button" do + visit rails_admin.dashboard_path + page.find('[data-model=event] a').click + # should have the Load button in the events tab + # Either + page.find(:xpath,"//*[text()='#{"Load From Proposal DB"}']") + # Or + page.find(:xpath,"//span[text()='Load From Proposal DB']") + end + end + + context "with an empty proposal database", :js => true, :type => :controller do + before(:each) do + # always login before accessing the admin page + http_basic_authentication + end + it "should have an empty events database after the the load button is pressed" do + visit rails_admin.dashboard_path + page.find('[data-model=event] a').click + page.find(:xpath,"//*[text()='#{"Load From Proposal DB"}']").click + expect(Event.count).to be == 0 + end + end +end diff --git a/spec/features/devise_spec.rb b/spec/features/devise_spec.rb new file mode 100644 index 0000000..ff536c9 --- /dev/null +++ b/spec/features/devise_spec.rb @@ -0,0 +1,32 @@ +require "spec_helper" +require 'support/basic_authentication' +require 'database_cleaner' +include Warden::Test::Helpers +Warden.test_mode! + +describe "omniauth authentication", :type => :feature do + + context "with an invalid email address and password", :js => true, :type => :controller do + it "should be redirected to sign in page" do + visit rails_admin.dashboard_path + page.find(:xpath,"//*[text()='#{"Log in"}']").click + expect(page).to have_content 'Forgot your password' + end + end + + context "with a valid email address and password", :js => true, :type => :controller do + it "should be redirected to admin page" do + # ad = Admin.create!(:nickname => "A nick" ,:email => "nick@email.com", :password => "123456789") + # ad.save! + + admin = FactoryGirl.create(:admin) + login_as(admin, :scope => :admin) + + visit rails_admin.dashboard_path + + expect(page).to have_content 'Site Administration' + + end + end + +end diff --git a/spec/features/omniauth_spec.rb b/spec/features/omniauth_spec.rb new file mode 100644 index 0000000..7e12b67 --- /dev/null +++ b/spec/features/omniauth_spec.rb @@ -0,0 +1,82 @@ +require "spec_helper" +require 'support/basic_authentication' + +require 'database_cleaner' + + +describe "omniauth authentication", :type => :feature do + describe "with authentication on", :js => true, :type => :controller do + it "twitter sign in button should get to the admin page", :strategy => :truncation do + # get the omniauth hash + mock_twitter_authorized + + # create an admin user + ad = Admin.create!(:uid => "Test", :provider => "Twitter", :nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") + ad.save! + + visit rails_admin.dashboard_path + click_link "Sign in with Twitter" + expect(page).to have_content 'Site Administration' + end + + it "twitter sign in button should redirect to proposal form", :strategy => :truncation do + # get the omniauth hash + mock_twitter_unauthorized + + # create an admin user + ad = Admin.create!(:uid => "Test", :provider => "Twitter", :nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") + ad.save! + + visit rails_admin.dashboard_path + click_link "Sign in with Twitter" + expect(page).to have_content 'Your email address' + end + + it "twitter sign in button should fail if database is empty" do + # get the omniauth hash + mock_google_unauthorized + + visit rails_admin.dashboard_path + click_link "Sign in with Twitter" + expect(page).to have_content 'Your email address' + end + + it "google sign in button should get to the admin page" do + # get the omniauth hash + mock_google_authorized + + ad = Admin.create!(:uid => "Test", :provider => "Google", :nickname => "", :email =>"alas@gmail.com", :password => "1234567890") + ad.save! + + visit rails_admin.dashboard_path + click_link "Sign in with Google" + expect(page).to have_content 'Site Administration' + end + + + it "google sign in button should redirect to proposal form i.e. fail if email is wrong" do + # get the omniauth hash + mock_google_unauthorized + + ad = Admin.create!(:uid => "Test", :provider => "Google", :nickname => "Alas", :email =>"alas@gmail.com", :password => "1234567890") + ad.save! + + visit rails_admin.dashboard_path + click_link "Sign in with Google" + expect(page).to have_content 'Your email address' + end + + it "google sign in button should fail if database is empty" do + # get the omniauth hash + mock_google_unauthorized + + visit rails_admin.dashboard_path + click_link "Sign in with Google" + expect(page).to have_content 'Your email address' + end + + + + end + +end diff --git a/spec/models/admin_spec.rb b/spec/models/admin_spec.rb new file mode 100644 index 0000000..e05072b --- /dev/null +++ b/spec/models/admin_spec.rb @@ -0,0 +1,32 @@ +require "rails_helper" + +# == Schema Information +# +# Table name: admins +# +# +# t.string "email", default: "", null: false +# t.string "encrypted_password", default: "", null: false +# t.string "name", 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, null: false +# 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 +# t.string "provider" +# t.string "uid" +# t.string "nickname" +# + +RSpec.describe Admin do + describe "createadmins" do + it "should return an admin user" do + adm = create(:admin) + end + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..75f3104 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,68 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../../config/environment', __FILE__) +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'spec_helper' +require 'rspec/rails' +require 'database_cleaner' + +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } + +# Checks for pending migrations before tests are run. +# If you are not using ActiveRecord, you can remove this line. +ActiveRecord::Migration.maintain_test_schema! + +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = false + + config.use_transactional_fixtures = false + + config.before(:suite) do + DatabaseCleaner.strategy = :truncation + end + + config.before(:each) do + DatabaseCleaner.start + end + + config.after(:each) do + DatabaseCleaner.clean + end + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, :type => :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! +end diff --git a/spec/routing/events_routing_spec.rb b/spec/routing/events_routing_spec.rb new file mode 100644 index 0000000..4bb4760 --- /dev/null +++ b/spec/routing/events_routing_spec.rb @@ -0,0 +1,39 @@ +require "rails_helper" + +RSpec.describe EventsController, type: :routing do + describe "routing" do + + it "routes to #index" do + expect(:get => "/events").to route_to("events#index") + end + + it "routes to #new" do + expect(:get => "/events/new").to route_to("events#new") + end + + it "routes to #show" do + expect(:get => "/events/1").to route_to("events#show", :id => "1") + end + + it "routes to #edit" do + expect(:get => "/events/1/edit").to route_to("events#edit", :id => "1") + end + + it "routes to #create" do + expect(:post => "/events").to route_to("events#create") + end + + it "routes to #update via PUT" do + expect(:put => "/events/1").to route_to("events#update", :id => "1") + end + + it "routes to #update via PATCH" do + expect(:patch => "/events/1").to route_to("events#update", :id => "1") + end + + it "routes to #destroy" do + expect(:delete => "/events/1").to route_to("events#destroy", :id => "1") + end + + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index eb4b318..d2b5ffe 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,55 +1,127 @@ -if ENV["CODECLIMATE_REPO_TOKEN"] - require 'codeclimate-test-reporter' - CodeClimate::TestReporter.start -end +require "capybara/rspec" +require 'capybara' +require 'capybara/dsl' +require 'omniauth' +require 'capybara/webkit' +require 'support/omniauth_macros' +require 'factory_girl_rails' + +#require "rails_helper" +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration + Capybara::Webkit.configure do |config| + config.allow_url("http://www.gravatar.com/avatar/774dfd6ed85de3337c35a6115ad0fc10?s=30") + config.allow_url("www.filepicker.io") + config.allow_url("dialog.filepicker.io") + config.allow_url("https://dialog.filepicker.io/dialog/comm_iframe/") + config.allow_url("api.filepicker.io") + config.allow_url("http://api.filepicker.io/v2/filepicker.js") + end -require "rubygems" - -ENV["RAILS_ENV"] ||= 'test' -ENV["SECRET_TOKEN"] = "TEST123" -ENV["DEVISE_SECRET_KEY"] = "TEST_DEVISE_123" -require "rails/application" -# https://github.com/timcharper/spork/wiki/Spork.trap_method-Jujutsu -require File.expand_path("../../config/environment", __FILE__) -require 'rspec/rails' -require 'shoulda/matchers/integrations/rspec' -require "factory_girl" -require 'capybara/rails' -require 'capybara/rspec' -require "subelsky_power_tools/page_load_assertions" -require "subelsky_power_tools/controller_shared_behavior" -require "pp" - -Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } RSpec.configure do |config| + + config.include FactoryGirl::Syntax::Methods - config.include PageLoadTest, :type => :feature - config.infer_spec_type_from_file_location! - config.use_transactional_fixtures = false + OmniAuth.config.test_mode = true +# OmniAuth.config.add_mock(:google, {:uid => '12345'}, {}) +# OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({ +# :provider => 'twitter', +# :uid => '123545', +# :info => { +# :nickname => "Alas" +# } +# }) + config.include(OmniauthMacros) + Capybara.javascript_driver = :webkit - config.expect_with :rspec do |c| - c.syntax = :expect - end - config.mock_with :rspec do |c| - c.syntax = :expect + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true end - config.before :suite do - DatabaseCleaner.clean_with :truncation - DatabaseCleaner.strategy = :truncation + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true end - config.before(:each) do - GC.disable - end +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true - config.before(:each) do - DatabaseCleaner.start - end + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching + config.disable_monkey_patching! - config.after(:each) do - DatabaseCleaner.clean + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end end diff --git a/spec/support/basic_authentication.rb b/spec/support/basic_authentication.rb new file mode 100644 index 0000000..bf021dc --- /dev/null +++ b/spec/support/basic_authentication.rb @@ -0,0 +1,22 @@ +require "spec_helper" +require "rails_helper" +require "capybara/rspec" +require 'capybara' +require 'capybara/dsl' + + +RSpec.shared_context 'basic authentication' do + def encoded_username_password + username = ENV.fetch('ADMIN_USERNAME') + password = ENV.fetch('ADMIN_PASSWORD') + + ActionController::HttpAuthentication::Basic + .encode_credentials(username, password) + end + + def http_basic_authentication + page.driver.header 'Authorization', encoded_username_password + request.env['HTTP_AUTHORIZATION'] = encoded_username_password + end + +end diff --git a/spec/support/omniauth_macros.rb b/spec/support/omniauth_macros.rb new file mode 100644 index 0000000..5511e9e --- /dev/null +++ b/spec/support/omniauth_macros.rb @@ -0,0 +1,42 @@ +module OmniauthMacros + def mock_twitter_authorized + OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({ + :provider => 'twitter', + :uid => '123545', + :info => { + :nickname => 'Alas' + } + }) + end + + def mock_twitter_unauthorized + OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({ + :provider => 'twitter', + :uid => '123545', + :info => { + :nickname => 'NoNick' + } + }) + end + + def mock_google_authorized + OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new({ + :provider => 'google', + :uid => '123545', + :info => { + :email => 'alas@gmail.com' + } + }) + end + + def mock_google_unauthorized + OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new({ + :provider => 'google', + :uid => '123545', + :info => { + :email => 'noemail@gmail.com' + } + }) + end + +end