Search code examples
ruby-on-railsrubydevise

Copied rails app but now devise is not working anymore


I copied an entire Rails app by doing this:

$ cp your-old-app your-new-app

and then creating a new database for it by doing this:

rake db:create db:migrate

Everything is working fine. Now I wanted to test my copied app and created a new user. Unfortunately this does not work. I am using the devise gem.

The error I get when trying to register a new test user is:

Started POST "/users/sign_in" for ::1 at 2019-11-12 19:07:42 +0100
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"jrmiVvIOB+m2a0WCQWhL4LSpdfw2x9hxP6yhJOC6HVyjXOpTTrxWeF37sTtG/dYaeK1DBr/425svb2zEcO5mhQ==", "user"=>{"email"=>"lkbkj23@test.de", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
  User Load (0.9ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["email", "lkbkj23@test.de"], ["LIMIT", 1]]
Completed 401 Unauthorized in 6ms (ActiveRecord: 0.9ms)

In the thread that explained how to copy a Rails app, I read something about the need to create a new secret_token variable. This is the only idea I have what I could have been missing. But I do not know if this is the error and I do not know where and how to set up a new secret_token variable.


Solution

  • In root of your new project run:

    rake secret
    

    Now copy the output of this to your clipboard. Then in config/initializer/devise.rb you need this line:

    config.secret_key = "#{ENV['DEVISE_SECRET_KEY']}"
    

    You'll need a way to load environment variables in your local development environment. You can either use dotenv gem and then you'll have a file in root of project called .env and you'll add the key you generated with the rake command. Or you might want to checkout figaro gem which appears to have not been updated/maintained recently. In your .env file add a line:

    DEVISE_SECRET_KEY=<paste key here>
    

    Make sure before making these changes, if you're using git version control to add .env to your .gitignore file. This will insure you don't accidentally commit your key to your repo.