From 5e71cc46abbdd63305ee1d4c223439b7b90542c3 Mon Sep 17 00:00:00 2001 From: Nono Date: Fri, 12 Feb 2016 15:34:31 -0500 Subject: [PATCH 01/30] Added new code to have a database for selected and not archived events --- app/assets/javascripts/events.js | 2 + app/assets/stylesheets/events.sass | 3 + app/assets/stylesheets/scaffolds.sass | 60 ++++++++ app/controllers/events_controller.rb | 59 ++++++++ app/helpers/events_helper.rb | 2 + app/models/event.rb | 16 ++ app/views/events/_form.html.haml | 10 ++ app/views/events/edit.html.haml | 7 + app/views/events/index.html.haml | 25 ++++ app/views/events/new.html.haml | 5 + app/views/events/show.html.haml | 15 ++ config/locales/rails_admin.en.yml | 155 +++++++++++++++++++ lib/rails_admin_loadevent.rb | 44 ++++++ spec/controllers/events_controller_spec.rb | 164 +++++++++++++++++++++ spec/models/event_spec.rb | 13 ++ spec/rails_helper.rb | 52 +++++++ spec/routing/events_routing_spec.rb | 39 +++++ 17 files changed, 671 insertions(+) create mode 100644 app/assets/javascripts/events.js create mode 100644 app/assets/stylesheets/events.sass create mode 100644 app/assets/stylesheets/scaffolds.sass create mode 100644 app/controllers/events_controller.rb create mode 100644 app/helpers/events_helper.rb create mode 100644 app/models/event.rb create mode 100644 app/views/events/_form.html.haml create mode 100644 app/views/events/edit.html.haml create mode 100644 app/views/events/index.html.haml create mode 100644 app/views/events/new.html.haml create mode 100644 app/views/events/show.html.haml create mode 100644 config/locales/rails_admin.en.yml create mode 100644 lib/rails_admin_loadevent.rb create mode 100644 spec/controllers/events_controller_spec.rb create mode 100644 spec/models/event_spec.rb create mode 100644 spec/rails_helper.rb create mode 100644 spec/routing/events_routing_spec.rb 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..d08cacd --- /dev/null +++ b/app/controllers/events_controller.rb @@ -0,0 +1,59 @@ +class EventsController < ApplicationController + before_action :set_event, only: [:show, :edit, :update, :destroy] + + # GET /events + def index + @events = Event.all + 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) + 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/event.rb b/app/models/event.rb new file mode 100644 index 0000000..c1967c4 --- /dev/null +++ b/app/models/event.rb @@ -0,0 +1,16 @@ +class Event < ActiveRecord::Base + belongs_to :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 + end + end +end diff --git a/app/views/events/_form.html.haml b/app/views/events/_form.html.haml new file mode 100644 index 0000000..d082c5a --- /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 + + .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..59de7f2 --- /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 + %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..f317aa2 --- /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 + += link_to 'Edit', edit_event_path(@event) +\| += link_to 'Back', events_path 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/lib/rails_admin_loadevent.rb b/lib/rails_admin_loadevent.rb new file mode 100644 index 0000000..2441764 --- /dev/null +++ b/lib/rails_admin_loadevent.rb @@ -0,0 +1,44 @@ +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) + recordEvent = Event.create(eachEvent.attributes) + if recordEvent.valid? + recordEvent.save + end + end + } + end + redirect_to back_or_index + end + end + 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/models/event_spec.rb b/spec/models/event_spec.rb new file mode 100644 index 0000000..28e04bb --- /dev/null +++ b/spec/models/event_spec.rb @@ -0,0 +1,13 @@ +require 'rails_helper' + +describe Event, type: :controller do +# it { should validate_presence_of :title} + +# it is_expected.to respond_with :ok do + it "OKKKKK" do + get :show + end + +end + + diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..88ff2d0 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,52 @@ +# 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' +# 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 = true + + # 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 From 11b9b4543ef609b44f4bd1ca30da281423d2d895 Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 13 Feb 2016 05:01:01 -0500 Subject: [PATCH 02/30] Added migration for events --- db/migrate/20160211082126_create_events.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 db/migrate/20160211082126_create_events.rb 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 From d9799401286fcf8617bad43f84b6677731874e4d Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 13 Feb 2016 05:05:01 -0500 Subject: [PATCH 03/30] changed routes and added events button --- config/initializers/rails_admin.rb | 38 +++++++++++++++++++++++++++++- config/routes.rb | 2 ++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/config/initializers/rails_admin.rb b/config/initializers/rails_admin.rb index 0da160f..4801886 100644 --- a/config/initializers/rails_admin.rb +++ b/config/initializers/rails_admin.rb @@ -1,8 +1,44 @@ # 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| +# # Load the class in lib/rails_admin_loadevent.rb +# module RailsAdmin +# module Config +# module Actions +# class Loadevent < RailsAdmin::Config::Actions::Base +# RailsAdmin::Config::Actions.register(self) +# end +# end +# end +# end +# + config.actions do + # root actions + dashboard # mandatory + # collection actions + index # mandatory + 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 ################ @@ -37,7 +73,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/routes.rb b/config/routes.rb index 709b801..bbb617a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,6 @@ Ignitespeak::Application.routes.draw do + resources :clothes + resources :events mount RailsAdmin::Engine => '/admin', :as => 'rails_admin' resources :proposals do From 40da11b3e7ed7d3efc98e40dd767daa081baa0c2 Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 13 Feb 2016 05:11:41 -0500 Subject: [PATCH 04/30] removed clothes from routes --- config/routes.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/config/routes.rb b/config/routes.rb index bbb617a..3f7a3f2 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,5 +1,4 @@ Ignitespeak::Application.routes.draw do - resources :clothes resources :events mount RailsAdmin::Engine => '/admin', :as => 'rails_admin' From 8b0b048f1eb3310339e264eb5d6d76b8a20ffad2 Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 13 Feb 2016 05:14:32 -0500 Subject: [PATCH 05/30] clean up rails_admin --- config/initializers/rails_admin.rb | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/config/initializers/rails_admin.rb b/config/initializers/rails_admin.rb index 4801886..d73ca81 100644 --- a/config/initializers/rails_admin.rb +++ b/config/initializers/rails_admin.rb @@ -5,27 +5,17 @@ RailsAdmin.config do |config| -# # Load the class in lib/rails_admin_loadevent.rb -# module RailsAdmin -# module Config -# module Actions -# class Loadevent < RailsAdmin::Config::Actions::Base -# RailsAdmin::Config::Actions.register(self) -# end -# end -# end -# end -# + config.actions do - # root actions - dashboard # mandatory - # collection actions - index # mandatory + # root actions + dashboard + # collection actions + index new export history_index bulk_delete - # member actions + # member actions show edit delete From bdc449367d6842bf6f7cf55ffdae09ee659b5317 Mon Sep 17 00:00:00 2001 From: Nono Date: Sun, 21 Feb 2016 12:38:42 -0500 Subject: [PATCH 06/30] Rspec tests for event and authentication --- Gemfile | 8 +- spec/controllers/events_integration_spec.rb | 22 ++++ spec/features/authentication_to_admin.rb | 17 +++ spec/features/click_spec.rb | 62 ++++++++++ spec/spec_helper.rb | 130 +++++++++++++------- spec/support/basic_authentication.rb | 22 ++++ 6 files changed, 217 insertions(+), 44 deletions(-) create mode 100644 spec/controllers/events_integration_spec.rb create mode 100644 spec/features/authentication_to_admin.rb create mode 100644 spec/features/click_spec.rb create mode 100644 spec/support/basic_authentication.rb diff --git a/Gemfile b/Gemfile index 2536463..80d575b 100644 --- a/Gemfile +++ b/Gemfile @@ -33,15 +33,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/spec/controllers/events_integration_spec.rb b/spec/controllers/events_integration_spec.rb new file mode 100644 index 0000000..da17e34 --- /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 => "hello/world" } + }.to_not change {Event.count} + end + 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/spec_helper.rb b/spec/spec_helper.rb index eb4b318..8de5ae4 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,55 +1,101 @@ -if ENV["CODECLIMATE_REPO_TOKEN"] - require 'codeclimate-test-reporter' - CodeClimate::TestReporter.start -end +require "capybara/rspec" +require 'capybara' +require 'capybara/dsl' + -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 } +#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 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 +Capybara.javascript_driver = :webkit - config.expect_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.mock_with :rspec do |c| - c.syntax = :expect + # 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 :suite do - DatabaseCleaner.clean_with :truncation - DatabaseCleaner.strategy = :truncation - 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 - GC.disable - 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" - config.before(:each) do - DatabaseCleaner.start - end + # 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 From 939e12b13d2fad39207cedf724a8629938778bbb Mon Sep 17 00:00:00 2001 From: Nono Date: Sun, 21 Feb 2016 14:07:03 -0500 Subject: [PATCH 07/30] Added relationship between event and proposal --- app/models/proposal.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/models/proposal.rb b/app/models/proposal.rb index 12748ac..75c9fc3 100644 --- a/app/models/proposal.rb +++ b/app/models/proposal.rb @@ -22,6 +22,8 @@ require "digest/sha2" class Proposal < ActiveRecord::Base + has_one :event + validates_presence_of :title, :description, :email, :bio, :speaker_name, allow_blank: false validates :description, length: { maximum: 1000 } validates :bio, length: { maximum: 100 } From 959c2dd93883674c7bfd9ab83e8b870bdb01ba6d Mon Sep 17 00:00:00 2001 From: Nono Date: Tue, 1 Mar 2016 15:22:49 -0500 Subject: [PATCH 08/30] Added authentication for Twitter and Googl --- Gemfile | 3 + .../omniauth_callbacks_controller.rb | 25 ++ app/models/admin.rb | 46 +++ config/initializers/devise.rb | 270 ++++++++++++++++++ config/initializers/rails_admin.rb | 10 +- config/locales/devise.en.yml | 100 +++---- config/routes.rb | 3 + .../20160229144015_devise_create_admins.rb | 43 +++ 8 files changed, 448 insertions(+), 52 deletions(-) create mode 100644 app/controllers/omniauth_callbacks_controller.rb create mode 100644 app/models/admin.rb create mode 100644 config/initializers/devise.rb create mode 100644 db/migrate/20160229144015_devise_create_admins.rb diff --git a/Gemfile b/Gemfile index 80d575b..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" diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb new file mode 100644 index 0000000..c9092a4 --- /dev/null +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -0,0 +1,25 @@ +class OmniauthCallbacksController < Devise::OmniauthCallbacksController + def twitter + auth = env["omniauth.auth"] + @admin = Admin.do_twitter_oauth(request.env["omniauth.auth"],current_admin) + 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_registration_url + end + end + + def google + @admin = Admin.do_google_oauth2(request.env["omniauth.auth"], current_admin) + if @admin.persisted? + flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" + sign_in_and_redirect @admin, :event => :authentication + else + session["devise.google_data"] = request.env["omniauth.auth"] + redirect_to new_admin_registration_url + end + end +end + diff --git a/app/models/admin.rb b/app/models/admin.rb new file mode 100644 index 0000000..c5c5b3d --- /dev/null +++ b/app/models/admin.rb @@ -0,0 +1,46 @@ +class Admin < ActiveRecord::Base + devise :database_authenticatable, :omniauthable, + :recoverable, :rememberable, :trackable, + :validatable + + def self.do_twitter_oauth(auth, signed_in_resource = nil) + admin = Admin.where(:provider => auth.provider, :uid => auth.uid).first + if admin + return admin + else + registered_admin = Admin.where(:email => auth.uid + "@twitter.com").first + if registered_admin + return registered_admin + else + # create user + admin = Admin.create(name:auth.info.name, + provider:auth.provider, + uid:auth.uid, + email:auth.uid+"@twitter.com", + password:Devise.friendly_token[0,20] + ) + end + end + end + + def self.do_google_oauth2(access_token, signed_in_resource = nil) + data = access_token.info + admin = Admin.where(:provider => access_token.provider, :uid => access_token.uid ).first + if admin + return admin + else + registered_admin = Admin.where(:email => access_token.info.email).first + if registered_admin + return registered_admin + else + # create user + admin = Admin.create(name: data["name"], + provider:access_token.provider, + email: data["email"], + uid: access_token.uid , + password: Devise.friendly_token[0,20] + ) + end + end + end +end 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 d73ca81..d8a9149 100644 --- a/config/initializers/rails_admin.rb +++ b/config/initializers/rails_admin.rb @@ -40,11 +40,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: 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/routes.rb b/config/routes.rb index 3f7a3f2..47f711b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,7 @@ 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' diff --git a/db/migrate/20160229144015_devise_create_admins.rb b/db/migrate/20160229144015_devise_create_admins.rb new file mode 100644 index 0000000..9dc3767 --- /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 From 7a8ec138e3032adb1aa988cbbe3637a9584329cc Mon Sep 17 00:00:00 2001 From: Nono Date: Tue, 1 Mar 2016 23:31:39 -0500 Subject: [PATCH 09/30] template to create a sample username and password --- db/seeds.rb | 1 + 1 file changed, 1 insertion(+) 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") From da680149facbaaff9eb5ede7a10a691359584b3c Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 2 Mar 2016 11:58:29 -0500 Subject: [PATCH 10/30] Added Foreign key and event_id --- app/models/event.rb | 2 +- app/models/proposal.rb | 2 +- db/migrate/20160229155901_add_columns_to_admins.rb | 7 +++++++ db/migrate/20160301165137_add_name_to_admins.rb | 5 +++++ db/migrate/20160302044450_add_foreign_key_to_events.rb | 5 +++++ .../20160302164052_add_foreign_reference_to_events.rb | 6 ++++++ 6 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20160229155901_add_columns_to_admins.rb create mode 100644 db/migrate/20160301165137_add_name_to_admins.rb create mode 100644 db/migrate/20160302044450_add_foreign_key_to_events.rb create mode 100644 db/migrate/20160302164052_add_foreign_reference_to_events.rb diff --git a/app/models/event.rb b/app/models/event.rb index c1967c4..afdcd13 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -1,5 +1,5 @@ class Event < ActiveRecord::Base - belongs_to :proposal + has_many :proposal validates_presence_of :title, allow_blank: false diff --git a/app/models/proposal.rb b/app/models/proposal.rb index 75c9fc3..8c558b2 100644 --- a/app/models/proposal.rb +++ b/app/models/proposal.rb @@ -22,7 +22,7 @@ require "digest/sha2" class Proposal < ActiveRecord::Base - has_one :event + belongs_to :event validates_presence_of :title, :description, :email, :bio, :speaker_name, allow_blank: false validates :description, length: { maximum: 1000 } 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..5573082 --- /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/20160301165137_add_name_to_admins.rb b/db/migrate/20160301165137_add_name_to_admins.rb new file mode 100644 index 0000000..f412855 --- /dev/null +++ b/db/migrate/20160301165137_add_name_to_admins.rb @@ -0,0 +1,5 @@ +class AddNameToAdmins < ActiveRecord::Migration + def change + add_column :admins, :name, :string + end +end diff --git a/db/migrate/20160302044450_add_foreign_key_to_events.rb b/db/migrate/20160302044450_add_foreign_key_to_events.rb new file mode 100644 index 0000000..bda02d8 --- /dev/null +++ b/db/migrate/20160302044450_add_foreign_key_to_events.rb @@ -0,0 +1,5 @@ +class AddForeignKeyToEvents < ActiveRecord::Migration + def change + add_foreign_key :events, :proposals + 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..9fa48a9 --- /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 + end +end From 3e974f12986bbca73c4a598b4364ec4baf0160a3 Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 2 Mar 2016 12:05:42 -0500 Subject: [PATCH 11/30] removed wrong migration file --- db/migrate/20160302044450_add_foreign_key_to_events.rb | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 db/migrate/20160302044450_add_foreign_key_to_events.rb diff --git a/db/migrate/20160302044450_add_foreign_key_to_events.rb b/db/migrate/20160302044450_add_foreign_key_to_events.rb deleted file mode 100644 index bda02d8..0000000 --- a/db/migrate/20160302044450_add_foreign_key_to_events.rb +++ /dev/null @@ -1,5 +0,0 @@ -class AddForeignKeyToEvents < ActiveRecord::Migration - def change - add_foreign_key :events, :proposals - end -end From 305f2d33f06f81d32aad7c055e73d9dc740e78d2 Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 2 Mar 2016 13:07:14 -0500 Subject: [PATCH 12/30] Modified migration file due to duplicate name --- db/migrate/20160229144015_devise_create_admins.rb | 2 +- db/migrate/20160229155901_add_columns_to_admins.rb | 2 +- db/migrate/20160301165137_add_name_to_admins.rb | 5 ----- 3 files changed, 2 insertions(+), 7 deletions(-) delete mode 100644 db/migrate/20160301165137_add_name_to_admins.rb diff --git a/db/migrate/20160229144015_devise_create_admins.rb b/db/migrate/20160229144015_devise_create_admins.rb index 9dc3767..13389f1 100644 --- a/db/migrate/20160229144015_devise_create_admins.rb +++ b/db/migrate/20160229144015_devise_create_admins.rb @@ -4,7 +4,7 @@ def change ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" - t.string :name null: false, default: "" + t.string :name, null: false, default: "" ## Recoverable t.string :reset_password_token diff --git a/db/migrate/20160229155901_add_columns_to_admins.rb b/db/migrate/20160229155901_add_columns_to_admins.rb index 5573082..197ab8b 100644 --- a/db/migrate/20160229155901_add_columns_to_admins.rb +++ b/db/migrate/20160229155901_add_columns_to_admins.rb @@ -2,6 +2,6 @@ class AddColumnsToAdmins < ActiveRecord::Migration def change add_column :admins, :provider, :string add_column :admins, :uid, :string - add_column :admins, :name, :string +# add_column :admins, :name, :string end end diff --git a/db/migrate/20160301165137_add_name_to_admins.rb b/db/migrate/20160301165137_add_name_to_admins.rb deleted file mode 100644 index f412855..0000000 --- a/db/migrate/20160301165137_add_name_to_admins.rb +++ /dev/null @@ -1,5 +0,0 @@ -class AddNameToAdmins < ActiveRecord::Migration - def change - add_column :admins, :name, :string - end -end From 47439e5f0e83843fbc31d37808db54c840f2f07b Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 2 Mar 2016 13:30:36 -0500 Subject: [PATCH 13/30] added scoped for event --- app/controllers/events_controller.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index d08cacd..57a9705 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -4,6 +4,7 @@ class EventsController < ApplicationController # GET /events def index @events = Event.all + Event.scoped end # GET /events/1 From 58b2a1467b419a8bca591b83246b991d6a593f66 Mon Sep 17 00:00:00 2001 From: Nono Date: Sun, 20 Mar 2016 05:23:34 -0400 Subject: [PATCH 14/30] Style change use if in return --- app/models/admin.rb | 62 ++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/app/models/admin.rb b/app/models/admin.rb index c5c5b3d..1680d71 100644 --- a/app/models/admin.rb +++ b/app/models/admin.rb @@ -5,42 +5,40 @@ class Admin < ActiveRecord::Base def self.do_twitter_oauth(auth, signed_in_resource = nil) admin = Admin.where(:provider => auth.provider, :uid => auth.uid).first - if admin - return admin - else - registered_admin = Admin.where(:email => auth.uid + "@twitter.com").first - if registered_admin - return registered_admin - else - # create user - admin = Admin.create(name:auth.info.name, - provider:auth.provider, - uid:auth.uid, - email:auth.uid+"@twitter.com", - password:Devise.friendly_token[0,20] - ) - end - end + + return admin if admin + + registered_admin = Admin.where(:email => auth.uid + "@twitter.com").first + + return registered_admin if registered_admin + + # create user + admin = Admin.create(name:auth.info.name, + provider:auth.provider, + uid:auth.uid, + email:auth.uid+"@twitter.com", + password:Devise.friendly_token[0,20] + ) end def self.do_google_oauth2(access_token, signed_in_resource = nil) data = access_token.info admin = Admin.where(:provider => access_token.provider, :uid => access_token.uid ).first - if admin - return admin - else - registered_admin = Admin.where(:email => access_token.info.email).first - if registered_admin - return registered_admin - else - # create user - admin = Admin.create(name: data["name"], - provider:access_token.provider, - email: data["email"], - uid: access_token.uid , - password: Devise.friendly_token[0,20] - ) - end - end + + return admin if admin + + registered_admin = Admin.where(:email => access_token.info.email).first + + return registered_admin if registered_admin + + # create user + admin = Admin.create(name: data["name"], + provider:access_token.provider, + email: data["email"], + uid: access_token.uid , + password: Devise.friendly_token[0,20] + ) end + end + From 33d57d7e21a175e025622f99ca1aa82552bac91e Mon Sep 17 00:00:00 2001 From: Nono Date: Mon, 21 Mar 2016 07:41:48 -0400 Subject: [PATCH 15/30] added rspec for testing sign in using twitter and Google --- spec/features/omniauth.rb | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 spec/features/omniauth.rb diff --git a/spec/features/omniauth.rb b/spec/features/omniauth.rb new file mode 100644 index 0000000..a9a4514 --- /dev/null +++ b/spec/features/omniauth.rb @@ -0,0 +1,31 @@ +require "spec_helper" +require "rails_helper" +require 'support/basic_authentication' + +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" do + visit rails_admin.dashboard_path + click_link "Sign in with Twitter" +# puts page.body + expect(page).to have_content 'Site Administration' + end + + it "google sign in button should get to the admin page" do + visit rails_admin.dashboard_path + click_link "Sign in with Google" +# puts page.body + expect(page).to have_content 'Site Administration' + end + +# 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 From e4ad82df262134f0e9c082c8acdca675ec04b12a Mon Sep 17 00:00:00 2001 From: Nono Date: Mon, 21 Mar 2016 07:49:01 -0400 Subject: [PATCH 16/30] DRY' omniauth callbacks duplicate code goes into one --- .../omniauth_callbacks_controller.rb | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index c9092a4..ac0331d 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -1,25 +1,23 @@ class OmniauthCallbacksController < Devise::OmniauthCallbacksController def twitter - auth = env["omniauth.auth"] - @admin = Admin.do_twitter_oauth(request.env["omniauth.auth"],current_admin) - 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_registration_url - end + social_callback("twitter") + return end def google - @admin = Admin.do_google_oauth2(request.env["omniauth.auth"], current_admin) + social_callback("google") + return + end + + def social_callback(provider) + @admin = Admin.do_generic_oauth(request.env["omniauth.auth"], current_admin, provider) if @admin.persisted? - flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" + flash[:notice] = I18n.t "devise.omniauth_callbacks.success" sign_in_and_redirect @admin, :event => :authentication else - session["devise.google_data"] = request.env["omniauth.auth"] - redirect_to new_admin_registration_url + session["devise.twitter_uid"] = request.env["omniauth.auth"] + redirect_to new_admin_session_path end end -end +end From fa3c56ccc58ccdcb392aa67e2dcd11a900e72000 Mon Sep 17 00:00:00 2001 From: Nono Date: Mon, 21 Mar 2016 07:52:27 -0400 Subject: [PATCH 17/30] Combined twitter and google omniauth functions into one --- app/models/admin.rb | 45 +++++++++++++++------------------------------ 1 file changed, 15 insertions(+), 30 deletions(-) diff --git a/app/models/admin.rb b/app/models/admin.rb index 1680d71..e7bc2bc 100644 --- a/app/models/admin.rb +++ b/app/models/admin.rb @@ -3,42 +3,27 @@ class Admin < ActiveRecord::Base :recoverable, :rememberable, :trackable, :validatable - def self.do_twitter_oauth(auth, signed_in_resource = nil) - admin = Admin.where(:provider => auth.provider, :uid => auth.uid).first - - return admin if admin - - registered_admin = Admin.where(:email => auth.uid + "@twitter.com").first - - return registered_admin if registered_admin - - # create user - admin = Admin.create(name:auth.info.name, - provider:auth.provider, - uid:auth.uid, - email:auth.uid+"@twitter.com", - password:Devise.friendly_token[0,20] - ) - end - - def self.do_google_oauth2(access_token, signed_in_resource = nil) - data = access_token.info - admin = Admin.where(:provider => access_token.provider, :uid => access_token.uid ).first + 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 - registered_admin = Admin.where(:email => access_token.info.email).first - + # 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: data["name"], - provider:access_token.provider, - email: data["email"], - uid: access_token.uid , - password: Devise.friendly_token[0,20] + 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 From 7df4cda38601aaab89b936a1b60dd2a2f8229a52 Mon Sep 17 00:00:00 2001 From: Nono Date: Mon, 21 Mar 2016 07:59:01 -0400 Subject: [PATCH 18/30] ignore lock file --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) 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 From 5539a7007817d51c965f6c45d7bea9493afcecf8 Mon Sep 17 00:00:00 2001 From: Nono Date: Mon, 21 Mar 2016 08:00:50 -0400 Subject: [PATCH 19/30] nickname added to the admin user table because twitter does not return email --- db/migrate/20160321050020_add_nickname_to_admins.rb | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 db/migrate/20160321050020_add_nickname_to_admins.rb 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 From a697e814da58fae43a974787901e077d08d3b13b Mon Sep 17 00:00:00 2001 From: Nono Date: Tue, 22 Mar 2016 04:10:31 -0400 Subject: [PATCH 20/30] Prevent any user from accessing admin page --- Gemfile.lock | 291 ------------------ .../omniauth_callbacks_controller.rb | 17 +- config/initializers/rails_admin.rb | 1 - spec/features/authentication_to_admin.rb | 2 +- spec/spec_helper.rb | 18 +- 5 files changed, 33 insertions(+), 296 deletions(-) delete mode 100644 Gemfile.lock 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/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index ac0331d..8183e34 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -10,7 +10,22 @@ def google end def social_callback(provider) - @admin = Admin.do_generic_oauth(request.env["omniauth.auth"], current_admin, provider) + auth_det = request.env["omniauth.auth"] + + # 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 + + @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 diff --git a/config/initializers/rails_admin.rb b/config/initializers/rails_admin.rb index d8a9149..1dcefed 100644 --- a/config/initializers/rails_admin.rb +++ b/config/initializers/rails_admin.rb @@ -5,7 +5,6 @@ RailsAdmin.config do |config| - config.actions do # root actions dashboard diff --git a/spec/features/authentication_to_admin.rb b/spec/features/authentication_to_admin.rb index a9710ca..b1dfbf8 100644 --- a/spec/features/authentication_to_admin.rb +++ b/spec/features/authentication_to_admin.rb @@ -8,7 +8,7 @@ it "access the admin page" do # go to the admin page visit rails_admin.dashboard_path - # login to the admin page + 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 diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 8de5ae4..b41da05 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,7 +1,8 @@ require "capybara/rspec" require 'capybara' require 'capybara/dsl' - +require 'omniauth' +require 'capybara/webkit' #require "rails_helper" # This file was generated by the `rails generate rspec:install` command. Conventionally, all @@ -22,9 +23,22 @@ # 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 + RSpec.configure do |config| -Capybara.javascript_driver = :webkit + + OmniAuth.config.test_mode = true +# OmniAuth.config.add_mock(:google, {:uid => '12345'}) + Capybara.javascript_driver = :webkit + # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest From 728d0f3f3ea682338c3817a759baecfd80778472 Mon Sep 17 00:00:00 2001 From: Nono Date: Tue, 22 Mar 2016 09:15:03 -0400 Subject: [PATCH 21/30] Added rake task to create admin user --- lib/tasks/adminusers.rake | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 lib/tasks/adminusers.rake diff --git a/lib/tasks/adminusers.rake b/lib/tasks/adminusers.rake new file mode 100644 index 0000000..6e2701a --- /dev/null +++ b/lib/tasks/adminusers.rake @@ -0,0 +1,29 @@ +include Rails.application.routes.url_helpers + +namespace :admin do + task :adduser => :environment do + puts "Email address should be as your google app or twitter app account. If you would login using Twitter, you would need to provide your twitter nickname" + puts "============================" + puts "Enter Google email address:" + email = STDIN.gets + puts "============================" + puts "Enter Twitter nickname:" + nickname = STDIN.gets + puts "============================" + puts "Enter a secure password:" + password = STDIN.gets + + # remove white spaces + password = password.strip! + email = email.strip! + nickname = nickname.strip! + if (email.present? or nickname.present?) and password.present? + if Admin.create!(:email => email, :nickname => nickname, :password => password) + puts "Admin user created!" + else + puts "Failed to create user" + end + end + puts "=============END=============" + end +end From ef2cdcffa127ace16dbdc3ac61b157eec4ec02a8 Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 23 Mar 2016 16:29:20 -0400 Subject: [PATCH 22/30] additional conditions to prevent unauthorized user from accessing admin area --- .../omniauth_callbacks_controller.rb | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index 8183e34..073157f 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -11,20 +11,44 @@ def google def social_callback(provider) auth_det = request.env["omniauth.auth"] - + puts "111111111111111111111111111111111111111111" + puts auth_det.info.nickname + puts auth_det.info.email + + # 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 + puts "HERE1:" +# puts Admin.where(:nickname => "Alas") + # puts Admin.where("admins.nickname IS NOT NULL") +# Admin.includes(:bar).where.not('bars.id' => nil) + # puts k[:nickname] + puts ActiveRecord::Base.connection.execute("Select * from admins") +# puts "over" # 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 - + puts "2222222222222222222222222222222222" 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 + + puts "333333333333333333333333333333333333333333" + @admin = Admin.do_generic_oauth(auth_det, current_admin, provider) if @admin.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success" From 2a2328d27032c7a8ee3e58ad9deacd60632f5ab1 Mon Sep 17 00:00:00 2001 From: Nono Date: Thu, 24 Mar 2016 09:34:08 -0400 Subject: [PATCH 23/30] added rspec for testing authorization of users using twitter and google --- .../omniauth_callbacks_controller.rb | 16 +--- spec/features/omniauth.rb | 77 +++++++++++++++---- spec/rails_helper.rb | 18 ++++- spec/spec_helper.rb | 11 ++- spec/support/omniauth_macros.rb | 42 ++++++++++ 5 files changed, 135 insertions(+), 29 deletions(-) create mode 100644 spec/support/omniauth_macros.rb diff --git a/app/controllers/omniauth_callbacks_controller.rb b/app/controllers/omniauth_callbacks_controller.rb index 073157f..56b5cb9 100644 --- a/app/controllers/omniauth_callbacks_controller.rb +++ b/app/controllers/omniauth_callbacks_controller.rb @@ -11,44 +11,32 @@ def google def social_callback(provider) auth_det = request.env["omniauth.auth"] - puts "111111111111111111111111111111111111111111" - puts auth_det.info.nickname - puts auth_det.info.email # 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 - puts "HERE1:" -# puts Admin.where(:nickname => "Alas") - # puts Admin.where("admins.nickname IS NOT NULL") -# Admin.includes(:bar).where.not('bars.id' => nil) - # puts k[:nickname] - puts ActiveRecord::Base.connection.execute("Select * from admins") -# puts "over" + # 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 - puts "2222222222222222222222222222222222" + 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 - puts "333333333333333333333333333333333333333333" - @admin = Admin.do_generic_oauth(auth_det, current_admin, provider) if @admin.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success" diff --git a/spec/features/omniauth.rb b/spec/features/omniauth.rb index a9a4514..50a7993 100644 --- a/spec/features/omniauth.rb +++ b/spec/features/omniauth.rb @@ -1,31 +1,82 @@ require "spec_helper" -require "rails_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" 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!(:nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") + ad.save! + visit rails_admin.dashboard_path click_link "Sign in with Twitter" -# puts page.body 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!(: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!(:nickname => "", :email =>"alas@gmail.com", :password => "1234567890") + ad.save! + visit rails_admin.dashboard_path click_link "Sign in with Google" -# puts page.body expect(page).to have_content 'Site Administration' end -# 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 + + 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!(: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/rails_helper.rb b/spec/rails_helper.rb index 88ff2d0..75f3104 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -5,6 +5,8 @@ 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 @@ -33,7 +35,21 @@ # 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 = 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 diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b41da05..5676769 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -3,6 +3,7 @@ require 'capybara/dsl' require 'omniauth' require 'capybara/webkit' +require 'support/omniauth_macros' #require "rails_helper" # This file was generated by the `rails generate rspec:install` command. Conventionally, all @@ -36,7 +37,15 @@ RSpec.configure do |config| OmniAuth.config.test_mode = true -# OmniAuth.config.add_mock(:google, {:uid => '12345'}) +# 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 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 From 0a025887956cdfc99d9cd0b03a694a38f33718ff Mon Sep 17 00:00:00 2001 From: Nono Date: Thu, 24 Mar 2016 09:35:04 -0400 Subject: [PATCH 24/30] added bang when creating admin user --- app/models/admin.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/admin.rb b/app/models/admin.rb index e7bc2bc..c5e39e0 100644 --- a/app/models/admin.rb +++ b/app/models/admin.rb @@ -17,7 +17,7 @@ def self.do_generic_oauth(auth_hash, signed_in_resource = nil, provider) registered_admin = Admin.where(:email => email_provider).first return registered_admin if registered_admin # create user - admin = Admin.create(name: auth_hash.info.name, + admin = Admin.create!(name: auth_hash.info.name, provider:auth_hash.provider, email: email_provider, uid: auth_hash.uid , From f4cb1afe0d8fe275457cbac6a462b0083162502b Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 26 Mar 2016 02:52:49 -0400 Subject: [PATCH 25/30] Added tests for authorization --- spec/factories/admin.rb | 15 +++++++++ spec/features/authentication_to_admin.rb | 2 +- spec/features/devise_spec.rb | 32 +++++++++++++++++++ .../{omniauth.rb => omniauth_spec.rb} | 0 spec/models/admin_spec.rb | 32 +++++++++++++++++++ spec/models/event_spec.rb | 13 -------- spec/spec_helper.rb | 3 ++ 7 files changed, 83 insertions(+), 14 deletions(-) create mode 100644 spec/factories/admin.rb create mode 100644 spec/features/devise_spec.rb rename spec/features/{omniauth.rb => omniauth_spec.rb} (100%) create mode 100644 spec/models/admin_spec.rb delete mode 100644 spec/models/event_spec.rb diff --git a/spec/factories/admin.rb b/spec/factories/admin.rb new file mode 100644 index 0000000..3504030 --- /dev/null +++ b/spec/factories/admin.rb @@ -0,0 +1,15 @@ +FactoryGirl.define do + factory :admin do + nickname "A nick" + email "nick@email.com" + password "123456789" + end + + factory :admin2 do + nickname "A" + email "a@email.com" + password "qwrt63876932179" + end + +end + diff --git a/spec/features/authentication_to_admin.rb b/spec/features/authentication_to_admin.rb index b1dfbf8..a9710ca 100644 --- a/spec/features/authentication_to_admin.rb +++ b/spec/features/authentication_to_admin.rb @@ -8,7 +8,7 @@ it "access the admin page" do # go to the admin page visit rails_admin.dashboard_path - login to the admin page + # 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 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.rb b/spec/features/omniauth_spec.rb similarity index 100% rename from spec/features/omniauth.rb rename to spec/features/omniauth_spec.rb 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/models/event_spec.rb b/spec/models/event_spec.rb deleted file mode 100644 index 28e04bb..0000000 --- a/spec/models/event_spec.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'rails_helper' - -describe Event, type: :controller do -# it { should validate_presence_of :title} - -# it is_expected.to respond_with :ok do - it "OKKKKK" do - get :show - end - -end - - diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 5676769..d2b5ffe 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -4,6 +4,7 @@ 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 @@ -36,6 +37,8 @@ RSpec.configure do |config| + + config.include FactoryGirl::Syntax::Methods OmniAuth.config.test_mode = true # OmniAuth.config.add_mock(:google, {:uid => '12345'}, {}) # OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new({ From b2fc36c8b713159022d5e2b08a7506d7cf25d29c Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 26 Mar 2016 06:21:37 -0400 Subject: [PATCH 26/30] Made rake file more user friendly --- lib/tasks/adminusers.rake | 45 ++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/lib/tasks/adminusers.rake b/lib/tasks/adminusers.rake index 6e2701a..690fbe6 100644 --- a/lib/tasks/adminusers.rake +++ b/lib/tasks/adminusers.rake @@ -2,21 +2,41 @@ include Rails.application.routes.url_helpers namespace :admin do task :adduser => :environment do - puts "Email address should be as your google app or twitter app account. If you would login using Twitter, you would need to provide your twitter nickname" - puts "============================" - puts "Enter Google email address:" - email = STDIN.gets - puts "============================" - puts "Enter Twitter nickname:" - nickname = STDIN.gets - puts "============================" + 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 + + 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 = "" + + else + return + end + + puts "Enter a secure password:" password = STDIN.gets + password = password.strip + puts "=================================================================================================" + puts "........................Creating an admin user for an authenticated user........................." - # remove white spaces - password = password.strip! - email = email.strip! - nickname = nickname.strip! if (email.present? or nickname.present?) and password.present? if Admin.create!(:email => email, :nickname => nickname, :password => password) puts "Admin user created!" @@ -24,6 +44,5 @@ namespace :admin do puts "Failed to create user" end end - puts "=============END=============" end end From 12a140deb4804a8bc97923b2114a922256e0c74a Mon Sep 17 00:00:00 2001 From: Nono Date: Sat, 26 Mar 2016 06:32:23 -0400 Subject: [PATCH 27/30] Added on delete cascade to prevent orphaned proposals --- db/migrate/20160302164052_add_foreign_reference_to_events.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/migrate/20160302164052_add_foreign_reference_to_events.rb b/db/migrate/20160302164052_add_foreign_reference_to_events.rb index 9fa48a9..1b9a420 100644 --- a/db/migrate/20160302164052_add_foreign_reference_to_events.rb +++ b/db/migrate/20160302164052_add_foreign_reference_to_events.rb @@ -1,6 +1,6 @@ class AddForeignReferenceToEvents < ActiveRecord::Migration def change add_reference :proposals, :event, index: true - add_foreign_key :proposals, :event + add_foreign_key :proposals, :event, on_delete: :cascade end end From bc59609f3c233dfdfff5635b5ee305602777798d Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 13 Apr 2016 14:15:16 -0400 Subject: [PATCH 28/30] non-null added --- app/controllers/events_controller.rb | 2 +- app/models/event.rb | 2 +- lib/rails_admin_loadevent.rb | 8 +++++++- lib/tasks/adminusers.rake | 8 +++++--- spec/controllers/events_integration_spec.rb | 2 +- spec/factories/admin.rb | 4 ++++ 6 files changed, 19 insertions(+), 7 deletions(-) diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index 57a9705..75acbc6 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -55,6 +55,6 @@ def set_event # Only allow a trusted parameter "white list" through. def event_params - params.require(:event).permit(:title, :time, :tickets) + params.require(:event).permit(:title, :time, :tickets_url) end end diff --git a/app/models/event.rb b/app/models/event.rb index afdcd13..6f503dc 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -10,7 +10,7 @@ class Event < ActiveRecord::Base list do field :title field :time - field :tickets + field :tickets_url end end end diff --git a/lib/rails_admin_loadevent.rb b/lib/rails_admin_loadevent.rb index 2441764..6ea244b 100644 --- a/lib/rails_admin_loadevent.rb +++ b/lib/rails_admin_loadevent.rb @@ -28,7 +28,13 @@ class Loadevent < RailsAdmin::Config::Actions::Base allSelectedEvents.each { |eachEvent| #if records already exist unless Event.exists?(eachEvent.attributes) - recordEvent = Event.create(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 diff --git a/lib/tasks/adminusers.rake b/lib/tasks/adminusers.rake index 690fbe6..0f9b4ad 100644 --- a/lib/tasks/adminusers.rake +++ b/lib/tasks/adminusers.rake @@ -14,7 +14,8 @@ namespace :admin do puts "Enter Twitter nickname:" nickname = STDIN.gets nickname = nickname.strip - + provider = "Twitter" + uid = "Manual" email = nickname + "@twitter.com" elsif option.strip == "2" puts "=================================================================================================" @@ -25,7 +26,8 @@ namespace :admin do email = STDIN.gets email = email.strip nickname = "" - + uid = "Manual" + provider = "Google" else return end @@ -38,7 +40,7 @@ namespace :admin do puts "........................Creating an admin user for an authenticated user........................." if (email.present? or nickname.present?) and password.present? - if Admin.create!(:email => email, :nickname => nickname, :password => password) + if Admin.create!(:uid => uid, :email => email, :nickname => nickname, :password => password, :provider => provider) puts "Admin user created!" else puts "Failed to create user" diff --git a/spec/controllers/events_integration_spec.rb b/spec/controllers/events_integration_spec.rb index da17e34..acbf5fa 100644 --- a/spec/controllers/events_integration_spec.rb +++ b/spec/controllers/events_integration_spec.rb @@ -12,7 +12,7 @@ context "with not a title field being filled and created" do it "the count should remain the same" do expect { - post :create, :event => {:tickets => "hello/world" } + post :create, :event => {:tickets_url => "hello/world" } }.to_not change {Event.count} end end diff --git a/spec/factories/admin.rb b/spec/factories/admin.rb index 3504030..f23e000 100644 --- a/spec/factories/admin.rb +++ b/spec/factories/admin.rb @@ -3,12 +3,16 @@ 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 From e0a52311f80a058a47c14f025ad42b6a9b3f7c3a Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 13 Apr 2016 14:16:29 -0400 Subject: [PATCH 29/30] tickets changed to tickets_url --- app/views/events/_form.html.haml | 2 +- app/views/events/index.html.haml | 2 +- app/views/events/show.html.haml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/views/events/_form.html.haml b/app/views/events/_form.html.haml index d082c5a..5137317 100644 --- a/app/views/events/_form.html.haml +++ b/app/views/events/_form.html.haml @@ -4,7 +4,7 @@ .form-inputs = f.input :title = f.input :time - = f.input :tickets + = f.input :tickets_url .form-actions = f.button :submit diff --git a/app/views/events/index.html.haml b/app/views/events/index.html.haml index 59de7f2..3de97ed 100644 --- a/app/views/events/index.html.haml +++ b/app/views/events/index.html.haml @@ -15,7 +15,7 @@ %tr %td= event.title %td= event.time - %td= event.tickets + %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?' } diff --git a/app/views/events/show.html.haml b/app/views/events/show.html.haml index f317aa2..ad7af92 100644 --- a/app/views/events/show.html.haml +++ b/app/views/events/show.html.haml @@ -8,7 +8,7 @@ = @event.time %p %b Tickets: - = @event.tickets + = @event.tickets_url = link_to 'Edit', edit_event_path(@event) \| From 3c1511dfbcf644293e0423d76bde2ed3ad9f043b Mon Sep 17 00:00:00 2001 From: Nono Date: Wed, 13 Apr 2016 14:17:13 -0400 Subject: [PATCH 30/30] modified spec to accommodate for non nullable columns --- spec/features/omniauth_spec.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spec/features/omniauth_spec.rb b/spec/features/omniauth_spec.rb index 50a7993..7e12b67 100644 --- a/spec/features/omniauth_spec.rb +++ b/spec/features/omniauth_spec.rb @@ -11,7 +11,7 @@ mock_twitter_authorized # create an admin user - ad = Admin.create!(:nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") + ad = Admin.create!(:uid => "Test", :provider => "Twitter", :nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") ad.save! visit rails_admin.dashboard_path @@ -24,7 +24,7 @@ mock_twitter_unauthorized # create an admin user - ad = Admin.create!(:nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") + ad = Admin.create!(:uid => "Test", :provider => "Twitter", :nickname => "Alas", :email =>"alas@twitter.com", :password => "1234567890") ad.save! visit rails_admin.dashboard_path @@ -45,7 +45,7 @@ # get the omniauth hash mock_google_authorized - ad = Admin.create!(:nickname => "", :email =>"alas@gmail.com", :password => "1234567890") + ad = Admin.create!(:uid => "Test", :provider => "Google", :nickname => "", :email =>"alas@gmail.com", :password => "1234567890") ad.save! visit rails_admin.dashboard_path @@ -58,7 +58,7 @@ # get the omniauth hash mock_google_unauthorized - ad = Admin.create!(:nickname => "Alas", :email =>"alas@gmail.com", :password => "1234567890") + ad = Admin.create!(:uid => "Test", :provider => "Google", :nickname => "Alas", :email =>"alas@gmail.com", :password => "1234567890") ad.save! visit rails_admin.dashboard_path