Rails Action Mailer with Devise - ruby-on-rails

I understand this has been asked before and I've been following Rails ActionMailer Guides as well as looking through a few related questions on stackoverflow. I'm running a localhost and trying to send emails from there. From the rails guides, I followed every step and double checked everything is written as in the guides. I've also read a few questions found here, but still my emails aren't sending from localhost. Also, I'm not getting any errors within my server.
config/environments/development.rb
EDIT
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
#Mailers
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'dogseeker7#gmail.com'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'localhost:3000',
user_name: ENV["ADMIN_EMAIL"],
password: ENV["DOG_SEEKER_GMAIL"],
authentication: 'plain',
enable_starttls_auto: true
}
mailers/admin_mailer.rb
Class AdminMailer < Devise::Mailer
helper :application
include Devise::Controllers::UrlHelpers
Edit
def welcome_email(admin)
#admin = admin
#login_url = "localhost:3000/admins/sign_in"
mail(to: #admin.email, subject: "Welcome to Dog Seeker!")
end
app/admin/admin_controllers.rb
def create
#admin = Admin.new(params[:admin])
respond_to do |format|
if #admin.save
AdminMailer.welcome_email(#admin).deliver_now
format.html { redirect_to(#admin, notice: 'Admin was successfully created.') }
format.json { render json: #admin, status: :created, location: #admin }
else
format.html { redirect_to new_admin_registration_path }
format.json { render json: #admin.errors, status: :unprocessable_entity }
end
end
end
UPDATE
Log when new admin Signs Up
Started POST "/admins" for 127.0.0.1 at 2017-08-05 22:09:15 -0700
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<token>==", "admin"=>{"email"=>"stenglinephoto#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
(0.2ms) BEGIN
Admin Exists (0.6ms) SELECT 1 AS one FROM "admins" WHERE "admins"."email" = $1 LIMIT $2 [["email", "stenglinephoto#gmail.com"], ["LIMIT", 1]]
SQL (0.6ms) INSERT INTO "admins" ("email", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["email", "stenglinephoto#gmail.com"], ["encrypted_password", "<password>"], ["created_at", "2017-08-06 05:09:15.904920"], ["updated_at", "2017-08-06 05:09:15.904920"]]
(2.0ms) COMMIT
(0.1ms) BEGIN
SQL (0.5ms) UPDATE "admins" 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 "admins"."id" = $7 [["sign_in_count", 1], ["current_sign_in_at", "2017-08-06 05:09:15.909337"], ["last_sign_in_at", "2017-08-06 05:09:15.909337"], ["current_sign_in_ip", "127.0.0.1/32"], ["last_sign_in_ip", "127.0.0.1/32"], ["updated_at", "2017-08-06 05:09:15.909955"], ["id", 29]]
(0.5ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 172ms (ActiveRecord: 4.5ms)
Started GET "/" for 127.0.0.1 at 2017-08-05 22:09:15 -0700
Processing by HomepagesController#index as HTML
Rendering homepages/index.html.erb within layouts/application
Rendered homepages/index.html.erb within layouts/application (0.5ms)
Admin Load (0.7ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = $1 ORDER BY "admins"."id" ASC LIMIT $2 [["id", 29], ["LIMIT", 1]]
Rendered shared/_header.html.erb (5.5ms)
Rendered shared/_main.html.erb (1.0ms)
Completed 200 OK in 18ms (Views: 16.2ms | ActiveRecord: 0.7ms)
Another update
I have another mailer that gets sent when a dog is created and that works fine from localhost and with all the above configurations. My guess is the reason that mailers won't send when an admin account is created is due to the devise registrations controller overriding my controller. In other words, it's not hitting my create action in the admin_controller, but is hitting the registration within devises registration controller.
Please let me know if you need additional information.

Had to follow the guide from Devise Wiki and was able to make it work when admins sign up.

Related

RubyOnRails 7 redirection protection

I want to redirect out of the application like this:
def create
#customer = Customer.new(customer_params)
#customer.save
redirect_to "https://www.shoptet.cz/", allow_other_host: true
end
ROR 7 have integrated redirect protection so I am using, allow_other_host: true as they say in the documentation and it's not working anyway, no error executed just nothing happed...
here is Server log:
Started POST "/customers" for 89.24.40.97 at 2022-08-20 21:38:41 +0200
Cannot render console from 89.24.40.97! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by CustomersController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "customer"=>{"name"=>"jirkanovakneda#seznam.cz", "heslo"=>"hahshjsueb28"}, "commit"=>"Přihlášení"}
TRANSACTION (0.1ms) begin transaction
↳ app/controllers/customers_controller.rb:25:in `create'
Customer Create (0.6ms) INSERT INTO "customers" ("name", "heslo", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "jirkanovakneda#seznam.cz"], ["heslo", "hahshjsueb28"], ["created_at", "2022-08-20 19:38:41.917978"], ["updated_at", "2022-08-20 19:38:41.917978"]]
↳ app/controllers/customers_controller.rb:25:in `create'
TRANSACTION (12.0ms) commit transaction
↳ app/controllers/customers_controller.rb:25:in `create'
Redirected to https://www.shoptet.cz/
Completed 302 Found in 22ms (ActiveRecord: 12.8ms | Allocations: 2081)
Thanks for the help.
Thanks for help, problem fixed by disabling turbo on the button:
data: {turbo: false}

Suppress password change email when accepting invitation with Devise Invitable

I have enabled password change notifications using
config.send_password_change_notification = true
However, currently when a user accepts an invitation triggered by Devise Invitable they are receiving a password change email.
e.g.
Started PUT "/users/invitation" for 127.0.0.1 at 2017-10-20 16:14:41 +0100
Processing by UsersController::InvitationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gDHF+Vm6oxGPILonaQe7NSnhytoQGsOBm0eVEMziSS6J93UFnoHSwouyV9NezleulmstfcNW8Axr/nJajBBYw==", "user"=>{"invitation_token"=>"98usw1XW4w31UuCd_DzQ", "full_name"=>"example", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Set my password"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["invitation_token", "0a0787a3270a097c22a1272f49040c5c11d67b2cb222059d88d85f35e95c8d78"], ["LIMIT", 1]]
(0.2ms) BEGIN
SQL (0.6ms) UPDATE "users" SET "invitation_token" = $1, "encrypted_password" = $2, "full_name" = $3, "invitation_accepted_at" = $4, "updated_at" = $5 WHERE "users"."id" = $6 [["invitation_token", nil], ["encrypted_password", "$2a$11$qQKCx4FWQS2ARyiiGf8zdeAn7XLBa0clbWuv1cH1c1cXWbF65VMd6"], ["full_name", "example"], ["invitation_accepted_at", "2017-10-20 16:14:41.323768"], ["updated_at", "2017-10-20 16:14:41.324814"], ["id", 9]]
DeviseMailer#password_change: processed outbound mail in 1.7ms
Sent mail to example#example.com (195.9ms)
Is it possible to suppress the notification if the user is accepting an invitation but continue to send it for other password change events?
Environment info:
Rails 5.1.4
devise (4.3.0, 4.2.1)
devise_invitable (1.7.2)
thank you for pointing me in the right direction, here is my take on this
def send_password_change_notification
super unless accepting_invitation?
end
accepting_invitation? is a variable set on the beginning of the process
As a bonus, it bugged me that when you ask for a password recover it would prompt you with a success message and don't do anything, with this it would prompt with an error message.
[:en, :errors, :messages, :invitation_active] on your locales or just use default :not_found
def send_reset_password_instructions
if invited_to_sign_up?
self.errors.add :email, :invitation_active
else
super
end
end
OK, figured this out.
Add the following to app/models/user.rb
def send_devise_notification(notification, *args)
unless(notification == :password_change && sign_in_count.zero?)
super
end
end

Change html response to json response in rails during cross platform response

I have created cross platform form to submit data. It sends data in json format, but rails controller response it as html. So that I always get error as.
Object {readyState: 0, responseJSON: undefined, status: 0, statusText: "error"}
test.html?batch[status]=0:88
Navigated to file:///home/shital/workspace/shitalluitel.github.io/test.html?batch%5Bstatus%5D=0
Here is my rails log after my form submit...
Started POST "/batches" for 127.0.0.1 at 2017-01-13 08:55:59 +0545
Processing by BatchesController#create as HTML
Parameters: {"batch"=>{"name"=>"eight", "course_id"=>"9", "start_date"=>"2016-12-12", "end_date"=>"2016-12-14", "status"=>"1"}}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
Course Load (0.5ms) SELECT "courses".* FROM "courses" WHERE
"courses"."id" = $1 LIMIT $2 [["id", 9], ["LIMIT", 1]]
SQL (0.4ms) INSERT INTO "batches" ("name", "course_id", "start_date", "end_date", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["name", "eight"], ["course_id", 9], ["start_date", Mon, 12 Dec 2016], ["end_date", Wed, 14 Dec 2016], ["created_at", 2017-01-13 03:10:59 UTC], ["updated_at", 2017-01-13 03:10:59 UTC]]
(133.8ms) COMMIT
entered to true part
Completed 200 OK in 147ms (Views: 0.8ms | ActiveRecord: 135.6ms)
You can use
render json: {your_response: "value"}, status: 200
or if you want nothing then
render :nothing => true
You can change the status base on you needs.
you can try this in the controller response will automatically varies according to your platform
respond_to do |format|
format.html { render 'filename.html'}
format.json { render json: #batches }
end

Rails redirect registers in terminal but not on client

I'm using Google geocode to let users create a new city. After registering the params and saving successfully, the cities controller redirects the user to the new_review_path (which is the page they were already on when they filled out the form).
When I look in terminal, everything seems to work just fine, and the new city is saved to the database.
Started POST "/cities" for ::1 at 2015-12-18 12:42:15 -0500
Processing by CitiesController#create as HTML
Parameters: {"name"=>"Walla Walla", "latitude"=>"46.0645809", "longitude"=>"-118.3430209"}
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO "cities" ("name", "latitude", "longitude", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["name", "Walla Walla"], ["latitude", 46.0646], ["longitude", -118.343], ["created_at", "2015-12-18 17:42:16.095349"], ["updated_at", "2015-12-18 17:42:16.095349"]]
(8.6ms) COMMIT
Redirected to http://localhost:3000/reviews/new
Completed 302 Found in 116ms (ActiveRecord: 11.6ms)
Started GET "/reviews/new" for ::1 at 2015-12-18 12:42:16 -0500
Processing by ReviewsController#new as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
City Load (0.7ms) SELECT "cities".* FROM "cities"
Rendered reviews/new.html.erb within layouts/application (5.6ms)
Completed 200 OK in 166ms (Views: 128.7ms | ActiveRecord: 5.0ms)
But there's no change on the client. No flash message, no refresh. Is there something simple I'm overlooking here? Something to do with not using strong params maybe?
Here's my cities controller Create method:
def create
latitude = params[:latitude].to_f.round(4)
longitude = params[:longitude].to_f.round(4)
name = params[:name]
city = City.new(name: name, latitude: latitude, longitude: longitude)
if city.save
flash[:success] = "City created! Please refresh."
redirect_to new_review_path
else
flash[:notice] = "Your city couldn't be created"
end
end

Rspec case for rails 4 patch :update

I am using Devise in my app, and trying to write a spec for updating email ID. The UI works, but the spec is failing. I am reloading the user object as well, before testing against changed email ID.
One thing that I do observe is that there is UPDATE USERS statement being run on the database.
What is the correct way to write the spec?
RSpec spec:
it "should update email" do
#user = subject.current_user
patch :update, id: #user, user: {:email => "john.doe#example1.com"}
#user.reload
expect(#user.email).to eq("john.doe#example1.com")
end
RSpec Error Log:
1) Users::RegistrationsController logged in user should update email
Failure/Error: expect(#user.email).to eq("john.doe#example1.com")
expected: "john.doe#example1.com"
got: "john.doe#example.com"
(compared using ==)
test.log:
ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations"
(0.2ms) BEGIN
(0.4ms) SAVEPOINT active_record_1
User Exists (0.9ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'john.doe#example.com' LIMIT 1
SQL (4.1ms) INSERT INTO "users" ("created_at", "email", "encrypted_password", "first_name", "last_name", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["created_at", Sat, 22 Jun 2013 13:12:28 UTC +00:00], ["email", "john.doe#example.com"], ["encrypted_password", "$2a$04$LIRWzphxstpCLTuZjicA..YMW.Ei2V/LlYWP32gfx39nBjhFg5tLe"], ["first_name", "John"], ["last_name", "Doe"], ["updated_at", Sat, 22 Jun 2013 13:12:28 UTC +00:00]]
(0.1ms) RELEASE SAVEPOINT active_record_1
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 457 ORDER BY "users"."id" ASC LIMIT 1
Processing by Users::RegistrationsController#update as HTML
Parameters: {"id"=>"457", "user"=>{"email"=>"john.doe#example1.com"}}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 457]]
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'john.doe#example1.com' AND "users"."id" != 457) LIMIT 1
Rendered devise/registrations/edit.html.slim within layouts/application (0.2ms)
Completed 200 OK in 73ms (Views: 4.0ms | ActiveRecord: 1.0ms)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 457]]
(0.2ms) ROLLBACK
Try
it "should update email" do
#user = subject.current_user
patch :update, id: #user, user: {:email => "john.doe#example1.com"}
#user.reload.email.should == "john.doe#example1.com"
end
Or alternatively
it "should update email" do
#user = subject.current_user
expect {
patch :update, id: #user, user: {:email => "john.doe#example1.com"}
#user.reload
}.to change(#user, :email).to("john.doe#example1.com")
end

Resources