is there any account recovery gem for ruby on rails that uses SMS? - ruby

I was wondering if there was any account recovery gem for a ruby on rails password allowing the app to send the user to his sms a pin to reset their password in the event the user forgets it? Googled but didn't see anything, figured I would ask here in case my google search string was just poorly written.
ruby on rails account recovery via sms

I'm not aware of any gem, but this sounds like something that wouldn't be terribly difficult to implement. As vgoff has mentioned, there are plenty of SMS services available to you.
Something along the lines of (haven't tested this):
class SMSReset < ActiveRecord::Base
TOKEN_LENGTH = 4
EXPIRY_TIME = 15.minutes
belongs_to :user
before_create :generate_token, :set_expiry
def dispatch_sms!
MySMSProvider.send_sms(to: user.mobile_number, body: "Your SMS token is: #{token}")
end
def has_not_expired?
expires_at > Time.now
end
private
def generate_token
self[:token] = SecureRandom.hex[0..TOKEN_LENGTH - 1].downcase
end
def set_expiry
self[:expires_at] = EXPIRY_TIME.from_now
end
end
class PasswordResetController < ApplicationController
def new
end
def create
#user = User.where(email: params[:email]).first
if #user
sms_reset = #user.create_sms_reset!
sms_reset.dispatch_sms!
flash.now[:success] = "Please enter the code that was sent to your phone in the field below"
else
flash.now[:error] = "No user was found by that email address"
render :new
end
end
def validate_token
sms_reset = SMSReset.where(user_id: params[:user_id], token: params[:token])
if sms_reset.present? && sms_reset.has_not_expired?
#user = sms_reset.user
render :password_reset_form
else
flash.now[:error] = "Sorry, that code wasn't recognized"
render :new
end
end
end
You'll want to handle errors, and there's room for improvement, but hopefully the gist makes sense.

Not that I am directly aware of, but https://www.ruby-toolbox.com/search?utf8=%E2%9C%93&q=sms gives some gems for SMS interaction.
That is one of the first places I look, as well as searching on github.com directly. RubyForge is another good source of information for finding gems.
https://rubyforge.org/search/?type_of_search=soft&words=sms&Search=Search

Related

Ruby - devise : confirmations_controller stop registrations_controller

I have a problem with devise I can't find the solution.
When a user sign_up, I need to call several services to make his profile. So here is the registrations_controller.rb.
require_relative '../../../app/services/affinities'
require_relative '../../../app/services/astroprofil'
require_relative '../../../app/services/geocode'
class Users::RegistrationsController < Devise::RegistrationsController
ASTROPROFIL = Astroprofil.new
AFFINITIES = Affinities.new
GEOCODE = Geocode.new
after_action :create_astroprofil, only: %i[new create]
after_action :create_affinities, only: %i[new create]
private
def create_astroprofil
return unless user_signed_in?
ASTROPROFIL.profil(current_user)
end
def create_affinities
return unless user_signed_in?
affinities(current_user, ten_mates)
end
def affinities(user, mates)
AFFINITIES.partner_report(user, mates)
AFFINITIES.sign_report(user, mates)
AFFINITIES.match_percentage(user, mates)
end
def ten_mates
mates_by_gender = User.where(gender: current_user.looking_for).where.not(id: current_user.id)
return mates_by_gender.sample(10)
end
end
When I sign up everything works perfectly, a new user is entirely created.
But as soon as I try to add a confirmation per mail with devise, the mails are sent but it stops the 'create_astroprofil' and the 'create_affinities' methods.
Do you have any idea about what's happening ?
I would say it's coming from this line
registrations_controller.rb#L28
Since you cannot login without having confirmed your email, I'm pretty sure create_astroprofil and create_affinities are called but their first line is return unless user_signed_in?.
2 options here:
Astroprofil.new and Affinities.new can be called for an unconfirmed user
Called create_astroprofil and create_affinities from ConfirmationController#show

Turning a single file into MVC without Rails

I need to take the single file code below and separate it into a Model, View, Controller (MVC) ruby program that can run by the ruby command in the command line without using Rails (for instructions on how to run this program from irb, check out the README.md on my RubyBank Github Repo).
require_relative 'view'
class BankAccount
attr_accessor :name, :balance
def initialize(name, balance=0)
#name = name
#balance = balance
end
def show_balance(pin_access)
if pin_access == pin || pin_access == bank_manager
puts "\nYour current balance is: $#{#balance}"
else
puts pin_error_message
end
end
def withdraw(pin_access, amount)
if pin_access == pin
#balance -= amount
puts "'\nYou just withdrew $#{amount} from your account. \n\nYour remaining balance is: $#{#balance}\n\n"
else
puts pin_error_message
end
if #balance < 0
#balance += amount
return overdraft_protection
end
end
def deposit(pin_access, amount)
if pin_access == pin
#balance += amount
puts "\nYou just deposited $#{amount} into your account. \n\nYour remaining balance is: $#{#balance}"
else
puts pin_error_message
end
end
private
def pin
#pin = 1234
end
def bank_manager
#bank_manager = 4321
end
def pin_error_message
puts "Invalid PIN number. Try again."
end
def overdraft_protection
puts "\nYou have overdrafted your account. We cannot complete your withdrawl. Please deposit money before trying again. \n\nYour corrected balance is $#{#balance}"
end
end
I am looking for a good place to start or a general approach towards taking on such a task.
A simple approach would be to create three classes:
BankAccount minus text output is your Model.
All the text I/O goes into your View. Prompt the user for an action or registration. Get the model (for displaying data) from your controller or use the model directly.
Your Controller is responsible for a) reacting to user input, b) modifying the model and c) for holding state not directly related to the BankAccount (this point is discussable) like being logged in or what actions are possible from your current state. Your Controller receives all actions with user supplied data from your view.
Clean separation between View and Controller may be a bit hard in a console application. Also, there are about a million possible ways to implement this in a MVC style. Most important point: no UI-Code (puts/gets) in your model.

Ruby on Rails: Having problems selecting correct parameters for a method depending on context the is method used

I am working on a application where Users can list their in-game items to trade with other Users. A user's profile url would be something like this:
/users/1/index
And their user listings profile would be something like
/users/1/listings/1
All other resources nested under users would be the same as the latter.
I am trying to implement a method that is called by a before_filter callback that checks to see if a user has blocked or is blocked by the user who owns the profile and respective nested resources such as ability to message them, view their listings etc. If either has blocked each other, then they redirected to the root page of the application. This is the method that I use for the before_filter:
def blocked_relationships
if blocked?
redirect_to :root
end
end
I used another method that checks the state of the relationships between the two users.
This is the method I found and worked on after some research courtesy of the Rails Recipes book:
def blocked?
Relationship.exists?(user_id: current_user.id, other_user_id: params[:user_id], status: "blocked") ||
Relationship.exists?(user_id: params[:user_id], other_user_id: current_user.id, status: "blocked")
end
The problem I have is that this method only works, for example, when User 1 is looking at User 2's items, messages, listings etc. because the url:
/users/2/listings [or items or etc]
will contain a params that makes reference to the user as params[:user_id]. params[:id] in this case and context will refer to the listings id.
BUT, if I am User 1 and I have blocked User 2 and visit User 2's profile, this method will not work because the url /users/2/index will use params[:id] to instead of params[:user_id].
I've been thinking about how to implement this in a DRY way but I can't seem to solve my problem other than doing something like this:
def blocked?
if params[:user_id].blank?
Relationship.exists?(user_id: current_user.id, other_user_id: params[:id], status: "blocked") ||
Relationship.exists?(user_id: params[:id], other_user_id: current_user.id, status: "blocked")
else
Relationship.exists?(user_id: current_user.id, other_user_id: params[:user_id], status: "blocked") ||
Relationship.exists?(user_id: params[:user_id], other_user_id: current_user.id, status: "blocked")
end
end
I also considered the possibility that I'm not even implementing my blocking feature correctly, but before I address that issue, I was wondering if anyone had any ideas on how to solve this problem. Any help or feedback would be greatly appreciated and I would be happy to add anymore information for clarification. Thanks!
Why not other_id = params[:user_id] || params[:id]? This is a way to override :id when :user_id is present.
About your blocking feature though, to me I'd like to see a user even if I've blocked them. I'd create a blocked_by_user_id field on the Relationship to see who did the blocking and only disallow the blocked party from seeing the user's profile.
You'd probably want to checkout authorization gems for rails like cancan or related (it's not my favorite but the most popular). However, you could handle it like this:
class User
has_many :relationships,
scope :accessible_by,
->(user) { where.not id: user.relationships.where(status: :blocked).pluck(:other_user_id) }
end
Then use the relationship User.accessible_by(current_user) on your controller instead of plainly User to retrieve resources. For example:
class UsersController < ApplicationController
def index
#users = User.accessible_by(current_user)
# bleh
end
def show
#user = User.accessible_by(current_user).find(params[:id])
# etc
end
end
When the resource is nested under a user you could do this:
class Users::PicturesController < UsersController
def index
#pictures = User.accessible_by(current_user)
.find(params[:user_id]).pictures
end
def show
#picture = User.accessible_by(current_user)
.find(params[:user_id]).pictures.find(params[:id])
end
end
When a user tries to access a resource that can't view, ActiveRecord::RecordNotFound will be raised, so you should handle it:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNorFound, with: :rescue_not_found
private
def rescue_not_found
redirect_to root_path,
notice: 'You can\'t access that with your current priveleges. '
end
end

Ruby Devise 2.2 add email address along with the user.email

Currently I am using ruby devise gem 2.2.3. And I tried to customize the confirmation_instructions for adding couple of email ids with the user email.
app/mailers/my_devise_mailer.rb
class MyDeviseMailer < Devise::Mailer
include Devise::Mailers::Helpers
def confirmation_instructions(record, opts={})
opts[:to] = "example1#mail.com, example2#mail.com"
super
end
end
config/initializers/devise.rb
config.mailer = "MyDeviseMailer"
And, I ran the following in my console
user = User.first
MyDeviseMailer.delay.confirmation_instructions(user)
I got a output without body message. PFA
Correct
Wrong
Can anyone tell me what I missed to add/configure?
You could create a new mailer instead and modify the headers of that one:
# app/mailers/my_mailer.rb
class MyMailer < Devise::Mailer
def headers_for(action, opts)
if action == :confirmation_instructions
super.merge!(to: ['example1#mail.com', 'example2#mail.com'])
else
super
end
end
end
Then tell Devise to use your mailer:
# config/initializers/devise.rb
config.mailer = MyMailer
super.merge!" will not work. Because it'll replace the value for the given key (:to). But, the requirement is to add two mail id's with 'To'. The following gist is working fine.
class MyMailer < Devise::Mailer
include Devise::Mailers::Helpers
def headers_for(action, opts={})
begin
super.merge!(to: [super[:to], 'example1#mail.com', 'example2#mail.com'], template_path: ["devise/mailer"]) if action == :confirmation_instructions
rescue Exception => e
super
end
end
end
Happy Coding!!

Accessing Sinatra scope from another class

I'm running a Sinatra application with a few extra classes pulled in for creating a User and a few others on the fly (no DB, it feeds in from a web service). I'm trying send out a flash notice (using https://github.com/nakajima/rack-flash) from within my User model but can't figure out how to get access to the flash method/variable because I'm out of scope.
Something like:
class User
def something
if true
flash[:notice] = 'Good job'
else
# nope
end
end
end
Which gets required into the Sinatra app by a simple require 'models/user'
This is an XY Problem[1]. Sinatra is responsible for sending out flash messages, not your User objects, so the code for setting the flash should be in your Sinatra app, not in your User class.
[1] http://www.perlmonks.org/index.pl?node_id=542341
You should not ask your User (model) to talk to the UI (view). That's bad/not MVC-clean. That's what a controller is for.
You can use either return values, exceptions, or throw/catch (which is not exception handling) to pass information from your model to your controller. For example, using return values:
post "/create_user" do
flash[:notice] = case User.something
when User then "User Created!"
when :nono then "That's not allowed"
when :later then "User queued to be created later."
end
end
class User
def self.something
if authorized
if can_create_now
new(...)
else
queue_create(...)
:later
end
else
:nono
end
end
end
Since I mentioned them above, following are examples using throw/catch and begin/rescue (exceptions). As the advisability of using either of these constructs is questionable, let us take a moment of silence to ponder if this is a good idea.
Here is an example using throw/catch:
post "/create_user" do
result = catch(:msg){ User.something }
flash[:notice] = case
when :nono then "That's not allowed"
when :later then "User queued to be created later."
else "User Created!"
end
end
class User
def self.something
throw :msg, :nono unless authorized
if can_create_now
new(...)
else
queue_create(...)
throw :msg, :later
end
end
end
Finally, here's an example using exceptions, though I'm not convinced that this will be appropriate for all (non-disastrous) cases where you want to flash unique messages to the user:
post "/create_user" do
flash[:notice] = "User Created!" # Assume all good
begin
User.something
rescue User::Trouble=>e
flash[:notice] = case e
when Unauthorized then "That's not allowed"
when DelayedCreate then "User queued to be created later."
else "Uh...Something bad happened."
end
end
end
class User
class Trouble < RuntimeError; end
class Unauthorized < Trouble; end
class DelayedCreate < Trouble; end
def self.something
raise Unauthorized unless authorized
if can_create_now
new(...)
else
queue_create(...)
raise DelayedCreate
end
end
end
Exceptions let you pass an additional data along (e.g. raise Unauthorized.new "No such account", or any custom properties you want to add to your class), and so may be more useful (when appropriate). Just remember to pass semantic results from your model to your controller, and let it translate them into user-facing messages.

Resources