I added this lines of code to create action:
def create
super
#card = Card.find(params[:card_id])
#card.update(:user_id=>current_user)
end
And everything works fine, user gets created, card gets updated, but after redirect this happens:
Couldn't find Card with 'id'=
Extracted source (around line #14):
def create
super
#card = Card.find(params[:card_id])
#card.update(:user_id=>current_user)
end
I checked my terminal to find out the reason why this happens, and it seems that create action triggers twice for no reason:
Started POST "/users" for ::1 at 2020-08-12 11:04:34 +0300
Processing by Users::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"q1W0+ZhzK85uHTcp1x4jKHvCG0ukIgj2JxZuAy6vuLQl/vPqJVu6eXSEWviYTnWC4cXAJk2xCJhl8mgoWzXIAA==", "user"=>{"name"=>"Терл Кабот", "email"=>"tafff1#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "card_id"=>"2000012606"}, "commit"=>"Sign up"}
Card Load (1.0ms) SELECT "cards".* FROM "cards" WHERE "cards"."id" = $1 LIMIT $2 [["id", 2000012606], ["LIMIT", 1]]
(0.0ms)
BEGIN
User Exists (1.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "tafff1#gmail.com"], ["LIMIT", 1]]
SQL (1.0ms) INSERT INTO "users" ("email", "encrypted_password", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["email", "tafff1#gmail.com"], ["encrypted_password", "$2a$12$qTrv/zFUxULi9sqWgYlY/uPjQoJsZxB8PJK2ae/e6YfAFT40ci47e"], ["name", "Терл Кабот"], ["created_at", "2020-08-12 08:04:35.174621"], ["updated_at", "2020-08-12 08:04:35.174621"]]
SQL (1.0ms) UPDATE "cards" SET "user_id" = $1, "updated_at" = $2 WHERE "cards"."id" = $3 [["user_id", 17], ["updated_at", "2020-08-12 08:04:35.178626"], ["id", 2000012606]]
(1.0ms) COMMIT
Redirected to http://localhost:3000/
Card Load (0.0ms) SELECT "cards".* FROM "cards" WHERE "cards"."id" = $1 LIMIT $2 [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 378ms (ActiveRecord: 6.0ms)
ActiveRecord::RecordNotFound (Couldn't find Card with 'id'=):
is there any solution for this?
EDIT: I gave up and just changed card and user logic, now user belongs to card, so I dont have to update cards user_id from devises create action.
The card_id is nested in the user key, so it will be: params[:user][:card_id]
Related
I have an app where user can register using email, facebook or google, also I have small referral system where user can share link and earn points.
Now everything works perfectly registering and login. But referral system works only when creating account using social networks.
the following is my code :
omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, event: :authentication
#this will throw if #user is not activated
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
# google callback
def google_oauth2
#user = User.from_omniauth(request.env['omniauth.auth'])
if #user.persisted?
sign_in_and_redirect #user
set_flash_message(:notice, :success, kind: 'Google') if is_navigational_format?
else
flash[:error] = 'There was a problem signing you in through Google. Please register or try signing in later.'
redirect_to new_user_registration_url
end
end
def failure
flash[:error] = 'There was a problem signing you in. Please register or try signing in later.'
redirect_to new_user_registration_url
end
end
registrations_controller.rb
def build_resource(hash = {})
super
if cookies[:referral_code] && referrer = User.find_by(referral_code: cookies[:referral_code])
self.resource.referred_by = referrer
end
end
user.rb
before_validation :set_referral_code
validates :referral_code, uniqueness: true
def set_referral_code
loop do
self.referral_code = SecureRandom.hex(6)
break unless self.class.exists?(referral_code: referral_code)
end
end
application_controller.rb
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_referral_cookie
def set_referral_cookie
if params[:ref]
cookies[:referral_code] = {
value: params[:ref],
expires: 30.days.from_now,
}
end
end
I built my system using help of this repository
gorails referral system
Edit
Started GET "/?ref=6c28f9668715" for 127.0.0.1 at 2019-01-27 21:23:32 +0100
Processing by HomeController#index as HTML
Parameters: {"ref"=>"6c28f9668715"}
Rendering home/index.html.erb within layouts/application
Rendered home/index.html.erb within layouts/application (0.6ms)
Rendered shared/_navbar.html.erb (1.4ms)
Completed 200 OK in 125ms (Views: 90.7ms | ActiveRecord: 0.0ms)
Started GET "/users/sign_up" for 127.0.0.1 at 2019-01-27 21:23:34 +0100
Processing by Users::RegistrationsController#new as HTML
User Load (1.6ms) SELECT "users".* FROM "users" WHERE "users"."referral_code" = $1 LIMIT $2 [["referral_code", "6c28f9668715"], ["LIMIT", 1]]
↳ app/controllers/users/registrations_controller.rb:7
Rendering users/registrations/new.html.erb within layouts/application
Rendered users/registrations/new.html.erb within layouts/application (6.7ms)
Rendered shared/_navbar.html.erb (1.2ms)
Completed 200 OK in 300ms (Views: 142.0ms | ActiveRecord: 1.6ms)
Started GET "/users/auth/facebook" for 127.0.0.1 at 2019-01-27 21:23:37 +0100
I, [2019-01-27T21:23:37.266108 #67828] INFO -- omniauth: (facebook) Request phase initiated.
Started GET "/users/auth/facebook" for 127.0.0.1 at 2019-01-27 21:23:38 +0100
I, [2019-01-27T21:23:38.488342 #67828] INFO -- omniauth: (facebook) Request phase initiated.
Started GET "/users/auth/facebook/callback?code=AQAemLam_HRACk1q5NTfix5Sve6rA1fsDD5z_21vKpDlaTq4hfuXM2Oh_CThPspwk1BIg4Tjc1bm0UOcXLo_X0XGVI8XdLsirhPV6wKnGiCO3uU3l4y6y31qnhC1xjzd-21wx_cWVO-ipPCzrZ8kqWCdvQrxxKOQXMj10LsKlTAbuSqMEpx90XvcZw3RAYGLSiEFQGJSgCpABpboh_n_ewjTbfbTB01JATW6hM9Wy8iN1AQLpXrRgOZ-5P1NdowqdHdjU420N6QoB7R9tyHXegioQ47J8cjgCMUFwDPi_T--zHK6_-sIkW_QE6P5ryot1qHxzHpOASvx46WHvJun5_Yh&state=bd3dfbf7e7a5c83c42d1d754149d7be5ea7f39b6d5b99b28" for 127.0.0.1 at 2019-01-27 21:23:39 +0100
I, [2019-01-27T21:23:39.483990 #67828] INFO -- omniauth: (facebook) Callback phase initiated.
Processing by Users::OmniauthCallbacksController#facebook as HTML
Parameters: {"code"=>"AQAemLam_HRACk1q5NTfix5Sve6rA1fsDD5z_21vKpDlaTq4hfuXM2Oh_CThPspwk1BIg4Tjc1bm0UOcXLo_X0XGVI8XdLsirhPV6wKnGiCO3uU3l4y6y31qnhC1xjzd-21wx_cWVO-ipPCzrZ8kqWCdvQrxxKOQXMj10LsKlTAbuSqMEpx90XvcZw3RAYGLSiEFQGJSgCpABpboh_n_ewjTbfbTB01JATW6hM9Wy8iN1AQLpXrRgOZ-5P1NdowqdHdjU420N6QoB7R9tyHXegioQ47J8cjgCMUFwDPi_T--zHK6_-sIkW_QE6P5ryot1qHxzHpOASvx46WHvJun5_Yh", "state"=>"bd3dfbf7e7a5c83c42d1d754149d7be5ea7f39b6d5b99b28"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT $3 [["provider", "facebook"], ["uid", "311741132783400"], ["LIMIT", 1]]
↳ app/models/user.rb:60
Disk Storage (5.7ms) Uploaded file to key: Sp8DiDxRWFn3uUfGTJJHdABc (checksum: tjmoDYRADOqNyXiWy90gxg==)
(0.3ms) BEGIN
↳ app/models/user.rb:66
ActiveStorage::Blob Create (44.9ms) INSERT INTO "active_storage_blobs" ("key", "filename", "content_type", "metadata", "byte_size", "checksum", "created_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["key", "Sp8DiDxRWFn3uUfGTJJHdABc"], ["filename", "avatar.jpg"], ["content_type", "image/jpeg"], ["metadata", "{\"identified\":true}"], ["byte_size", 1640], ["checksum", "tjmoDYRADOqNyXiWy90gxg=="], ["created_at", "2019-01-27 20:23:42.423862"]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/persistence.rb:12
(0.9ms) COMMIT
↳ app/models/user.rb:66
(0.2ms) BEGIN
↳ app/models/user.rb:66
(0.2ms) COMMIT
↳ app/models/user.rb:66
(0.2ms) BEGIN
↳ app/models/user.rb:60
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 AND "users"."referral_code" = $3 LIMIT $4 [["provider", "facebook"], ["uid", "311741132783400"], ["referral_code", "2925f372e912"], ["LIMIT", 1]]
↳ app/models/user.rb:79
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "qubitam#gmail.com"], ["LIMIT", 1]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/rails5_1/uniqueness_validator.rb:38
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."referral_code" = $1 LIMIT $2 [["referral_code", "2925f372e912"], ["LIMIT", 1]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/rails5_1/uniqueness_validator.rb:38
User Create (2.5ms) INSERT INTO "users" ("email", "encrypted_password", "name", "created_at", "updated_at", "provider", "uid", "referral_code") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["email", "qubitam#gmail.com"], ["encrypted_password", "$2a$11$JUxrDl1I4uDQwxi3yRVrnuqRJNYQJA8BcvLrmAj29nwBggJknrP3i"], ["name", "Abdelmoumin Mokhtari"], ["created_at", "2019-01-27 20:23:42.483417"], ["updated_at", "2019-01-27 20:23:42.483417"], ["provider", "facebook"], ["uid", "311741132783400"], ["referral_code", "2925f372e912"]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/persistence.rb:12
ActiveStorage::Attachment Create (0.7ms) INSERT INTO "active_storage_attachments" ("name", "record_type", "record_id", "blob_id", "created_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["name", "image"], ["record_type", "User"], ["record_id", 13], ["blob_id", 10], ["created_at", "2019-01-27 20:23:42.487979"]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/persistence.rb:12
User Update (41.5ms) UPDATE "users" SET "updated_at" = $1 WHERE "users"."id" = $2 [["updated_at", "2019-01-27 20:23:42.490719"], ["id", 13]]
↳ app/models/user.rb:60
(40.9ms) COMMIT
↳ app/models/user.rb:60
[ActiveJob] Enqueued ActiveStorage::AnalyzeJob (Job ID: 1f7ce124-dc8b-4302-912e-7b1138656e35) to Async(default) with arguments: #<GlobalID:0x00007fa636abf0e8 #uri=#<URI::GID gid://classifyads/ActiveStorage::Blob/10>>
(1.0ms) BEGIN
↳ app/controllers/users/omniauth_callbacks_controller.rb:8
ActiveStorage::Blob Load (0.4ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2 [["id", 10], ["LIMIT", 1]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] Performing ActiveStorage::AnalyzeJob (Job ID: 1f7ce124-dc8b-4302-912e-7b1138656e35) from Async(default) with arguments: #<GlobalID:0x00007fa636aac790 #uri=#<URI::GID gid://classifyads/ActiveStorage::Blob/10>>
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] Disk Storage (0.2ms) Downloaded file from key: Sp8DiDxRWFn3uUfGTJJHdABc
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] Skipping image analysis because the mini_magick gem isn't installed
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] (0.2ms) BEGIN
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] ↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] ActiveStorage::Blob Update (0.6ms) UPDATE "active_storage_blobs" SET "metadata" = $1 WHERE "active_storage_blobs"."id" = $2 [["metadata", "{\"identified\":true,\"analyzed\":true}"], ["id", 10]]
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] ↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/persistence.rb:7
User Update (82.8ms) UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" = $2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5, "updated_at" = $6 WHERE "users"."id" = $7 [["sign_in_count", 1], ["current_sign_in_at", "2019-01-27 20:23:42.581519"], ["last_sign_in_at", "2019-01-27 20:23:42.581519"], ["current_sign_in_ip", "127.0.0.1/32"], ["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2019-01-27 20:23:42.584122"], ["id", 13]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/bundler/gems/globalize-3fe2f93ab2d0/lib/patches/active_record/persistence.rb:7
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] (61.8ms) COMMIT
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] ↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
[ActiveJob] [ActiveStorage::AnalyzeJob] [1f7ce124-dc8b-4302-912e-7b1138656e35] Performed ActiveStorage::AnalyzeJob (Job ID: 1f7ce124-dc8b-4302-912e-7b1138656e35) from Async(default) in 122.16ms
(79.1ms) COMMIT
↳ app/controllers/users/omniauth_callbacks_controller.rb:8
Redirected to http://localhost:3000/users/edit
Completed 302 Found in 2383ms (ActiveRecord: 297.1ms)
Started GET "/users/edit" for 127.0.0.1 at 2019-01-27 21:23:42 +0100
Processing by Users::RegistrationsController#edit as HTML
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 13], ["LIMIT", 1]]
↳ /Users/qubitam/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Rendering users/registrations/edit.html.erb within layouts/application
ActiveStorage::Attachment Load (0.6ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id", 13], ["record_type", "User"], ["name", "image"], ["LIMIT", 1]]
↳ app/views/users/registrations/edit.html.erb:8
ActiveStorage::Blob Load (0.9ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2 [["id", 10], ["LIMIT", 1]]
↳ app/views/users/registrations/edit.html.erb:8
Rendered users/registrations/edit.html.erb within layouts/application (14.4ms)
Rendered shared/_navbar.html.erb (3.9ms)
Completed 200 OK in 105ms (Views: 100.1ms | ActiveRecord: 2.2ms)
I have
class CustomSessionsController < Devise::SessionsController
def create
#user = resource # needed for Merit
super
end
protected
def after_sign_in_path_for(resource)
#user = resource # needed for Merit
resource.update_streak
super
And
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, model_name: 'User' do |user|
puts user.inspect
user.streak.count >= 3
end
But it gives the error
[merit] no target_obj found on Rule#applies?
And I can't access the model and it doesn't grant the badge or log the user. What is wrong? I followed the guide.
https://github.com/merit-gem/merit/wiki/How-to-grant-badges-on-user-using-Devise
It's doing something.
Processing by CustomSessionsController#create as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"gqUQjF9hfzJdQqxAAQJxv7bi+kZYwuv1NWtOP0YhkbjHKwnfa5WAb/CkRZ5c+Xi5yVlnJ2v774w3XLhTa1b1sQ==", "user"=>{"email"=>"student#gmail.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (6.0ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["email", "student#gmail.com"]]
(7.0ms) BEGIN
SQL (3.0ms) UPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5 [["last_sign_in_at", "2018-08-09 05:38:58.345271"], ["current_sign_in_at", "2018-08-10 01:40:51.644592"], ["sign_in_count", 15], ["updated_at", "2018-08-10 01:40:51.668609"], ["id", 3]]
(25.0ms) COMMIT
Streak Load (21.0ms) SELECT "streaks".* FROM "streaks" WHERE "streaks"."user_id" = $1 LIMIT 1 [["user_id", 3]]
Redirected to http://localhost:3000/
(1.0ms) BEGIN
SQL (7.0ms) INSERT INTO "merit_actions" ("user_id", "action_method", "target_model", "target_data", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["user_id", 3], ["action_method", "create"], ["target_model", "custom_sessions"], ["target_data", "--- \n...\n"], ["created_at", "2018-08-10 01:40:53.539847"], ["updated_at", "2018-08-10 01:40:53.539847"]]
(8.0ms) COMMIT
Merit::Action Load (6.0ms) SELECT "merit_actions".* FROM "merit_actions" WHERE "merit_actions"."processed" = $1 [["processed", "f"]]
(3.0ms) BEGIN
SQL (2.0ms) UPDATE "merit_actions" SET "processed" = $1, "updated_at" = $2 WHERE "merit_actions"."id" = $3 [["processed", "t"], ["updated_at", "2018-08-10 01:40:53.581875"], ["id", 17]]
(20.0ms) COMMIT
User Load (2.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
[merit] no target_obj found on Rule#applies?
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
[merit] no target_obj found on Rule#applies?
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
Completed 302 Found in 2567ms (ActiveRecord: 293.2ms)
Merit 2.4, Rails 4.2.
I tried
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true do
puts current_user.inspect
current_user.streak.count >= 3
end
But it gave
[merit] no target found: uninitialized constant CustomSession. base_target_finder.rb:13:in 'find'
error NameError (undefined local variable or method 'current_user'
I tried
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, to: :itself do |user|
puts user.inspect
user.streak.count >= 3
end
def create
#custom_session = resource # needed for Merit
def after_sign_in_path_for(resource)
#custom_session = resource # needed for Merit
But it gave
[merit] no target found: uninitialized constant CustomSession. C:/ruby23/lib/ruby/gems/2.3.0/gems/merit-2.4.0/lib/merit/base_target_finder.rb:13:in `find'
true
Completed 500 Internal Server Error in 2181ms (ActiveRecord: 177.1ms)
NoMethodError (undefined method `streak' for true:TrueClass):
app/models/merit/badge_rules.rb:43:in `block in initialize'
I got it working with
grant_on 'custom_sessions#create', badge: :streak, level: 3, temporary: true, model_name: 'User', to: :itself do |user|
def create
super
#custom_session = resource # needed for Merit
But I don't know why because the /users/sign_in path does not have an :id parameter.
https://github.com/merit-gem/merit#how-merit-finds-the-target-object
Merit would fetch the Article object from the database, found by the :id param sent in that update action.
I posted this of the issues page for the doorkeeper gem, but looking at it, I wonder if I should post here, any help would be amazing as I am completely stuck
I have been following the wiki on doorkeeper and doing the "Testing your provider with OAuth2 gem" (https://github.com/doorkeeper-gem/doorkeeper/wiki/Testing-your-provider-with-OAuth2-gem)
I am running rails 5.1.4, ruby 2.4.1, doorkeeper gem 4.2.6 and oauth2 v1.4.0
I am having issues trying to do what is done in the testing wiki in code, which is get an auth token
My sessions controller:
def new
session[:state] = 'some state sent from amazon'
session[:client_id] = 'some client id'
session[:client_secret] = 'some client secret'
session[:redirect_uri] = "#{request.base_url}/oauth/callback"
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
if user.activated?
log_in user
redirect_to client.auth_code.authorize_url(:redirect_uri => session[:redirect_uri])
end
end
end
#route for /oauth/cllback comes here
def callback
token = client.auth_code.get_token(params[:code], :redirect_uri => session[:redirect_uri])
# testing print to screen
render json: token
end
private
def client
OAuth2::Client.new(session[:client_id], session[:client_secret], :site => request.base_url)
end
So as a user i log in, I authorise the app and then it times out and I get the following log for the whole flow:
Started GET "/login?client_id=<client_id>&response_type=code&state=<amazon state>&redirect_uri=https%3A%2F%2Fpitangui.amazon.com%2Fapi%2Fskill%2Flink%2FM2X1TLJOHDU07S" for 5.175.83.20 at 2017-10-23 13:36:35 +0100
Processing by SessionsController#new as HTML
Parameters: {"client_id"=>"<client_id>", "response_type"=>"code", "state"=>"<amazon state>", "redirect_uri"=>"https://pitangui.amazon.com/api/skill/link/M2X1TLJOHDU07S"}
Rendering sessions/new.html.erb within layouts/application
Rendered sessions/new.html.erb within layouts/application (1.5ms)
Rendered layouts/_shim.html.erb (0.5ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (36.3ms)
Completed 200 OK in 121ms (Views: 107.5ms | ActiveRecord: 4.0ms)
Started POST "/login" for 5.175.83.20 at 2017-10-23 13:40:35 +0100
Processing by SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"aR03Eo+jxzN+oDPrnOevHn6moTCSePoLAi2Ncc7pKbtxVQa6lLu+IzdEsfzrexpJVm6MdOugIQICyN2ZNS7hgw==", "session"=>{"email"=>"me#daviesp.co.uk", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log In"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "me#daviesp.co.uk"], ["LIMIT", 1]]
Redirected to https://3751d64e.ngrok.io/oauth/authorize?client_id=<client_id>&redirect_uri=https%3A%2F%2F3751d64e.ngrok.io%2Foauth%2Fcallback&response_type=code
Completed 302 Found in 67ms (ActiveRecord: 0.6ms)
Started GET "/oauth/authorize?client_id=<client_id>&redirect_uri=https%3A%2F%2F3751d64e.ngrok.io%2Foauth%2Fcallback&response_type=code" for 5.175.83.20 at 2017-10-23 13:40:36 +0100
Processing by Doorkeeper::AuthorizationsController#new as HTML
Parameters: {"client_id"=>"<client_id>", "redirect_uri"=>"https://3751d64e.ngrok.io/oauth/callback", "response_type"=>"code"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Doorkeeper::Application Load (0.4ms) SELECT "oauth_applications".* FROM "oauth_applications" WHERE "oauth_applications"."uid" = $1 LIMIT $2 [["uid", "6067fbe8f36b4343aa297ce76348e868f9ea04b04841adb411d0885c491c1d48"], ["LIMIT", 1]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Doorkeeper::AccessToken Load (0.5ms) SELECT "oauth_access_tokens".* FROM "oauth_access_tokens" WHERE "oauth_access_tokens"."application_id" = $1 AND "oauth_access_tokens"."resource_owner_id" = $2 AND "oauth_access_tokens"."revoked_at" IS NULL ORDER BY created_at desc LIMIT $3 [["application_id", 11], ["resource_owner_id", 1], ["LIMIT", 1]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
Doorkeeper::AccessGrant Exists (0.6ms) SELECT 1 AS one FROM "oauth_access_grants" WHERE "oauth_access_grants"."token" = $1 LIMIT $2 [["token", "a6bd0459570f1e0116ca6b2cade1e60ae83ba439d3c70b750046cfffe3cc85e4"], ["LIMIT", 1]]
SQL (0.5ms) INSERT INTO "oauth_access_grants" ("resource_owner_id", "application_id", "token", "expires_in", "redirect_uri", "created_at", "scopes") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["resource_owner_id", 1], ["application_id", 11], ["token", "a6bd0459570f1e0116ca6b2cade1e60ae83ba439d3c70b750046cfffe3cc85e4"], ["expires_in", 600], ["redirect_uri", "https://3751d64e.ngrok.io/oauth/callback"], ["created_at", "2017-10-23 12:40:36.235539"], ["scopes", ""]]
(1.5ms) COMMIT
Redirected to https://3751d64e.ngrok.io/oauth/callback?code=a6bd0459570f1e0116ca6b2cade1e60ae83ba439d3c70b750046cfffe3cc85e4
Completed 302 Found in 14ms (ActiveRecord: 4.2ms)
Started GET "/oauth/callback?code=[FILTERED]" for 5.175.83.20 at 2017-10-23 13:40:36 +0100
Processing by SessionsController#oauth_call as HTML
Parameters: {"code"=>"[FILTERED]"}
Started POST "/oauth/token" for 5.175.83.20 at 2017-10-23 13:40:37 +0100
Completed 500 Internal Server Error in 60406ms (ActiveRecord: 0.0ms)
Faraday::TimeoutError (Net::ReadTimeout)
Cant for the life of me figure out why it works in irb but not in code. Here is what i do in irb
irb(main):001:0> require 'oauth2'
=> true
irb(main):002:0>
irb(main):003:0* client_id = '6067fbe8f36b4343aa297ce76348e868f9ea04b04841adb411d0885c491c1d48'
=> "6067fbe8f36b4343aa297ce76348e868f9ea04b04841adb411d0885c491c1d48"
irb(main):004:0> client_secret = '937088f4b7579b8922ad02518477da7be699958df1b1e8a85da34f2e8b4ce086'
=> "937088f4b7579b8922ad02518477da7be699958df1b1e8a85da34f2e8b4ce086"
irb(main):005:0> redirect_uri = 'https://3751d64e.ngrok.io/oauth/callback'
=> "https://3751d64e.ngrok.io/oauth/callback"
irb(main):006:0> site = 'https://3751d64e.ngrok.io'
=> "https://3751d64e.ngrok.io"
irb(main):007:0> state = 'some state'
=> "some state"
irb(main):008:0> client = OAuth2::Client.new(client_id, client_secret, :site => site)
=> #<OAuth2::Client:0x007fa61414c4b0 #id="6067fbe8f36b4343aa297ce76348e868f9ea04b04841adb411d0885c491c1d48", #secret="937088f4b7579b8922ad02518477da7be699958df1b1e8a85da34f2e8b4ce086", #site="https://3751d64e.ngrok.io", #options={:authorize_url=>"/oauth/authorize", :token_url=>"/oauth/token", :token_method=>:post, :auth_scheme=>:request_body, :connection_opts=>{}, :connection_build=>nil, :max_redirects=>5, :raise_errors=>true}>
irb(main):009:0> client.auth_code.authorize_url(:redirect_uri => redirect_uri)
=> "https://3751d64e.ngrok.io/oauth/authorize?client_id=6067fbe8f36b4343aa297ce76348e868f9ea04b04841adb411d0885c491c1d48&redirect_uri=https%3A%2F%2F3751d64e.ngrok.io%2Foauth%2Fcallback&response_type=code"
even If i put that uri into browser and it returns the access token:
{"token_type":"bearer","created_at":1508763209,"access_token":"38282cae5191923f1f358aece869e237d4d9742cdd7c918ae63104c57807a826","refresh_token":null,"expires_at":1508770409}
Again any help would be amazing!
So I found in my Dev Environment, if i stop using puma and rails server and started using POW, the issue went away. I checked if puma was running as single thread but it was running 5 threads, so not sure why this was happening.
I am using Rails 4.1.14, Ruby 2.1.6, Devise 3.2.4 and Devise_invitable 1.3.6.
The issue I am having is once a new user I invited presses the accept invitation link in the email they received, it gets stuck in a redirect loop. I can't figure out why.
These are the server logs for the entire operation (note that the bulk of the first part of the log corresponds to the logic I omit below - but I left it in case it tells something interesting) :
Started GET "/users/invitation/accept?invitation_token=qANzitr64dxzxG9dSsMU" for 127.0.0.1 at 2015-12-12 04:51:29 -0500
Processing by Users::InvitationsController#edit as HTML
Parameters: {"invitation_token"=>"qANzitr6"}
User Load (4.0ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = 'qANzitr6' ORDER BY "users"."id" ASC LIMIT 1
User Load (1.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
Member Load (3.8ms) SELECT "members".* FROM "members" WHERE "members"."email" = 'def#test.com' LIMIT 1
Membership Load (88.3ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."member_id" = 115 LIMIT 1
Connection Load (14.8ms) SELECT "connections".* FROM "connections" WHERE "connections"."membership_id" = 173 ORDER BY "connections"."id" ASC LIMIT 1
(2.3ms) BEGIN
SQL (3.4ms) UPDATE "memberships" SET "invited_id" = $1, "member_id" = $2, "relative_type" = $3, "updated_at" = $4 WHERE "memberships"."id" = 173 [["invited_id", 83], ["member_id", nil], ["relative_type", 1], ["updated_at", "2015-12-12 09:51:30.038439"]]
(1.8ms) COMMIT
Membership Load (2.3ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."user_id" = $1 AND "memberships"."invited_id" = 83 ORDER BY "memberships"."id" ASC LIMIT 1 [["user_id", 1]]
FamilyTree Load (1.7ms) SELECT "family_trees".* FROM "family_trees" WHERE "family_trees"."user_id" = $1 LIMIT 1 [["user_id", 83]]
Membership Load (3.7ms) SELECT "memberships".* FROM "memberships" WHERE "memberships"."user_id" = 83 AND "memberships"."invited_id" = 1 AND "memberships"."family_tree_id" = 85 AND "memberships"."relation" = 'wife' AND "memberships"."relative_type" = 1 LIMIT 1
(33.0ms) BEGIN
SQL (37.9ms) INSERT INTO "memberships" ("created_at", "family_tree_id", "invited_id", "relation", "relative_type", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["created_at", "2015-12-12 09:51:30.105734"], ["family_tree_id", 85], ["invited_id", 1], ["relation", "wife"], ["relative_type", 1], ["updated_at", "2015-12-12 09:51:30.105734"], ["user_id", 83]]
Connection Exists (11.7ms) SELECT 1 AS one FROM "connections" INNER JOIN "memberships" ON "memberships"."id" = "connections"."membership_id" WHERE (memberships.invited_id = 83) LIMIT 1
(2.1ms) COMMIT
(1.6ms) BEGIN
SQL (3.7ms) UPDATE "connections" SET "invited_membership_id" = $1, "invited_user_id" = $2, "request_status" = $3, "responded_at" = $4, "updated_at" = $5 WHERE "connections"."id" = 127 [["invited_membership_id", 174], ["invited_user_id", 83], ["request_status", 1], ["responded_at", "2015-12-12 09:51:30.167563"], ["updated_at", "2015-12-12 09:51:30.172215"]]
(1.9ms) COMMIT
SQL (2.3ms) DELETE FROM "members" WHERE "members"."id" = 115
Rendered shared/_footer.html.erb (4.5ms)
Rendered users/invitations/edit.html.erb within layouts/devise (48.6ms)
Completed 200 OK in 1689ms (Views: 1405.9ms | ActiveRecord: 222.2ms)
Started PUT "/users/invitation" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓", "user"=>{"invitation_token"=>"qANzitr6", "gender"=>"female", "invitation_relation"=>"wife", "full_name"=>"My Wife", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Register", "id"=>"invitation"}
Completed 401 Unauthorized in 8ms (ActiveRecord: 0.0ms)
Started GET "/users/login" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#show as HTML
Parameters: {"id"=>"login"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
Started GET "/users/login" for 127.0.0.1 at 2015-12-12 04:51:53 -0500
Processing by UsersController#show as HTML
Parameters: {"id"=>"login"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
This is my Users::InvitationsController#Edit
def edit
# Some logic that I know works and is irrelevant to this question.
# below is lifted directly from the `edit` action within the gem itself.
set_minimum_password_length if respond_to? :set_minimum_password_length
resource.invitation_token = params[:invitation_token]
render :edit
end
Then I specified an accept_resource method like the docs suggested I do if I want anything special to happen after or before the invitation is sent.
def accept_resource
resource = resource_class.accept_invitation!(update_resource_params)
resource.confirm!
resource
end
I assumed that part of the reason this must be happening is that I am stuck in a loop where the user's account wasn't confirmed after they accepted....hence that override.
Here is my User.rb:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :invitable, :confirmable
end
What could be causing this?
Here is my problem:
I'm using Devise's guest_user, that contains a logging_in method to transfer guest_user parameters to the registered user when he logs in. So in my case, the user has_many periods, dependent: :destroy, so here is the logging_in method:
def logging_in
guest_periods = guest_user.periods.all
guest_periods.each do |p|
p.user_id = current_user.id
p.save!
end
current_user.latest_entry = guest_user.latest_entry
current_user.is_in_zone = guest_user.is_in_zone
current_user.save
end
However, when a guest_user logs in, his periods gets destroyed instead of being transfered. Here is the log:
Started GET "/" for ::1 at 2015-05-11 00:18:03 +0300
Processing by WelcomeController#index as HTML
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 24]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 23]]
Period Load (0.3ms) SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1 [["user_id", 23]]
(0.2ms) BEGIN
CACHE (0.0ms) SELECT "periods".* FROM "periods" WHERE "periods"."user_id" = $1 [["user_id", 23]]
SQL (0.8ms) UPDATE "periods" SET "user_id" = $1, "updated_at" = $2 WHERE "periods"."id" = $3 [["user_id", 24], ["updated_at", "2015-05-10 21:18:03.863162"], ["id", 170]]
(0.9ms) COMMIT
(0.2ms) BEGIN
SQL (2.1ms) UPDATE "users" SET "is_in_zone" = $1, "latest_entry" = $2, "updated_at" = $3 WHERE "users"."id" = $4 [["is_in_zone", "t"], ["latest_entry", "2015-05-04"], ["updated_at", "2015-05-10 21:18:03.875572"], ["id", 24]]
(15.8ms) COMMIT
(0.5ms) BEGIN
SQL (0.3ms) DELETE FROM "periods" WHERE "periods"."id" = $1 [["id", 170]]
SQL (0.7ms) DELETE FROM "users" WHERE "users"."id" = $1 [["id", 23]]
(1.2ms) COMMIT
So we can see that the transfer is done, but then in the end, the periods are destroyed anyway. They should not be, as they are not belonging to the user to be destroyed any more.
Why is it happening?
Even though Period#user_id has changed, guest_user.periods is still loaded in memory and is what gets destroyed when you destroy the guest user. If you guest_user.reload, its associations will clear out and it becomes safe to destroy. You could also guest_user.periods(true) to force reload of just the periods.
Another option is:
guest_user.periods.update_all(user_id: current_user.id)
This executes a single query to perform the update, which will be nice if there are a lot of periods, and also doesn't load the guest_user.periods association, so it will load fresh during the destroy and find the correct empty set.