[Rails] How to solve ActiveSupport :: MessageVerifier :: InvalidSignature that I was addicted to when introducing twitter login [ActiveStorage]

I was really into it when I introduced twitter login to my personal development app that is about to be completed, so I will leave the solution here as a memorandum.

error contents

When linking with twitter, the following error occurred when implementing the implementation of attaching the image set in the twitter account with ActiveStorage and setting it as the default profile image. (Of course, the twitter account name is also pulled at the same time)

ActiveSupport::MessageVerifier::InvalidSignature

When I commented out the code for the image, the error disappeared, so Active Storage seemed to be doing something wrong.

Illegal signature when trying to attach directly with the URL of the image? It seems that it is recognized by Active Storage as.

solution

The flow is an image of downloading a twitter image using open-uri and attaching the IO instance directly to ActiveStorage. (I would appreciate it if you could point out any errors in the expression.) Below is a partial code excerpt.

sessions_controller.rb



class SessionsController < ApplicationController
  before_action :forbid_login_user, only: %i[new]

  def new; end

  def create
    auth = request.env['omniauth.auth']
    if auth.present?
      user = User.find_or_create_from_auth(request.env['omniauth.auth'])
      session[:user_id] = user.id
      user.activate!
      redirect_to user
    else
      user = User.find_by(email: params[:session][:email].downcase)
      if user&.authenticate(params[:session][:password])
        if user.activated?
          log_in user
          params[:session][:remember_me] == '1' ? remember(user) : forget(user)
          flash[:success] = 'You have successfully logged in.'
          redirect_to user
        else
          message  = 'Your account has not been activated.'
          message += 'Click on the email account activation link.'
          flash[:warning] = message
          redirect_to root_url
        end
      else
        flash.now[:danger] = 'The password or email address is incorrect.'
        render 'new'
      end
    end
  end

user.rb


require 'open-uri'
#twitter authentication
  def self.find_or_create_from_auth(auth)
    provider = auth[:provider]
    uid = auth[:uid]
    nickname = auth[:info][:nickname]
    email = User.dummy_email(auth)
    password = SecureRandom.urlsafe_base64
    #Get Twitter original size profile image path
    profile_image_url = auth.info.image.gsub("_normal","")

    self.find_or_create_by(provider: provider, uid: uid) do |user|
      user.nickname = nickname
      user.email = email
      user.password = password
      user.download_and_attach_avatar(profile_image_url)
    end
  end

  private

  #Open the image data acquired by twitter API-Download with uri and attach IO instance directly
  def download_and_attach_avatar(profile_image_url)
    return unless profile_image_url

    file = open(profile_image_url)
    avatar.attach(io: file,
                  filename: "profile_image.#{file.content_type_parse.first.split("/").last}",
                  content_type: file.content_type_parse.first)  
  end

  def self.dummy_email(auth)
    "#{auth.uid}-#{auth.provider}@example.com"
  end

The point is the part of ``` profile_image_url = auth.info.image.gsub ("_normal "," ")` ``. The image URL obtained from the twitter client contains the character string _normal, and the image has been reduced. If you use it as it is, the image will be rough, so I used the gsub method to delete the character string _nomal. By doing this, you can get the data of the original image size.

Then, after downloading by passing `profile_image_url``` as an argument to the `download_and_attach_avatar``` method, it is attached to ActiveStorage as an IO instance.

By doing this, I was able to implement it without any errors.

Even if I searched for it, I couldn't find any information, so I managed to arrive at this method through trial and error. I hope you find this article useful.

By the way, in my case, I can't log in without activating the account with normal login, so I forcibly change the activated column from false to true with user.activate! To avoid validation. (Dummy data is put in the column with the `` `find_or_create_from_auth``` method to avoid validation even with email and password.)

Referenced articles

https://rit-inc.hatenablog.com/entry/2018/04/02/160106 https://note.com/marikooota/n/n7ac0a66e34ea

Thank you for reading to the end!

We output what we have learned every day. If you have any suggestions, I would appreciate it if you could comment! !!

Recommended Posts

[Rails] How to solve ActiveSupport :: MessageVerifier :: InvalidSignature that I was addicted to when introducing twitter login [ActiveStorage]
What I was addicted to when implementing google authentication with rails
About the matter that I was addicted to how to use hashmap
My.cnf configuration problem that I was addicted to when I was touching MySQL 8.0 like 5.7
A memo that I was addicted to when making batch processing with Spring Boot
What I was addicted to when trying to properly openAPI/Swagger documentation with Rails + Grape + Grape Swagger
A story I was addicted to when getting a key that was automatically tried on MyBatis
How to batch initialize arrays in Java that I didn't know when I was a beginner
What I fixed when updating to Spring Boot 1.5.12 ・ What I was addicted to
What I was addicted to while using rspec on rails
I was addicted to setting default_url_options with Rails devise introduction
A story I was addicted to in Rails validation settings
The story I was addicted to when setting up STS
A note when I was addicted to converting Ubuntu on WSL1 to WSL2
I was addicted to starting sbt
[Rails] How to solve the problem that the default image is overwritten when editing without uploading the image [Active Storage]
Memorandum: What I was addicted to when I hit the accounting freee API
A story I was addicted to when testing the API using MockMVC
I was a little addicted to running old Ruby environment and old Rails
[CircleCI] I was addicted to the automatic test of CircleCI (rails + mysql) [Memo]
I was addicted to rewriting to @SpringApplicationConfiguration-> @SpringBootTest
How to resolve errors when installing Rails 5.1.3
I was addicted to the roll method
I was addicted to the Spring-Batch test