diff --git a/Gemfile b/Gemfile index d3f7da1..488db5d 100644 --- a/Gemfile +++ b/Gemfile @@ -1,14 +1,18 @@ source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } + ruby '3.2.2' -gem 'rails', '~> 6.1.4.4' + +gem 'rails', '~> 7.1.2' + # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'dotenv-rails', '~> 2.7', '>= 2.7.4' gem 'pg' + # Use Puma as the app server gem 'puma', '~> 5.0' # Use SCSS for stylesheets @@ -24,37 +28,46 @@ gem 'jbuilder', '~> 2.7' # Use Active Model has_secure_password # gem 'bcrypt', '~> 3.1.7' + # Use Active Storage variant -# gem 'image_processing', '~> 1.2' +gem 'image_processing', '~> 1.2' + + gem 'twitter', '~> 6.2.0' gem 'sentry-raven', '~> 2.11' -gem "devise", "~> 4.7.3" -gem "omniauth", "~>1.9.0" + +gem 'devise', '~> 4.9', '>= 4.9.2' +gem 'omniauth', '~> 2.1', '>= 2.1.1' gem "omniauth-twitter", "~> 1.4.0" +gem 'omniauth-github', '~> 2.0.0' +gem "omniauth-rails_csrf_protection" gem "haml-rails", "~> 2.0.1" gem "twitter-bootstrap-rails", "~> 5.0.0" gem "redcarpet", "~> 1.17.2" -gem "nokogiri", "~> 1.12.5" +gem 'nokogiri', '~> 1.16' + gem 'newrelic_rpm' -gem "activeadmin", "~> 2.9.0" +gem 'activeadmin', '~> 3.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '~> 1.9.2', require: false + group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] gem 'rspec-rails' - - end + group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. - gem 'web-console', '>= 4.1.0' + gem 'web-console', '~> 4.2', '>= 4.2.1' + + gem 'better_errors', '~> 2.10', '>= 2.10.1' # Display performance information such as SQL time and flame graphs for each request in your browser. # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md gem 'rack-mini-profiler', '~> 2.0' @@ -64,6 +77,7 @@ group :development do gem 'pry', '~> 0.14.2' end + group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 3.26' @@ -79,4 +93,5 @@ gem 'simplecov', require: false, group: :test # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] -gem 'mimemagic', github: 'mimemagicrb/mimemagic', ref: '01f92d86d15d85cfd0f20dabd025dcbd36a8a60f' + +gem 'mimemagic', github: 'mimemagicrb/mimemagic', ref: '01f92d86d15d85cfd0f20dabd025dcbd36a8a60f' \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock index 2fda62f..4020df6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -8,80 +8,101 @@ GIT GEM remote: https://rubygems.org/ specs: - actioncable (6.1.4.4) - actionpack (= 6.1.4.4) - activesupport (= 6.1.4.4) + actioncable (7.1.2) + actionpack (= 7.1.2) + activesupport (= 7.1.2) nio4r (~> 2.0) websocket-driver (>= 0.6.1) - actionmailbox (6.1.4.4) - actionpack (= 6.1.4.4) - activejob (= 6.1.4.4) - activerecord (= 6.1.4.4) - activestorage (= 6.1.4.4) - activesupport (= 6.1.4.4) + zeitwerk (~> 2.6) + actionmailbox (7.1.2) + actionpack (= 7.1.2) + activejob (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) mail (>= 2.7.1) - actionmailer (6.1.4.4) - actionpack (= 6.1.4.4) - actionview (= 6.1.4.4) - activejob (= 6.1.4.4) - activesupport (= 6.1.4.4) + net-imap + net-pop + net-smtp + actionmailer (7.1.2) + actionpack (= 7.1.2) + actionview (= 7.1.2) + activejob (= 7.1.2) + activesupport (= 7.1.2) mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 2.0) - actionpack (6.1.4.4) - actionview (= 6.1.4.4) - activesupport (= 6.1.4.4) - rack (~> 2.0, >= 2.0.9) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.2) + actionview (= 7.1.2) + activesupport (= 7.1.2) + nokogiri (>= 1.8.5) + racc + rack (>= 2.2.4) + rack-session (>= 1.0.1) rack-test (>= 0.6.3) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.0, >= 1.2.0) - actiontext (6.1.4.4) - actionpack (= 6.1.4.4) - activerecord (= 6.1.4.4) - activestorage (= 6.1.4.4) - activesupport (= 6.1.4.4) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.2) + actionpack (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) + globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (6.1.4.4) - activesupport (= 6.1.4.4) + actionview (7.1.2) + activesupport (= 7.1.2) builder (~> 3.1) - erubi (~> 1.4) - rails-dom-testing (~> 2.0) - rails-html-sanitizer (~> 1.1, >= 1.2.0) - activeadmin (2.9.0) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activeadmin (3.2.0) arbre (~> 1.2, >= 1.2.1) - formtastic (>= 3.1, < 5.0) - formtastic_i18n (~> 0.4) + formtastic (>= 3.1) + formtastic_i18n (>= 0.4) inherited_resources (~> 1.7) - jquery-rails (~> 4.2) - kaminari (~> 1.0, >= 1.2.1) - railties (>= 5.2, < 6.2) - ransack (~> 2.1, >= 2.1.1) - activejob (6.1.4.4) - activesupport (= 6.1.4.4) + jquery-rails (>= 4.2) + kaminari (>= 1.2.1) + railties (>= 6.1) + ransack (>= 4.0) + activejob (7.1.2) + activesupport (= 7.1.2) globalid (>= 0.3.6) - activemodel (6.1.4.4) - activesupport (= 6.1.4.4) - activerecord (6.1.4.4) - activemodel (= 6.1.4.4) - activesupport (= 6.1.4.4) - activestorage (6.1.4.4) - actionpack (= 6.1.4.4) - activejob (= 6.1.4.4) - activerecord (= 6.1.4.4) - activesupport (= 6.1.4.4) - marcel (~> 1.0.0) - mini_mime (>= 1.1.0) - activesupport (6.1.4.4) + activemodel (7.1.2) + activesupport (= 7.1.2) + activerecord (7.1.2) + activemodel (= 7.1.2) + activesupport (= 7.1.2) + timeout (>= 0.4.0) + activestorage (7.1.2) + actionpack (= 7.1.2) + activejob (= 7.1.2) + activerecord (= 7.1.2) + activesupport (= 7.1.2) + marcel (~> 1.0) + activesupport (7.1.2) + base64 + bigdecimal concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb i18n (>= 1.6, < 2) minitest (>= 5.1) + mutex_m tzinfo (~> 2.0) - zeitwerk (~> 2.3) addressable (2.8.0) public_suffix (>= 2.0.2, < 5.0) - arbre (1.4.0) - activesupport (>= 3.0.0, < 6.2) - ruby2_keywords (>= 0.0.2, < 1.0) + arbre (1.7.0) + activesupport (>= 3.0.0) + ruby2_keywords (>= 0.0.2) + base64 (0.2.0) bcrypt (3.1.20) + better_errors (2.10.1) + erubi (>= 1.0.0) + rack (>= 0.9.0) + rouge (>= 1.0.0) + bigdecimal (3.1.5) bindex (0.8.1) bootsnap (1.9.4) msgpack (~> 1.0) @@ -101,6 +122,7 @@ GEM coderay (1.1.3) commonjs (0.2.7) concurrent-ruby (1.2.2) + connection_pool (2.4.1) crass (1.0.6) database_cleaner (2.0.1) database_cleaner-active_record (~> 2.0.0) @@ -108,8 +130,8 @@ GEM activerecord (>= 5.a) database_cleaner-core (~> 2.0.0) database_cleaner-core (2.0.1) - date (3.3.3) - devise (4.7.3) + date (3.3.4) + devise (4.9.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0) @@ -123,6 +145,8 @@ GEM dotenv-rails (2.7.6) dotenv (= 2.7.6) railties (>= 3.2) + drb (2.2.0) + ruby2_keywords equalizer (0.0.11) erubi (1.12.0) erubis (2.7.0) @@ -137,11 +161,11 @@ GEM faraday (0.17.4) multipart-post (>= 1.2, < 3) ffi (1.15.5) - formtastic (4.0.0) - actionpack (>= 5.2.0) + formtastic (5.0.0) + actionpack (>= 6.0.0) formtastic_i18n (0.7.0) - globalid (1.0.0) - activesupport (>= 5.0) + globalid (1.2.1) + activesupport (>= 6.1) haml (5.2.2) temple (>= 0.8.0) tilt @@ -151,7 +175,7 @@ GEM haml (>= 4.0.6, < 6.0) html2haml (>= 1.0.1) railties (>= 5.1) - has_scope (0.8.0) + has_scope (0.8.2) actionpack (>= 5.2) activesupport (>= 5.2) hashie (5.0.0) @@ -171,18 +195,26 @@ GEM http_parser.rb (0.6.0) i18n (1.14.1) concurrent-ruby (~> 1.0) - inherited_resources (1.13.1) - actionpack (>= 5.2, < 7.1) - has_scope (~> 0.6) - railties (>= 5.2, < 7.1) - responders (>= 2, < 4) + image_processing (1.12.2) + mini_magick (>= 4.9.5, < 5) + ruby-vips (>= 2.0.17, < 3) + inherited_resources (1.14.0) + actionpack (>= 6.0) + has_scope (>= 0.6) + railties (>= 6.0) + responders (>= 2) + io-console (0.7.1) + irb (1.11.1) + rdoc + reline (>= 0.4.2) jbuilder (2.11.5) actionview (>= 5.0.0) activesupport (>= 5.0.0) - jquery-rails (4.4.0) + jquery-rails (4.6.0) rails-dom-testing (>= 1, < 3) railties (>= 4.2.0) thor (>= 0.14, < 2.0) + jwt (2.7.1) kaminari (1.2.2) activesupport (>= 4.1.0) kaminari-actionview (= 1.2.2) @@ -217,33 +249,57 @@ GEM memoizable (0.4.2) thread_safe (~> 0.3, >= 0.3.1) method_source (1.0.0) + mini_magick (4.12.0) mini_mime (1.1.5) - mini_portile2 (2.6.1) + mini_portile2 (2.8.5) minitest (5.19.0) msgpack (1.7.1) + multi_xml (0.6.0) multipart-post (2.1.1) + mutex_m (0.2.0) naught (1.1.0) - net-imap (0.3.7) + net-imap (0.4.9.1) date net-protocol net-pop (0.1.2) net-protocol - net-protocol (0.2.1) + net-protocol (0.2.2) timeout - net-smtp (0.3.3) + net-smtp (0.4.0.1) net-protocol newrelic_rpm (8.4.0) nio4r (2.5.8) - nokogiri (1.12.5) - mini_portile2 (~> 2.6.1) + nokogiri (1.16.0) + mini_portile2 (~> 2.8.2) + racc (~> 1.4) + nokogiri (1.16.0-x64-mingw-ucrt) + racc (~> 1.4) + nokogiri (1.16.0-x86_64-linux) racc (~> 1.4) oauth (0.5.8) - omniauth (1.9.2) + oauth2 (2.0.9) + faraday (>= 0.17.3, < 3.0) + jwt (>= 1.0, < 3.0) + multi_xml (~> 0.5) + rack (>= 1.2, < 4) + snaky_hash (~> 2.0) + version_gem (~> 1.1) + omniauth (2.1.1) hashie (>= 3.4.6) - rack (>= 1.6.2, < 3) + rack (>= 2.2.3) + rack-protection + omniauth-github (2.0.1) + omniauth (~> 2.0) + omniauth-oauth2 (~> 1.8) omniauth-oauth (1.2.0) oauth omniauth (>= 1.0, < 3) + omniauth-oauth2 (1.8.0) + oauth2 (>= 1.4, < 3) + omniauth (~> 2.0) + omniauth-rails_csrf_protection (1.0.1) + actionpack (>= 4.2) + omniauth (~> 2.0) omniauth-twitter (1.4.0) omniauth-oauth (~> 1.1) rack @@ -253,6 +309,8 @@ GEM pry (0.14.2) coderay (~> 1.1) method_source (~> 1.0) + psych (5.1.2) + stringio public_suffix (4.0.6) puma (5.6.1) nio4r (~> 2.0) @@ -260,51 +318,65 @@ GEM rack (2.2.8) rack-mini-profiler (2.3.3) rack (>= 1.2.0) + rack-protection (3.1.0) + rack (~> 2.2, >= 2.2.4) rack-proxy (0.7.2) rack + rack-session (1.0.2) + rack (< 3) rack-test (2.1.0) rack (>= 1.3) - rails (6.1.4.4) - actioncable (= 6.1.4.4) - actionmailbox (= 6.1.4.4) - actionmailer (= 6.1.4.4) - actionpack (= 6.1.4.4) - actiontext (= 6.1.4.4) - actionview (= 6.1.4.4) - activejob (= 6.1.4.4) - activemodel (= 6.1.4.4) - activerecord (= 6.1.4.4) - activestorage (= 6.1.4.4) - activesupport (= 6.1.4.4) + rackup (1.0.0) + rack (< 3) + webrick + rails (7.1.2) + actioncable (= 7.1.2) + actionmailbox (= 7.1.2) + actionmailer (= 7.1.2) + actionpack (= 7.1.2) + actiontext (= 7.1.2) + actionview (= 7.1.2) + activejob (= 7.1.2) + activemodel (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) bundler (>= 1.15.0) - railties (= 6.1.4.4) - sprockets-rails (>= 2.0.0) + railties (= 7.1.2) rails-dom-testing (2.2.0) activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.5.0) - loofah (~> 2.19, >= 2.19.1) - railties (6.1.4.4) - actionpack (= 6.1.4.4) - activesupport (= 6.1.4.4) - method_source - rake (>= 0.13) - thor (~> 1.0) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.1.2) + actionpack (= 7.1.2) + activesupport (= 7.1.2) + irb + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) rake (13.0.6) - ransack (2.5.0) - activerecord (>= 5.2.4) - activesupport (>= 5.2.4) + ransack (4.1.1) + activerecord (>= 6.1.5) + activesupport (>= 6.1.5) i18n rb-fsevent (0.11.0) rb-inotify (0.10.1) ffi (~> 1.0) + rdoc (6.6.2) + psych (>= 4.0.0) redcarpet (1.17.2) regexp_parser (2.2.0) + reline (0.4.2) + io-console (~> 0.5) responders (3.0.1) actionpack (>= 5.0) railties (>= 5.0) rexml (3.2.5) + rouge (4.2.0) rspec-core (3.12.2) rspec-support (~> 3.12.0) rspec-expectations (3.12.3) @@ -322,6 +394,8 @@ GEM rspec-mocks (~> 3.12) rspec-support (~> 3.12) rspec-support (3.12.1) + ruby-vips (2.2.0) + ffi (~> 1.12) ruby2_keywords (0.0.5) ruby_parser (3.18.1) sexp_processor (~> 4.16) @@ -353,6 +427,9 @@ GEM simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.3) + snaky_hash (2.0.1) + hashie + version_gem (~> 1.1, >= 1.1.1) spring (4.0.0) sprockets (3.7.2) concurrent-ruby (~> 1.0) @@ -361,11 +438,12 @@ GEM actionpack (>= 5.2) activesupport (>= 5.2) sprockets (>= 3.0.0) + stringio (3.1.0) temple (0.8.2) thor (1.2.2) thread_safe (0.3.6) tilt (2.0.10) - timeout (0.4.0) + timeout (0.4.1) turbolinks (5.2.1) turbolinks-source (~> 5.2) turbolinks-source (5.2.0) @@ -392,9 +470,10 @@ GEM unf (0.1.4) unf_ext unf_ext (0.0.8) + version_gem (1.1.3) warden (1.2.9) rack (>= 2.0.9) - web-console (4.2.0) + web-console (4.2.1) actionview (>= 6.0.0) activemodel (>= 6.0.0) bindex (>= 0.4.0) @@ -408,7 +487,8 @@ GEM rack-proxy (>= 0.6.1) railties (>= 5.2) semantic_range (>= 2.3.0) - websocket-driver (0.7.5) + webrick (1.8.1) + websocket-driver (0.7.6) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) xpath (3.2.0) @@ -421,28 +501,32 @@ PLATFORMS x86_64-linux DEPENDENCIES - activeadmin (~> 2.9.0) + activeadmin (~> 3.2) + better_errors (~> 2.10, >= 2.10.1) bootsnap (~> 1.9.2) byebug capybara (>= 3.26) database_cleaner - devise (~> 4.7.3) + devise (~> 4.9, >= 4.9.2) dotenv-rails (~> 2.7, >= 2.7.4) factory_bot_rails faker (~> 2.19) haml-rails (~> 2.0.1) + image_processing (~> 1.2) jbuilder (~> 2.7) listen (~> 3.3) mimemagic! newrelic_rpm - nokogiri (~> 1.12.5) - omniauth (~> 1.9.0) + nokogiri (~> 1.16) + omniauth (~> 2.1, >= 2.1.1) + omniauth-github (~> 2.0.0) + omniauth-rails_csrf_protection omniauth-twitter (~> 1.4.0) pg pry (~> 0.14.2) puma (~> 5.0) rack-mini-profiler (~> 2.0) - rails (~> 6.1.4.4) + rails (~> 7.1.2) redcarpet (~> 1.17.2) rspec-rails sass-rails (>= 6) @@ -455,7 +539,7 @@ DEPENDENCIES twitter (~> 6.2.0) twitter-bootstrap-rails (~> 5.0.0) tzinfo-data - web-console (>= 4.1.0) + web-console (~> 4.2, >= 4.2.1) webdrivers webpacker (~> 5.0) diff --git a/app/admin/external_identities.rb b/app/admin/external_identities.rb new file mode 100644 index 0000000..d1fb562 --- /dev/null +++ b/app/admin/external_identities.rb @@ -0,0 +1,26 @@ +ActiveAdmin.register ExternalIdentity do + + # See permitted parameters documentation: + # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters + # + # Uncomment all parameters which should be permitted for assignment + # + permit_params :user_id, :provider, :uid, :oauth, :handle, :description, :website, :name, :email, :image + # + # or + # + # permit_params do + # permitted = [:user_id, :provider, :uid, :oauth, :handle, :description, :website, :name, :email, :image] + # permitted << :other if params[:action] == 'create' && current_user.admin? + # permitted + # end + + index do + column :id + column :name + column :handle + actions + end + + +end diff --git a/app/admin/user.rb b/app/admin/user.rb index dfb3196..e674569 100644 --- a/app/admin/user.rb +++ b/app/admin/user.rb @@ -2,7 +2,6 @@ index do column :id - column :twitter_handle column :name column :last_sign_in_at column :created_at @@ -10,6 +9,7 @@ column :letters_count do |user| user.letters.count end + column :external_identities column :likes do |user| user.likes.count end diff --git a/app/controllers/users/omniauth_callbacks_controller.rb b/app/controllers/users/omniauth_callbacks_controller.rb index c177469..f8beac6 100644 --- a/app/controllers/users/omniauth_callbacks_controller.rb +++ b/app/controllers/users/omniauth_callbacks_controller.rb @@ -14,4 +14,16 @@ def twitter redirect_to root_path end end + + def github + @user = User.find_for_github_oauth(request.env["omniauth.auth"]) + if @user.persisted? + flash[:notice] = t("flash.successful_sign_in_github") + sign_in_and_redirect @user, :event => :authentication + else + session["devise.github_data"] = request.env["omniauth.auth"] + flash[:error] = t('flash.error_signing_in') + redirect_to root_path + end + end end \ No newline at end of file diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 41bbac6..9230d13 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,27 +1,18 @@ module ApplicationHelper - def get_twitter_image(user) - image_tag image_for_twitter_handle(user), onerror: 'this.error=null;this.src="https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"' + def get_profile_image(user) + image_tag image_for_handle(user), onerror: 'this.error=null;this.src="https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"' end - private - RubyConfIndia2023 = Date.parse('2023-08-26') + private - def image_for_twitter_handle(user) - if user.updated_at.after?(RubyConfIndia2023) && user.image.present? - # this is a quick workaround for being unable to fetch images via Cloudinary for new twitter sign_ins due to Twitter API policy changes. - # one problem with continuing to use this long term would be: - # - if a user changes their profile picture, the url saved on our model will become invalid - # we do have a fallback to default image in place, but it's not ideal - # - As an improvement, we can try to cache it (more like a permanent snapshot until their next login) - # - But a proper solution would be to fetch their current profile picture via a service or to periodically refresh it ourself - user.image + def image_for_handle(user) + if user.twitter_identity.present? && user.twitter_identity.profile_image.attached? + url_for(user.twitter_identity.profile_image) + elsif user.github_identity.present? && user.github_identity.profile_image.attached? + url_for(user.github_identity.profile_image) else - cloudinary_image_url(user.twitter_handle) + 'https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png' end end - - def cloudinary_image_url(twitter_handle) - "https://res.cloudinary.com/#{ENV['CLOUDINARY_HANDLE']}/image/twitter_name/#{twitter_handle}.jpg" - end end diff --git a/app/models/external_identity.rb b/app/models/external_identity.rb index 65a1b14..14194a5 100644 --- a/app/models/external_identity.rb +++ b/app/models/external_identity.rb @@ -4,4 +4,6 @@ class ExternalIdentity < ActiveRecord::Base validates :provider, uniqueness: { scope: :user_id, message: 'has already been taken for this user' } validates :provider, presence: true validates :uid, uniqueness: { scope: :provider, message: 'has already been taken for this provider' } + + has_one_attached :profile_image end diff --git a/app/models/user.rb b/app/models/user.rb index a77aa3b..d1dfb04 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,41 +1,95 @@ +require 'open-uri' + + class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :registerable, :rememberable, :trackable, :database_authenticatable, :omniauthable, - omniauth_providers: [:twitter] + omniauth_providers: [:github, :twitter] + # Setup accessible (or protected) attributes for your model # attr_accessible :remember_me, :name, :twitter_handle, :twitter_description, :twitter_description, :twitter_oauth, :website, :image + has_many :letters has_many :likes has_many :external_identities + has_one :twitter_identity, -> { where provider: 'twitter' }, class_name: "ExternalIdentity" + has_one :github_identity, -> { where provider: 'github' }, class_name: "ExternalIdentity" class << self def find_for_twitter_oauth(auth) - user = User.where(uid: auth.uid, provider: auth.provider).first - + user = User.joins(:external_identities) + .where(external_identities: { uid: auth.uid, provider: auth.provider }) + .first if user - profile_image_url = auth["info"]["image"] - user.update(image: profile_image_url) if profile_image_url.present? - - # TODO: handle exceptions later. For now, continue to sign in the user, regardless of whether image url is saved + user.update(name: auth.info.name) + user.twitter_identity.update( + handle: auth.info.nickname, + description: auth.info.description, + website: auth.info.urls.Website, + oauth: auth.credentials.token, + name: auth.info.name + ) + user.update_profile_image(auth.info.image) user else - User.create( - uid: auth["uid"], - provider: auth["provider"], - name: auth["info"]["name"], - twitter_handle: auth["info"]["nickname"], - twitter_description: auth["info"]["description"], - website: (auth["info"]["urls"]["Website"] rescue nil), - twitter_oauth: auth["credentials"]["token"], - image: auth["info"]["image"] + user = User.create(name: auth.info.name) + user.external_identities.create( + uid: auth.uid, + provider: auth.provider, + handle: auth.info.nickname, + name: auth.info.name, + description: auth.info.description, + website: auth.info.urls.Website, + oauth: auth.credentials.token ) + user.update_profile_image(auth.info.image) + user end + end + def find_for_github_oauth(auth) + data = auth.info + user = User.joins(:external_identities) + .where(external_identities: { uid: auth.uid, provider: auth.provider }) + .first + if user + user.update(name: auth.info.name, email: auth.info.email) + user.github_identity.update( + handle: auth.extra.raw_info.login, + name: data['name'], + email: data['email'] + ) + user.update_profile_image(auth.extra.raw_info.avatar_url) + user + else + user = User.create(name: auth.info.name, email: auth.info.email) + user.external_identities.create( + uid: auth.uid, + provider: auth.provider, + handle: auth.extra.raw_info.login, + name: data.name, + email: data.email + ) + user.update_profile_image(auth.extra.raw_info.avatar_url) + user + end end + end + def update_profile_image(image_url) + if twitter_identity + twitter_identity.profile_image.attach(io: open_uri(image_url), filename: "#{twitter_identity.handle}.jpg") + elsif github_identity + github_identity.profile_image.attach(io: open_uri(image_url), filename: "#{github_identity.handle}.jpg") + end end + private + + def open_uri(url) + URI.parse(url).open + end end diff --git a/app/views/home/index.html.haml b/app/views/home/index.html.haml index d159535..1ae49bc 100644 --- a/app/views/home/index.html.haml +++ b/app/views/home/index.html.haml @@ -10,6 +10,7 @@ -else = link_to 'Submit', '#', class: 'btn primary pull-right disabled', rel: 'popover', data: {title: 'Oops!!', content: 'You need to login first to submit!!'} + %hr .row .span8 @@ -25,20 +26,28 @@ - else = link_to 'UpVote', '#', class: 'btn', rel: 'popover', data: {content: "You need to login first to Like it. ", title: 'Oops !!'} + .personalInfo.pull-right .pull-right.names = letter.user.name %br %strong - %a{ href: "https://www.twitter.com/#{letter.user.twitter_handle}", target: "_blank" } - = "@#{letter.user.twitter_handle}" + - if letter.user.twitter_identity.present? + - twitter_identity = letter.user.twitter_identity + %a{ href: "https://www.twitter.com/#{twitter_identity.handle}", target: "_blank" } + = "@#{twitter_identity.handle}" + - if letter.user.github_identity.present? + - github_identity = letter.user.github_identity + %a{ href: "https://www.github.com/#{github_identity.handle}", target: "_blank" } + = "@#{github_identity.handle}" %br %small.timeAgo = link_to letter_path(letter) do = time_ago_in_words letter.created_at ago .pull-right.thumbnail.imageWrapper{ style: 'max-height: 50px; max-width: 50px' } - = get_twitter_image(letter.user) + = get_profile_image(letter.user) + -# TODO refactor this - unless letter.user_id == 43 @@ -50,10 +59,16 @@ %br %div %div.pull-left - %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", - href: "https://twitter.com/share", class: 'pull-right', - "data-text": "Here is @#{letter.user.twitter_handle}\'s reason to love Ruby. - #{letter_url(letter)}\n Tell us yours at"} - + - if letter.user.twitter_identity.present? + - twitter_identity = letter.user.twitter_identity + %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", "data-url": "#{root_url}", + href: "https://twitter.com/share", class: 'pull-right', + "data-text": "Here is @#{twitter_identity.handle}\'s reason to love Ruby. - #{letter_url(letter)}\n Tell us yours at" } + - if letter.user.github_identity.present? + - github_identity = letter.user.github_identity + %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", "data-url": "#{root_url}", + href: "https://twitter.com/share", class: 'pull-right', + "data-text": "Here is @#{github_identity.handle}\'s reason to love Ruby. - #{letter_url(letter)}\n Tell us yours at" } .clr :javascript !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml index 190eb1d..a762951 100644 --- a/app/views/layouts/application.html.haml +++ b/app/views/layouts/application.html.haml @@ -11,6 +11,7 @@ %meta{:content => "Why Love Ruby", :property => "og:site_name"}/ %meta{:content => "Why Love Ruby", :itemprop => "name"} + %title= "I Love Ruby because .." = csrf_meta_tags / Le HTML5 shim, for IE6-8 support of HTML elements @@ -32,6 +33,8 @@ %script{:src => "//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"} + + %body .navbar.navbar-fixed-top.navbar-inverse .navbar-inner @@ -47,19 +50,25 @@ %li %span.welcome Welcome, - = current_user.twitter_handle + - if current_user.twitter_identity.present? + = current_user.twitter_identity&.handle + - if current_user.github_identity.present? + = current_user.github_identity&.handle | = link_to "Logout", destroy_user_session_path, method: 'delete' - else - %li= link_to 'Login with Twitter' , user_twitter_omniauth_authorize_path + %li= link_to 'Login with Twitter' , user_twitter_omniauth_authorize_path, method: :post + %li= link_to 'Login with GitHub' , user_github_omniauth_authorize_path, method: :post %li=# link_to "Link 1", "/path1" %li=# link_to "Link 2", "/path2" %li=# link_to "Link 3", "/path3" + %div{:style => "position:absolute; top:0; right:0;z-index:1040"} = link_to 'https://github.com/rtdp/myloveruby', target: '_blank' do %img{:alt => "Beta Version", :border => "0", :src => "/forkme_right_red.png"} + .container .row .span12 @@ -107,15 +116,21 @@ %tr %td .thumbnail.pull-left{ style: 'max-height: 50px; max-width: 50px' } - = get_twitter_image(l.user) + = get_profile_image(l.user) .info.pull-left - = truncate("#{l.user.name} (#{l.user.twitter_handle})", length: 27) + - if l.user.twitter_identity.present? + - twitter_identity = l.user.twitter_identity + = truncate("#{twitter_identity.name} (#{twitter_identity.handle})", length: 27) + - if l.user.github_identity.present? + - github_identity = l.user.github_identity + = truncate("#{github_identity.name} (#{github_identity.handle})", length: 27) %br %small.timeAgo = link_to letter_path(l) do = time_ago_in_words l.created_at ago + %footer %hr %p @@ -132,6 +147,7 @@ _gaq.push(['_setAccount', 'UA-10763136-15']); _gaq.push(['_trackPageview']); + (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; diff --git a/app/views/letters/show.html.haml b/app/views/letters/show.html.haml index 12f0b37..ceb5ba9 100644 --- a/app/views/letters/show.html.haml +++ b/app/views/letters/show.html.haml @@ -15,22 +15,35 @@ = @letter.user.name %br %strong - %a{ href: "https://www.twitter.com/#{@letter.user.twitter_handle}", target: "_blank" } - = "@#{@letter.user.twitter_handle}" + - if @letter.user.twitter_identity.present? + - twitter_identity = @letter.user.twitter_identity + %a{ href: "https://www.twitter.com/#{twitter_identity.handle}", target: "_blank" } + = "@#{twitter_identity.handle}" + - if @letter.user.github_identity.present? + - github_identity = @letter.user.github_identity + %a{ href: "https://www.github.com/#{github_identity.handle}", target: "_blank" } + = "@#{github_identity.handle}" %br %small.timeAgo = link_to letter_path(@letter) do = time_ago_in_words @letter.created_at ago .pull-right.thumbnail.imageWrapper{ style: 'max-height: 50px; max-width: 50px' } - = get_twitter_image(@letter.user) + = get_profile_image(@letter.user) = markdown(@letter.description) %br %div %div.pull-left - %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", "data-url": "#{root_url}", + - if @letter.user.twitter_identity.present? + - twitter_identity = @letter.user.twitter_identity + %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", "data-url": "#{root_url}", href: "https://twitter.com/share", class: 'pull-right', - "data-text": "Here is @#{@letter.user.twitter_handle}\'s reason to love Ruby. - #{letter_url(@letter)}\n Tell us yours at" } + "data-text": "Here is @#{twitter_identity.handle}\'s reason to love Ruby. - #{letter_url(@letter)}\n Tell us yours at" } + - if @letter.user.github_identity.present? + - github_identity = @letter.user.github_identity + %a.twitter-share-button{"data-size": "large", "data-hashtags": "whyloveruby", "data-url": "#{root_url}", + href: "https://twitter.com/share", class: 'pull-right', + "data-text": "Here is @#{github_identity.handle}\'s reason to love Ruby. - #{letter_url(@letter)}\n Tell us yours at" } .clr :javascript !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); @@ -43,4 +56,4 @@ method: :delete, data: {confirm: "Are you sure?"} %br - %hr + %hr \ No newline at end of file diff --git a/bin/rails b/bin/rails index 40b071e..7bcc36e 100755 --- a/bin/rails +++ b/bin/rails @@ -1,5 +1,4 @@ -#!/usr/bin/env ruby -load File.expand_path("spring", __dir__) -APP_PATH = File.expand_path('../config/application', __dir__) -require_relative '../config/boot' -require 'rails/commands' +#!/usr/bin/env ruby.exe +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake index a5c86fc..01f7fc0 100755 --- a/bin/rake +++ b/bin/rake @@ -1,5 +1,4 @@ -#!/usr/bin/env ruby -load File.expand_path("spring", __dir__) -require_relative '../config/boot' -require 'rake' +#!/usr/bin/env ruby.exe +require_relative "../config/boot" +require "rake" Rake.application.run diff --git a/bin/setup b/bin/setup index 97dc988..95077f1 100755 --- a/bin/setup +++ b/bin/setup @@ -1,8 +1,8 @@ -#!/usr/bin/env ruby -require 'fileutils' +#!/usr/bin/env ruby.exe +require "fileutils" # path to your application root. -APP_ROOT = File.expand_path('..', __dir__) +APP_ROOT = File.expand_path("..", __dir__) def system!(*args) system(*args) || abort("\n== Command #{args} failed ==") @@ -13,24 +13,24 @@ FileUtils.chdir APP_ROOT do # This script is idempotent, so that you can run it at any time and get an expectable outcome. # Add necessary setup steps to this file. - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") # Install JavaScript dependencies system! 'bin/yarn' # puts "\n== Copying sample files ==" - # unless File.exist?('config/database.yml') - # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" # end puts "\n== Preparing database ==" - system! 'bin/rails db:prepare' + system! "bin/rails db:prepare" puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' + system! "bin/rails log:clear tmp:clear" puts "\n== Restarting application server ==" - system! 'bin/rails restart' + system! "bin/rails restart" end diff --git a/config/application.rb b/config/application.rb index 7839cc3..c948e21 100644 --- a/config/application.rb +++ b/config/application.rb @@ -11,6 +11,11 @@ class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.0 + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w(assets tasks)) + # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files @@ -18,61 +23,6 @@ class Application < Rails::Application # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") - # Activate observers that should always be running. - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer - - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. - # config.time_zone = 'Central Time (US & Canada)' - - # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] - # config.i18n.default_locale = :de - - # Configure the default encoding used in templates for Ruby 1.9. - config.encoding = "utf-8" - - # Configure sensitive parameters which will be filtered from the log file. - config.filter_parameters += [:password] - - # Use SQL instead of Active Record's schema dumper when creating the database. - # This is necessary if your schema can't be completely dumped by the schema dumper, - # like if you have constraints or database-specific column types - # config.active_record.schema_format = :sql - - # Enforce whitelist mode for mass assignment. - # This will create an empty whitelist of attributes available for mass-assignment for all models - # in your app. As such, your models will need to explicitly whitelist or blacklist accessible - # parameters by using an attr_accessible or attr_protected declaration. - # config.active_record.whitelist_attributes = true - - # Enable the asset pipeline - config.assets.enabled = true - - # Version of your assets, change this if you want to expire all your assets - config.assets.version = '1.0' - - # heroku fix - config.assets.initialize_on_precompile = false - - # exception notification - - # if Rails.env.production? - # Myloveruby::Application.config.middleware.use ExceptionNotifier, - # :email_prefix => "[My Love Ruby] ", - # :sender_address => %{"notifier" }, - # :exception_recipients => %w{rtdp@rainingclouds.com} - # end - - - config.action_mailer.delivery_method = :smtp - config.action_mailer.smtp_settings = { - :address => "smtp.gmail.com", - :port => 587, - :domain => 'smtp.gmail.com', - :user_name => 'droid@rainingclouds.com', - :password => 'droidcloudhere', - :authentication => 'plain', - :enable_starttls_auto => true - } + config.active_support.cache_format_version = 7.1 end end diff --git a/config/boot.rb b/config/boot.rb index b9e460c..988a5dd 100644 --- a/config/boot.rb +++ b/config/boot.rb @@ -1,4 +1,4 @@ -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) -require 'bundler/setup' # Set up gems listed in the Gemfile. -require 'bootsnap/setup' # Speed up boot time by caching expensive operations. +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/environment.rb b/config/environment.rb index 426333b..cac5315 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,5 +1,5 @@ # Load the Rails application. -require_relative 'application' +require_relative "application" # Initialize the Rails application. Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb index 5b908d3..e07a304 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/integer/time' +require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -6,7 +6,7 @@ # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. - config.cache_classes = false + config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false @@ -14,15 +14,21 @@ # Show full error reports. config.consider_all_requests_local = true + config.web_console.permissions = '127.0.0.1' + + + # Enable server timing + config.server_timing = true + # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. - if Rails.root.join('tmp', 'caching-dev.txt').exist? + if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{2.days.to_i}" + "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false @@ -73,4 +79,7 @@ # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true end diff --git a/config/environments/production.rb b/config/environments/production.rb index bdf906a..05118c7 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/integer/time' +require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -13,11 +13,11 @@ config.eager_load = true # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false + config.consider_all_requests_local = false config.action_controller.perform_caching = true - # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] - # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment + # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since @@ -25,42 +25,51 @@ config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. - # config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.asset_host = 'http://assets.example.com' + # config.asset_host = "http://assets.example.com" # Specifies the header that your server uses for sending files. - # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache - # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil - # config.action_cable.url = 'wss://example.com/cable' - # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. + # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - # config.force_ssl = true + config.force_ssl = true - # Include generic and useful information about system operation, but avoid logging too much - # information to avoid inadvertent exposure of personally identifiable information (PII). - config.log_level = :info + # Log to STDOUT by default + config.logger = ActiveSupport::Logger.new(STDOUT) + .tap { |logger| logger.formatter = ::Logger::Formatter.new } + .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] + # Info include generic and useful information about system operation, but avoids logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). If you + # want to log everything, set the level to "debug". + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). - # config.active_job.queue_adapter = :resque + # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "myloveruby_production" config.action_mailer.perform_caching = false @@ -98,24 +107,11 @@ # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false - # Inserts middleware to perform automatic connection switching. - # The `database_selector` hash is used to pass options to the DatabaseSelector - # middleware. The `delay` is used to determine how long to wait after a write - # to send a subsequent read to the primary. - # - # The `database_resolver` class is used by the middleware to determine which - # database is appropriate to use based on the time delay. - # - # The `database_resolver_context` class is used by the middleware to set - # timestamps for the last write to the primary. The resolver uses the context - # class timestamps to determine how long to wait before reading from the - # replica. - # - # By default Rails will store a last write timestamp in the session. The - # DatabaseSelector middleware is designed as such you can define your own - # strategy for connection switching and pass that into the middleware through - # these configuration options. - # config.active_record.database_selector = { delay: 2.seconds } - # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver - # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end diff --git a/config/environments/test.rb b/config/environments/test.rb index 83a40ae..8a7ff89 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -18,16 +18,16 @@ # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + "Cache-Control" => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. - config.consider_all_requests_local = true + config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store - # Raise exceptions instead of rendering exception templates. - config.action_dispatch.show_exceptions = false + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false @@ -56,4 +56,7 @@ # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true end diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 4b828e8..19f51aa 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -1,7 +1,7 @@ # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = '1.0' +Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb index 35d0f26..b3076b3 100644 --- a/config/initializers/content_security_policy.rb +++ b/config/initializers/content_security_policy.rb @@ -1,30 +1,25 @@ # Be sure to restart your server when you modify this file. -# Define an application-wide content security policy -# For further information see the following documentation -# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header -# Rails.application.config.content_security_policy do |policy| -# policy.default_src :self, :https -# policy.font_src :self, :https, :data -# policy.img_src :self, :https, :data -# policy.object_src :none -# policy.script_src :self, :https -# policy.style_src :self, :https -# # If you are using webpack-dev-server then specify webpack-dev-server host -# policy.connect_src :self, :https, "http://localhost:3035", "ws://localhost:3035" if Rails.env.development? - -# # Specify URI for violation reports -# # policy.report_uri "/csp-violation-report-endpoint" +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true # end - -# If you are using UJS then enable automatic nonce generation -# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } - -# Set the nonce only to specific directives -# Rails.application.config.content_security_policy_nonce_directives = %w(script-src) - -# Report CSP violations to a specified URI -# For further information see the following documentation: -# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only -# Rails.application.config.content_security_policy_report_only = true diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb index 3b1c1b5..0c5dd99 100644 --- a/config/initializers/cors.rb +++ b/config/initializers/cors.rb @@ -1,15 +1,15 @@ # Be sure to restart your server when you modify this file. # Avoid CORS issues when API is called from the frontend app. -# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests. # Read more: https://github.com/cyu/rack-cors # Rails.application.config.middleware.insert_before 0, Rack::Cors do # allow do -# origins 'example.com' +# origins "example.com" # -# resource '*', +# resource "*", # headers: :any, # methods: [:get, :post, :put, :patch, :delete, :options, :head] # end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index d1b82fe..947768f 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -211,6 +211,7 @@ # 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' + config.omniauth :github, ENV['GITHUB_CLIENT_ID'], ENV['GITHUB_CLIENT_SECRET_KEY'], scope: 'user:email' config.omniauth :twitter, ENV['TWITTER_CONSUMER_KEY'], ENV['TWITTER_CONSUMER_SECRET'], { secure_image_url: 'true', image_size: 'original' } diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb index e7b628e..017f495 100644 --- a/config/initializers/filter_parameter_logging.rb +++ b/config/initializers/filter_parameter_logging.rb @@ -1,6 +1,8 @@ # Be sure to restart your server when you modify this file. -# Configure sensitive parameters which will be filtered from the log file. +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :password, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb index ac033bf..3860f65 100644 --- a/config/initializers/inflections.rb +++ b/config/initializers/inflections.rb @@ -4,13 +4,13 @@ # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.plural /^(ox)$/i, '\1en' -# inflect.singular /^(ox)en/i, '\1' -# inflect.irregular 'person', 'people' +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.acronym 'RESTful' +# inflect.acronym "RESTful" # end diff --git a/config/initializers/new_framework_defaults_7_1.rb b/config/initializers/new_framework_defaults_7_1.rb new file mode 100644 index 0000000..e18bbf3 --- /dev/null +++ b/config/initializers/new_framework_defaults_7_1.rb @@ -0,0 +1,283 @@ +# Be sure to restart your server when you modify this file. +# +# This file eases your Rails 7.1 framework defaults upgrade. +# +# Uncomment each configuration one by one to switch to the new default. +# Once your application is ready to run with all new defaults, you can remove +# this file and set the `config.load_defaults` to `7.1`. +# +# Read the Guide for Upgrading Ruby on Rails for more info on each option. +# https://guides.rubyonrails.org/upgrading_ruby_on_rails.html + +### +# No longer add autoloaded paths into `$LOAD_PATH`. This means that you won't be able +# to manually require files that are managed by the autoloader, which you shouldn't do anyway. +# +# This will reduce the size of the load path, making `require` faster if you don't use bootsnap, or reduce the size +# of the bootsnap cache if you use it. +#++ +# Rails.application.config.add_autoload_paths_to_load_path = false + +### +# Remove the default X-Download-Options headers since it is used only by Internet Explorer. +# If you need to support Internet Explorer, add back `"X-Download-Options" => "noopen"`. +#++ +# Rails.application.config.action_dispatch.default_headers = { +# "X-Frame-Options" => "SAMEORIGIN", +# "X-XSS-Protection" => "0", +# "X-Content-Type-Options" => "nosniff", +# "X-Permitted-Cross-Domain-Policies" => "none", +# "Referrer-Policy" => "strict-origin-when-cross-origin" +# } + +### +# Do not treat an `ActionController::Parameters` instance +# as equal to an equivalent `Hash` by default. +#++ +# Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality = false + +### +# Active Record Encryption now uses SHA-256 as its hash digest algorithm. +# +# There are 3 scenarios to consider. +# +# 1. If you have data encrypted with previous Rails versions, and you have +# +config.active_support.key_generator_hash_digest_class+ configured as SHA1 (the default +# before Rails 7.0), you need to configure SHA-1 for Active Record Encryption too: +#++ +# Rails.application.config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA1 +# +# 2. If you have +config.active_support.key_generator_hash_digest_class+ configured as SHA256 (the new default +# in 7.0), then you need to configure SHA-256 for Active Record Encryption: +#++ +# Rails.application.config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA256 +# +# 3. If you don't currently have data encrypted with Active Record encryption, you can disable this setting to +# configure the default behavior starting 7.1+: +#++ +# Rails.application.config.active_record.encryption.support_sha1_for_non_deterministic_encryption = false + +### +# No longer run after_commit callbacks on the first of multiple Active Record +# instances to save changes to the same database row within a transaction. +# Instead, run these callbacks on the instance most likely to have internal +# state which matches what was committed to the database, typically the last +# instance to save. +#++ +# Rails.application.config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction = false + +### +# Configures SQLite with a strict strings mode, which disables double-quoted string literals. +# +# SQLite has some quirks around double-quoted string literals. +# It first tries to consider double-quoted strings as identifier names, but if they don't exist +# it then considers them as string literals. Because of this, typos can silently go unnoticed. +# For example, it is possible to create an index for a non existing column. +# See https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted for more details. +#++ +# Rails.application.config.active_record.sqlite3_adapter_strict_strings_by_default = true + +### +# Disable deprecated singular associations names. +#++ +# Rails.application.config.active_record.allow_deprecated_singular_associations_name = false + +### +# Enable the Active Job `BigDecimal` argument serializer, which guarantees +# roundtripping. Without this serializer, some queue adapters may serialize +# `BigDecimal` arguments as simple (non-roundtrippable) strings. +# +# When deploying an application with multiple replicas, old (pre-Rails 7.1) +# replicas will not be able to deserialize `BigDecimal` arguments from this +# serializer. Therefore, this setting should only be enabled after all replicas +# have been successfully upgraded to Rails 7.1. +#++ +# Rails.application.config.active_job.use_big_decimal_serializer = true + +### +# Specify if an `ArgumentError` should be raised if `Rails.cache` `fetch` or +# `write` are given an invalid `expires_at` or `expires_in` time. +# Options are `true`, and `false`. If `false`, the exception will be reported +# as `handled` and logged instead. +#++ +# Rails.application.config.active_support.raise_on_invalid_cache_expiration_time = true + +### +# Specify whether Query Logs will format tags using the SQLCommenter format +# (https://open-telemetry.github.io/opentelemetry-sqlcommenter/), or using the legacy format. +# Options are `:legacy` and `:sqlcommenter`. +#++ +# Rails.application.config.active_record.query_log_tags_format = :sqlcommenter + +### +# Specify the default serializer used by `MessageEncryptor` and `MessageVerifier` +# instances. +# +# The legacy default is `:marshal`, which is a potential vector for +# deserialization attacks in cases where a message signing secret has been +# leaked. +# +# In Rails 7.1, the new default is `:json_allow_marshal` which serializes and +# deserializes with `ActiveSupport::JSON`, but can fall back to deserializing +# with `Marshal` so that legacy messages can still be read. +# +# In Rails 7.2, the default will become `:json` which serializes and +# deserializes with `ActiveSupport::JSON` only. +# +# Alternatively, you can choose `:message_pack` or `:message_pack_allow_marshal`, +# which serialize with `ActiveSupport::MessagePack`. `ActiveSupport::MessagePack` +# can roundtrip some Ruby types that are not supported by JSON, and may provide +# improved performance, but it requires the `msgpack` gem. +# +# For more information, see +# https://guides.rubyonrails.org/v7.1/configuring.html#config-active-support-message-serializer +# +# If you are performing a rolling deploy of a Rails 7.1 upgrade, wherein servers +# that have not yet been upgraded must be able to read messages from upgraded +# servers, first deploy without changing the serializer, then set the serializer +# in a subsequent deploy. +#++ +# Rails.application.config.active_support.message_serializer = :json_allow_marshal + +### +# Enable a performance optimization that serializes message data and metadata +# together. This changes the message format, so messages serialized this way +# cannot be read by older versions of Rails. However, messages that use the old +# format can still be read, regardless of whether this optimization is enabled. +# +# To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have +# not yet been upgraded must be able to read messages from upgraded servers, +# leave this optimization off on the first deploy, then enable it on a +# subsequent deploy. +#++ +# Rails.application.config.active_support.use_message_serializer_for_metadata = true + +### +# Set the maximum size for Rails log files. +# +# `config.load_defaults 7.1` does not set this value for environments other than +# development and test. +#++ +# if Rails.env.local? +# Rails.application.config.log_file_size = 100 * 1024 * 1024 +# end + +### +# Enable raising on assignment to attr_readonly attributes. The previous +# behavior would allow assignment but silently not persist changes to the +# database. +#++ +# Rails.application.config.active_record.raise_on_assign_to_attr_readonly = true + +### +# Enable validating only parent-related columns for presence when the parent is mandatory. +# The previous behavior was to validate the presence of the parent record, which performed an extra query +# to get the parent every time the child record was updated, even when parent has not changed. +#++ +# Rails.application.config.active_record.belongs_to_required_validates_foreign_key = false + +### +# Enable precompilation of `config.filter_parameters`. Precompilation can +# improve filtering performance, depending on the quantity and types of filters. +#++ +# Rails.application.config.precompile_filter_parameters = true + +### +# Enable before_committed! callbacks on all enrolled records in a transaction. +# The previous behavior was to only run the callbacks on the first copy of a record +# if there were multiple copies of the same record enrolled in the transaction. +#++ +# Rails.application.config.active_record.before_committed_on_all_records = true + +### +# Disable automatic column serialization into YAML. +# To keep the historic behavior, you can set it to `YAML`, however it is +# recommended to explicitly define the serialization method for each column +# rather than to rely on a global default. +#++ +# Rails.application.config.active_record.default_column_serializer = nil + +### +# Enable a performance optimization that serializes Active Record models +# in a faster and more compact way. +# +# To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have +# not yet been upgraded must be able to read caches from upgraded servers, +# leave this optimization off on the first deploy, then enable it on a +# subsequent deploy. +#++ +# Rails.application.config.active_record.marshalling_format_version = 7.1 + +### +# Run `after_commit` and `after_*_commit` callbacks in the order they are defined in a model. +# This matches the behaviour of all other callbacks. +# In previous versions of Rails, they ran in the inverse order. +#++ +# Rails.application.config.active_record.run_after_transaction_callbacks_in_order_defined = true + +### +# Whether a `transaction` block is committed or rolled back when exited via `return`, `break` or `throw`. +#++ +# Rails.application.config.active_record.commit_transaction_on_non_local_return = true + +### +# Controls when to generate a value for has_secure_token declarations. +#++ +# Rails.application.config.active_record.generate_secure_token_on = :initialize + +### +# ** Please read carefully, this must be configured in config/application.rb ** +# +# Change the format of the cache entry. +# +# Changing this default means that all new cache entries added to the cache +# will have a different format that is not supported by Rails 7.0 +# applications. +# +# Only change this value after your application is fully deployed to Rails 7.1 +# and you have no plans to rollback. +# When you're ready to change format, add this to `config/application.rb` (NOT +# this file): +# config.active_support.cache_format_version = 7.1 + + +### +# Configure Action View to use HTML5 standards-compliant sanitizers when they are supported on your +# platform. +# +# `Rails::HTML::Sanitizer.best_supported_vendor` will cause Action View to use HTML5-compliant +# sanitizers if they are supported, else fall back to HTML4 sanitizers. +# +# In previous versions of Rails, Action View always used `Rails::HTML4::Sanitizer` as its vendor. +#++ +# Rails.application.config.action_view.sanitizer_vendor = Rails::HTML::Sanitizer.best_supported_vendor + + +### +# Configure Action Text to use an HTML5 standards-compliant sanitizer when it is supported on your +# platform. +# +# `Rails::HTML::Sanitizer.best_supported_vendor` will cause Action Text to use HTML5-compliant +# sanitizers if they are supported, else fall back to HTML4 sanitizers. +# +# In previous versions of Rails, Action Text always used `Rails::HTML4::Sanitizer` as its vendor. +#++ +# Rails.application.config.action_text.sanitizer_vendor = Rails::HTML::Sanitizer.best_supported_vendor + + +### +# Configure the log level used by the DebugExceptions middleware when logging +# uncaught exceptions during requests. +#++ +# Rails.application.config.action_dispatch.debug_exception_log_level = :error + + +### +# Configure the test helpers in Action View, Action Dispatch, and rails-dom-testing to use HTML5 +# parsers. +# +# Nokogiri::HTML5 isn't supported on JRuby, so JRuby applications must set this to :html4. +# +# In previous versions of Rails, these test helpers always used an HTML4 parser. +#++ +# Rails.application.config.dom_testing_default_html_version = :html5 diff --git a/config/initializers/permissions_policy.rb b/config/initializers/permissions_policy.rb index 00f64d7..7db3b95 100644 --- a/config/initializers/permissions_policy.rb +++ b/config/initializers/permissions_policy.rb @@ -1,11 +1,13 @@ +# Be sure to restart your server when you modify this file. + # Define an application-wide HTTP permissions policy. For further -# information see https://developers.google.com/web/updates/2018/06/feature-policy -# -# Rails.application.config.permissions_policy do |f| -# f.camera :none -# f.gyroscope :none -# f.microphone :none -# f.usb :none -# f.fullscreen :self -# f.payment :self, "https://secure.example.com" +# information see: https://developers.google.com/web/updates/2018/06/feature-policy + +# Rails.application.config.permissions_policy do |policy| +# policy.camera :none +# policy.gyroscope :none +# policy.microphone :none +# policy.usb :none +# policy.fullscreen :self +# policy.payment :self, "https://secure.example.com" # end diff --git a/config/locales/en.yml b/config/locales/en.yml index 6705233..bccc3d7 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -2,6 +2,7 @@ en: flash: error_signing_in: "Error signin in !" successful_sign_in: "Successfully signed in with Twitter" + successful_sign_in_github: "Successfully signed in with GitHub" error_saving_letter: "Oopss !! Error. Please try again." error_updating_letter: 'Oopss !! Error. Please try again.' saved_letter_successfully: "Saved successfully !" diff --git a/db/migrate/20231201112603_remover_user_attributes_from_user_table.rb b/db/migrate/20231201112603_remover_user_attributes_from_user_table.rb new file mode 100644 index 0000000..08ca97f --- /dev/null +++ b/db/migrate/20231201112603_remover_user_attributes_from_user_table.rb @@ -0,0 +1,11 @@ +class RemoverUserAttributesFromUserTable < ActiveRecord::Migration[6.1] + def change + remove_column :users, :uid, :string + remove_column :users, :provider, :string + remove_column :users, :twitter_oauth, :string + remove_column :users, :twitter_handle, :string + remove_column :users, :twitter_description, :string + remove_column :users, :website, :string + remove_column :users, :image, :string + end +end diff --git a/db/migrate/20231219125704_create_active_storage_tables.active_storage.rb b/db/migrate/20231219125704_create_active_storage_tables.active_storage.rb new file mode 100644 index 0000000..8779826 --- /dev/null +++ b/db/migrate/20231219125704_create_active_storage_tables.active_storage.rb @@ -0,0 +1,36 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[5.2] + def change + create_table :active_storage_blobs do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum, null: false + t.datetime :created_at, null: false + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false + t.references :blob, null: false + + t.datetime :created_at, null: false + + t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records do |t| + t.belongs_to :blob, null: false, index: false + t.string :variation_digest, null: false + + t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end +end diff --git a/db/migrate/20240102095132_add_service_name_to_active_storage_blobs.active_storage.rb b/db/migrate/20240102095132_add_service_name_to_active_storage_blobs.active_storage.rb new file mode 100644 index 0000000..a15c6ce --- /dev/null +++ b/db/migrate/20240102095132_add_service_name_to_active_storage_blobs.active_storage.rb @@ -0,0 +1,22 @@ +# This migration comes from active_storage (originally 20190112182829) +class AddServiceNameToActiveStorageBlobs < ActiveRecord::Migration[6.0] + def up + return unless table_exists?(:active_storage_blobs) + + unless column_exists?(:active_storage_blobs, :service_name) + add_column :active_storage_blobs, :service_name, :string + + if configured_service = ActiveStorage::Blob.service.name + ActiveStorage::Blob.unscoped.update_all(service_name: configured_service) + end + + change_column :active_storage_blobs, :service_name, :string, null: false + end + end + + def down + return unless table_exists?(:active_storage_blobs) + + remove_column :active_storage_blobs, :service_name + end +end diff --git a/db/migrate/20240102095133_create_active_storage_variant_records.active_storage.rb b/db/migrate/20240102095133_create_active_storage_variant_records.active_storage.rb new file mode 100644 index 0000000..94ac83a --- /dev/null +++ b/db/migrate/20240102095133_create_active_storage_variant_records.active_storage.rb @@ -0,0 +1,27 @@ +# This migration comes from active_storage (originally 20191206030411) +class CreateActiveStorageVariantRecords < ActiveRecord::Migration[6.0] + def change + return unless table_exists?(:active_storage_blobs) + + # Use Active Record's configured type for primary key + create_table :active_storage_variant_records, id: primary_key_type, if_not_exists: true do |t| + t.belongs_to :blob, null: false, index: false, type: blobs_primary_key_type + t.string :variation_digest, null: false + + t.index %i[ blob_id variation_digest ], name: "index_active_storage_variant_records_uniqueness", unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end + + private + def primary_key_type + config = Rails.configuration.generators + config.options[config.orm][:primary_key_type] || :primary_key + end + + def blobs_primary_key_type + pkey_name = connection.primary_key(:active_storage_blobs) + pkey_column = connection.columns(:active_storage_blobs).find { |c| c.name == pkey_name } + pkey_column.bigint? ? :bigint : pkey_column.type + end +end diff --git a/db/migrate/20240102095134_remove_not_null_on_active_storage_blobs_checksum.active_storage.rb b/db/migrate/20240102095134_remove_not_null_on_active_storage_blobs_checksum.active_storage.rb new file mode 100644 index 0000000..93c8b85 --- /dev/null +++ b/db/migrate/20240102095134_remove_not_null_on_active_storage_blobs_checksum.active_storage.rb @@ -0,0 +1,8 @@ +# This migration comes from active_storage (originally 20211119233751) +class RemoveNotNullOnActiveStorageBlobsChecksum < ActiveRecord::Migration[6.0] + def change + return unless table_exists?(:active_storage_blobs) + + change_column_null(:active_storage_blobs, :checksum, true) + end +end diff --git a/db/schema.rb b/db/schema.rb index ef1fbe5..251395c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2023_10_11_140047) do +ActiveRecord::Schema.define(version: 2023_12_19_125704) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -29,6 +29,34 @@ t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id" end + create_table "active_storage_attachments", force: :cascade do |t| + t.string "name", null: false + t.string "record_type", null: false + t.bigint "record_id", null: false + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.string "key", null: false + t.string "filename", null: false + t.string "content_type" + t.text "metadata" + t.string "service_name", null: false + t.bigint "byte_size", null: false + t.string "checksum", null: false + t.datetime "created_at", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + end + create_table "admin_users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false @@ -82,7 +110,6 @@ end create_table "users", force: :cascade do |t| - t.string "email", default: "" t.string "encrypted_password", default: "" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0 @@ -93,16 +120,10 @@ t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "name" - t.string "twitter_oauth" - t.string "twitter_handle" - t.string "twitter_description" - t.string "website" - t.string "image" - t.string "provider" - t.string "uid" - t.index ["provider"], name: "index_users_on_provider" - t.index ["uid"], name: "index_users_on_uid" + t.string "email" end + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" add_foreign_key "external_identities", "users" end diff --git a/lib/tasks/images.rake b/lib/tasks/images.rake new file mode 100644 index 0000000..3483e82 --- /dev/null +++ b/lib/tasks/images.rake @@ -0,0 +1,36 @@ +namespace :images do + desc 'Load images from Cloudinary and store in Active Storage' + task load_images: :environment do + saved_count = 0 + error_count = 0 + batch_count = 0 + User.where('updated_at < ?', '2023-08-26').find_in_batches(batch_size: 20) do |batch| + batch.each do |user| + cloudinary_url = "https://res.cloudinary.com/whyloveruby/image/twitter_name/#{user.twitter_identity.handle}.jpg" + begin + downloaded_image = URI.parse(cloudinary_url).open + downloaded_image.rewind + + user.twitter_identity.profile_image.attach(io: downloaded_image, filename: "#{user.twitter_identity.handle}.jpg") + + if user.twitter_identity.profile_image.attached? + saved_count += 1 + else + error_count += 1 + puts "\nError saving profile image for user #{user.twitter_identity.name}:" + puts user.twitter_identity.errors_full_message.to_sentence + end + rescue StandardError => e + # Handling the exception + error_count += 1 + puts "\nError downloading image for user #{user.id}: #{e.message}" + end + end + batch_count += 1 + puts "\nBatch #{batch_count} completed..." + puts "#{error_count} errors..." + puts "#{saved_count} saved..." + end + puts "\n\nProcess Completed" + end +end diff --git a/spec/factories/external_identity.rb b/spec/factories/external_identity.rb new file mode 100644 index 0000000..8941d55 --- /dev/null +++ b/spec/factories/external_identity.rb @@ -0,0 +1,8 @@ +FactoryBot.define do + factory :external_identity do + association :user + provider { "SomeProvider" } + uid { "SomeUID" } + end + end + \ No newline at end of file diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb index a03505a..5a1d7b6 100644 --- a/spec/helpers/application_helper_spec.rb +++ b/spec/helpers/application_helper_spec.rb @@ -15,26 +15,28 @@ # actual context: We realized just in time before RubyConfIndia2023 that due to Twitter API changes # we are unable to retrieve profile pictures for new twitter sign_ups through Cloudinary - context 'get_twitter_image for User who last signed in before RubyIndiaConf 2023' do - it 'should render image tag with the twitter handle' do - user = User.new(twitter_handle: 'my_twitter_handle', updated_at: Date.parse('2022-12-31').end_of_day) - expect(helper.get_twitter_image(user)).to match("cloudinary.*my_twitter_handle\.jpg") - end - end - context 'get_twitter_image for User who last signed in after RubyIndiaConf 2023' do - it 'should render image tag with twitter handle (in the unlikely case, our User model does not contain the image url)' do - user = User.new(twitter_handle: 'my_twitter_handle', updated_at: Date.parse('2024-01-01').end_of_day) - expect(helper.get_twitter_image(user)).to match("cloudinary.*my_twitter_handle\.jpg") + context 'get_profile_image for User' do + it 'should render image tag with the twitter handle from active storage' do + user = User.create(name: "Test") + user.external_identities.create(handle: "my_twitter_handle", provider: "twitter", uid: "252152") + + image_path = Rails.root.join('app', 'assets', 'images', 'rails.png') + user.twitter_identity.profile_image.attach(io: File.open(image_path), filename: 'my_twitter_handle.png') + + generated_url = helper.get_profile_image(user) + + expect(generated_url).to match("profile_image.*my_twitter_handle\.png") end - it 'should render image tag using the URL saved on the User model' do - user = User.new( - twitter_handle: 'my_twitter_handle', - image: 'https://pbs.twimg.com/profile_images/123456789/my_selfie.jpg', - updated_at: Date.parse('2024-01-01').end_of_day - ) - image_url = helper.get_twitter_image(user) - expect(image_url).to_not match("my_twitter_handle\.jpg") - expect(image_url).to match("my_selfie\.jpg") + it 'should render image tag with the github handle from active storage' do + user = User.create(name: "Test") + user.external_identities.create(handle: "my_github_handle", provider: "github", uid: "252150") + + image_path = Rails.root.join('app', 'assets', 'images', 'rails.png') + user.github_identity.profile_image.attach(io: File.open(image_path), filename: 'my_github_handle.png') + + generated_url = helper.get_profile_image(user) + + expect(generated_url).to match("profile_image.*my_github_handle\.png") end end end diff --git a/spec/models/external_identity_spec.rb b/spec/models/external_identity_spec.rb index ca779f4..864cbe4 100644 --- a/spec/models/external_identity_spec.rb +++ b/spec/models/external_identity_spec.rb @@ -1,5 +1,15 @@ require 'rails_helper' RSpec.describe ExternalIdentity, type: :model do - pending "add some examples to (or delete) #{__FILE__}" + describe 'ActiveRecord associations' do + it { should belong_to(:user) } + end + + describe 'ActiveModel validations' do + subject { create(:external_identity) } + it { should validate_presence_of(:provider) } + it { should validate_uniqueness_of(:provider).scoped_to(:user_id).with_message('has already been taken for this user') } + + it { should validate_uniqueness_of(:uid).scoped_to(:provider).with_message('has already been taken for this provider') } + end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 039af61..5e2c830 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -4,5 +4,6 @@ describe 'ActiveRecord associations' do it { should have_many(:letters) } it { should have_many(:likes) } + it { should have_many(:external_identities) } end end