Devise Mailer, using custom email template for existing module - ruby-on-rails

I'm using ruby on rails, with devise.
I have a senario wherin an Administrator would be able to add new user to the web application giving his email id and under this senario i'd be creating a new user. and would like to issue an Auth-Token to the user email. so when he clicks the link in his email, he'd be prompted to issue his/her new password.
My forgot password implementation.
def create
resource = User.send_reset_password_instructions(params[:user])
if successfully_sent?(resource)
render json: {status: :true},status: 200
else
render json: {status: :false, error: user.errors.full_messages.join(",") } , status: 200
end
end
Now my question is how do i use the same logic as that of forgot password, but use different Email-template for the user-added by the administrator screen. ?
Thanks a lot.

Why are you redirecting a user to forgot your password page when you can simply redirect him/her to settings page from where a user can change his/her password?
Create a mailer action with its template and simply call that mailer action inside the method where your admin is creating users. e.g:
if your mailer action is:
def forgot_pass(email)
mail(to: email, subject: 'Change your pass')
end
and your method where your admin is creating users is:
def create_user
# your logic
YourMailerClass.forgot_pass(xyz#abc.com).deliver
end
For more details on mailer refer to here

Related

Render email text conditionally based on who sent it

Users can accept a project, or an admin user can do it on their behalf. Regardless of the sender, an email is sent. I would like the contents of the email to be different when an admin triggers its' sending.
There's a current_user method in ApplicationController. When current_user.admin? evaluates to true, I'd like to do something else.
How can I access current_user from either inside the mailer's view template or from the *_mailer.rb itself?
I'm also open to working with controller/action names. For example, if controller_name == "Admin". It'll get us there, but this method is unavailable in the mailer as well.
Just pass the current_user to the mailer when you are creating a new delivery:
YourMailer.conditional_creation_email(current_user).deliver_now
In your_mailer.rb
def conditional_creation_email(sender)
if sender.admin?
# do...
mail(to: '#gmail.com', subject: 'New Order')
end
end

How to implement "forgot password" using Warden?

In the process of switching from Devise to directly using Warden.
How can I go about implementing a "forgot password" functionality that comes out of the box with Devise?
Is there a gem that can add this onto Warden?
PS. The reason for not using Devise is because of some customization needed that makes hacking Devise to make it work not worthwhile.
I don't know if there is a gem, but doing it yourself doesn't take to long. Assuming that each account has an email attached to it. Have a forgot password button that links to a page where the user will input there username or whatever information that is unique to the user and once the user submits the form. Send a new password to there email.
Step-by-step:
Create a forgot password button on your login page to link to a new forgot password page.
Make the route, controller actions for the this new forgot password page.
Make a form on the forgot password page that takes in a unique piece of information about the user. ex. username. This form will be a post request to a action in your controller that will email a new password to the user who has this username for example.
This is what one of mine looked like:
def emailor
#user = User.find_by username: params[:user][:username]
random_password = Array.new(10).map { (65 + rand(58)).chr }.join
#user.password = random_password
if #user.save
UserMailer.reset_password_email(#user.email, random_password ).deliver
flash[:notice] = "Email has been sent";
redirect_to root_path
end
end
Make your mailer. This guide goes over how its done if you don't know. Mailers in Rails

ensure last admin remains while destroying/deleting/removing an user in devise authentication

I'm new to rails.I'm working on a small application which needs an admin role who can add, modify and delete the content. So some models/views should be hidden from general users and only admin can have access to them through authentication.
To achieve this I have used 'rails_admin' and 'devise' gems. I did not the want the sign_up page to be shown to genral user, so I have removed that removing :registerable from my Admin model.
Now everything seems fine but, when I log in through an admin, delete each and every admin from my dashboard, I cannot login again since I have removed the sign_up page.
So I want to ensure that my last user remains. A warning/notice should be shown user while deleting the last user. I wrote the following code for that
private
def ensure_an_admin_remains
if Admin.count.zero?
raise "Can't delete last user"
end
end
This throws an error but my browser shows all the Error details. I want it to be shown to as a flash message. I think I have to change the devise controllers destroy method. But I don't know where to find it and how to do the required changes.
Can someone please help me on this?
In controller...
def destroy
admin = Admin.find(params[:id])
begin
admin.destroy
redirect_to admins_path, notice: 'Admin destroyed.'
rescue => e
redirect_to admins_path, alert: e.message
end
end

Implicit user creation with Authlogic and Authlogic OAuth plugin

I'm trying to write a simple OAuth consumer app in Rails. I'm using Authlogic for handling authentication and the Authlogic OAuth plugin to do the oauth thing.
The oauth plugin provides a couple of helpers to render the sign in button: oauth_login_button and oauth_register_button. Together with the Authlogic logics and the plugin's request filters these two buttons somehow create the session/user.
What happens next is as follows:
- if I use the oauth_login_button helper, then the session object fails to save as there's no such user locally.
- if I use the oauth_register_button helper, then, on any login after the first one, Rails complains that the token has been taken already... that means it can't create the second copy for the same user, which is right.
The issue is: I don't want to have BOTH Register AND Login buttons on my site.
On the user side, what I want to achieve is a single button on the start page, saying smth. like "Sign In with Twitter", which the user must click to proceed to inner pages of the site.
On the server side, I want to implicitly create the local user account, if the user is a first time visitor to my site.
Any hints on how to do this?
All the samples on Authlogic+OAuth I was able to find don't seem to care about having only a single button for sign in. :(
Seems like I'm going to answer the question myself.
I use the following code to generate the Sign In button (in HAML):
- form_tag({:controller => "users", :action => "create"}, {:method => "post"}) do
= oauth_register_button :value => "Sign In with Twitter"
and then I simply create the user's session object in the create method of the UsersController class, if the user already exists:
def create
#user = User.new(params[:user])
#user.save do |result| # LINE A
if result
flash[:notice] = "Account registered!"
redirect_to some_inner_path
else
unless #user.oauth_token.nil?
#user = User.find_by_oauth_token(#user.oauth_token)
unless #user.nil?
UserSession.create(#user)
flash.now[:message] = "Welcome back!"
redirect_to some_inner_path
else
redirect_back_or_default root_path
end
else
redirect_back_or_default root_path
end
end
end
end
If the user is a first time visitor, then the user object is successfully saved in the LINE A. And if it's not and there's an oauth token available, then we try to fetch the user from the DB and log him/her in.

Create a new user with new openid login authlogic

I've implemented authlogic in a rails site, and I'm trying to get openid to work correctly. So far, you can login just fine as long as you have an existing account, but not so much if you don't. I'd like to be able to automagically create a new account if the identity_url is not already in the database.
The problem is that I also need to store some additional info. if the user is logging in for the first time with their openid, I'd like to ask them to fill in basic info (name, email), BEFORE the account is created.
I've played around with a few methods, but nothing seems to be working.
Thanks in advance for any input!
acts_as_authentic do |c|
c.openid_required_fields = [:email,"http://axschema.org/contact/email"]
end
Will allow you to require an email. I'm unsure of how to require other fields, but maybe check that axschema.org page. There is no need for the user to fill anything out other than their OpenID provider URL.
Combining login and registration could be done with something like this (untested create method from UserSessions controller, like from the authlogic tutorial stuff)
def create
if User.find_by_openid_provider(params[:user_session]).nil? # or something like that
#user = User.new(params[:user_session])
if #user.save
redirect_to whatever_path
else
# handle error
end
else
#user_session = UserSession.new(params[:user_session])
if #user_session.save
add_message 'Login successful!'
redirect_to whatever_path
else
render :action => :new
end
end
end
Maybe try putting the additional information into a temp table of some kind, and keep track of the session the user is in. Once they have authenticated, connect the previously entered information with the OpenID information to create the real user.

Resources