I am using rails 3.2 with ruby 1.9.3 and devise 2.1.2.
I want an admin to create users with username and email.
How can i randomly generate a password for this user, and send him an email with his password?
First you should need create controller for handle regristration user by admin.
Assumed you name of controller is registrations_controller.rb
Here's app/controller/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
before_filter :resource_name
def resource_name
:user
end
def new
#user = User.new
end
def create
#user = User.new(params[:user])
generated_password = Devise.friendly_token.first(6) #password length 6
#user.password_confirmation = #user.password = generated_password
if #user.save
# Send Password Via Email
UserMailer.password_send(#user).deliver
redirect_to a_path
else
render action: "new"
end
end
Here's app/mailer/user_mailer.rb
class UserMailer < ActionMailer::Base
default :from => "youremail#email.com"
def password_send(user)
#user = user
mail(:to => user.email, :subject => "password", :from => "youremail#email.com")
end
end
Here's app/views/user_mailer/password_send.html.erb
Email : #user.email<br/>
Username : #user.username<br/>
Password : #user.password
Devise - Automatically generate password for users
Hope this help!
Randomly generate a password for a user
In your controller
pwd = Devise.friendly_token[0,16]
#user = User.new(params[:user])
#user.password_confirmation = #user.password = pwd
Send an email with his password
Take a look at this question: Send an actionmailer email upon user registration in devise rails 3 application
In the end it will boils down to something like:
mail(:to => "#{user.email}", :subject => "Welcome to My Awesome Site, your password #{pwd}")
Related
after setup devise
i would like to get the user by username or email with in a api session
I passed login to parameters but rails spits out a error
User.find_for_database_authentication(:login => params[:username][:email])
the overwrite of find_for_database_authentication on model is already done.
def self.find_for_database_authentication(warden_conditions)
Someone has any hint to spare?
Devise
class Api::SessionsController < Devise::SessionsController
respond_to :json
def create
resource = User.find_for_database_authentication(:login => params[:username][:email])
if resource.valid_password?(params[:login][:password])
sign_in(:user, resource)
render :json=> {:auth_token=>resource.authentication_token, :email=>resource.email}, :status => :ok
return
end
invalid_login_attempt
end
end
I did this by overriding find_for_database_authentication like this:
class User
def self.find_for_database_authentication(auth_hash)
self.where("username = :query OR email = :query", query: auth_hash[:email]).first
end
end
Nothing more was needed.
Try this: User.find_by(username: 'username') or User.find_by(email: 'your#email.com')
I'm developing an Ruby on Rails webapp and I'm trying to use LDAP authentication to authenticate my users, I have the connection set up and working to the LDAP, but now I can't find any examples or documentation online on how to write code to authenticate users against my LDAP on Ruby on Rails
I'm using: Ruby v2.2 and Rails v5.0.3 and the gem I'm using to connect to ldap is gem 'net-ldap', '~> 0.16.0'
This is my login form at the moment, authenticating with a sqlserver DB, but I want it to authenticate against my LDAP DB :
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_NumeroEmpregado(params[:NumeroEmpregado])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to '/'
else
flash[:error] = "Erro! \nNĂºmero de Empregado e/ou password incorrecto(a)"
redirect_to '/login'
end
end
def destroy
session[:user_id] = nil
redirect_to '/index/new'
end
end
users_controller.rb
class UsersController < ApplicationController
def new
end
def create
user = User.new(user_params)
if user.save
session[:user_id] = user.id
redirect_to '/'
else
flash[:error] = "Erro! \nNenhum dos campos pode ser deixado em branco"
redirect_to '/signup'
end
end
private
def user_params
params.require(:user).permit(:NumeroEmpregado, :nome, :password, :password_confirmation)
end
end
How can I reformulate this code into authenticating with my LDAP DB?
You could create a service that handles that process:
app/services/authenticate_user.rb
class AuthenticateUser
def initialize(user, password)
#user = user
#password = password
end
def call
user_is_valid?
end
private
def user_is_valid?
ldap = Net::LDAP.new
ldap.host = your_server_ip_address
ldap.port = 389
ldap.auth(#user, #password)
ldap.bind
end
end
Then use it in your controller:
class SessionsController < ApplicationController
def new
end
def create
username = params[:NumeroEmpregado]
password = params[:password]
name = "Some Name" # Change "Some Name" to set the correct name
if AuthenticateUser.new(username, password).call
user = User.create_with(nome: name).find_or_create_by(NumeroEmpregado: username)
session[:user_id] = user.id
redirect_to '/'
else
flash[:error] = "Erro! \nNĂºmero de Empregado e/ou password incorrecto(a)"
redirect_to '/login'
end
end
def destroy
session[:user_id] = nil
redirect_to '/index/new'
end
end
AuthenticateUser.new(user, password).call will return true when valid user and password are provided, and will return false otherwise.
This is a basic example covering only the LDAP authentication, you will need to adapt it for your specific needs, including exception handling.
I'm using devise with my Rails 4 app.
I have the following in my user.rb model:
def send_admin_mail
AdminMailer.new_user_waiting_for_approval(self).deliver
end
def send_user_welcome_mail
AdminMailer.new_user_waiting_for_access(user).deliver
end
The first method sends me an email when a new user registers. The aim is for the second method to send a welcome email to the new user. The first method works. The second raises an issue with 'no_method_error' (undefined method email in my callbacks controller).
My callback controller has the following:
def linkedin
#user = User.find_for_linkedin_oauth(request.env["omniauth.auth"])
if #user.persisted?
#user.send_admin_mail
#user.send_user_welcome_mail
redirect_to root_path, :event => :authentication
# sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
# set_flash_message(:notice, :success, :kind => "LinkedIn") if is_navigational_format?
else
session["devise.linkedin_data"] = request.env["omniauth.auth"]
redirect_to root_path
end
end
My admin_mailer has:
def new_user_waiting_for_approval(user)
#user = user
mail(to: "myemailaddress#gmail.com", from: "myemailaddress#gmail.com",
subject: "Registration Request #{user.first_name} #{user.last_name} <#{user.email}>")
end
def new_user_waiting_for_access(user)
#user = user
mail(to: user.email, from: "myemailaddress#gmail.com", subject: "Welcome to Co #{user.first_name}")
end
I'm wondering whether I need to replace user with current_user to make use of the devise method or maybe whether some variation on {} and/or "" is required around the user.email in the second method?? I've tried a few different variations and combinations but haven't had any success.
Thank you for your help.
def send_user_welcome_mail
AdminMailer.new_user_waiting_for_access(user).deliver
end
should be replaced with
def send_user_welcome_mail
AdminMailer.new_user_waiting_for_access(self).deliver
end
user -> self
I am attempting to send a confirmation email to a newly registered user using Rails 4.0.1 and Ruby 2.0.0.
I am not getting any errors but the mail just is not sending. Here is the relevant code:
config/environments/development.rb
...
config.action_mailer.smtp_settings = {
:authenication=>:plain,
:address=>"smpt.mailgun.org",
:port=>587,
:domain=>"sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org",
:user_name=>"postmaster#sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org",
:password=>"6j3c9l35tu33"
}
app/model/user.rb
...
def create
#user=User.new(user_params)
if #user.save
ModelMailer.account_activation(#user).deliver
redirect_to lessons_url
else
render :new
end
end
mailers/model_mailer.rb
class ModelMailer < ActionMailer::Base
default from: "me#sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org"
def account_activation(user)
#user = user
mail to: "myemail#gmail.com", subject: "Account Activation"
end
end
Any help would be appreciated.
I set up a basic sign in, login, sign out format for a rails app and I was going to give it a function so that if a person forgot their password they could get a email back. when I went click on submit password reset I got
Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
Extracted source (around line #3):
1: To reset your password click the URL below.
2:
3: <%= edit_password_reset_url(#user.password_reset_token) %>
4:
5: If you did not request your password to be reset please ignore this email and your password will stay as it is.
Rails.root: /Users/cheatermoves/nightclass/mainproject/project
Application Trace | Framework Trace | Full Trace
app/views/user_mailer/password_reset.text.erb:3:in `_app_views_user_mailer_password_reset_text_erb__3613112772785486465_70118994937040'
app/mailers/user_mailer.rb:6:in `password_reset'
app/models/user.rb:17:in `send_password_reset'
app/controllers/password_resets_controller.rb:7:in `create'
just completed rails cast 250 and was doing 274. Everything was fine until I got this problem.
here is my controllers. Password resets:
class PasswordResetsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
user.send_password_reset if user
redirect_to root_url, :notice => "Email sent with password reset instructions."
end
end
sessions:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
if params[:remember_me]
cookies.permanent[:auth_token] = user.auth_token
else
cookies[:auth_token] = user.auth_token
end
redirect_to root_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
cookies.delete(:auth_token)
redirect_to root_url, :notice => "Logged out!"
end
end
users:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = #user.id
redirect_to root_url, notice: "Thank you for signing up!"
else
render "new"
end
end
end
and application:
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
#current_user ||= User.find_by_auth_token( cookies[:auth_token]) if cookies[:auth_token]
end
helper_method :current_user
end
in environments/development.rb I have
config.action_mailer.default_url_options = { :host => "localhost:3000" }
here is my user model
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
validates_presence_of :password, :on => :create
before_create { generate_token(:auth_token) }
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
def send_password_reset
generate_token(:password_reset_token)
self.password_reset_sent_at = Time.zone.now
save!
UserMailer.password_reset(self).deliver
end
end
user_mailer.rb file
class UserMailer < ActionMailer::Base
default from: "from#example.com"
def password_reset(user)
#user = user
mail :to => user.email, :subject => "Password Reset"
end
end
anyone know what the problem is and how to fix it? I'm using rails 3.2.14 if anyone is wondering. Thanks!
Didn't read the part where you said that you already set your
config.default_url_options[:host] = "localhost:3000"
my bad, sorry