0

I'm creating a rails app that has two types of users: drivers and mechanics.

So far I have the drivers class (called "users") completely set up with profiles and attributes with a "cars" model connected so they can add cars to their profile.

Now I need to create "mechanic" users that will be like a business page, with address, services offered, etc, and these mechanics will then add drivers as their customers.

My intuition was to create a new mechanic model and set it up the same way as I did the user model but with the appropriate schema. I think I may run into issues with the sessions helper though, because "user" is used in a lot of the functions. I could duplicate these items in the sessions helper and replace "user" with "mechanic", but I'm not sure if that would work or not.

I considered using a gem like cancancan for user restrictions but it seems questionable. Also wondering if I could use the current "User" class and create two more models (drivers and mechanics) that inherit from User with specific functions for each.

I really need an idea of which direction to start in to make this happen, so any advice, links to helpful rails casts, etc would be amazing. Thanks!

sessions helper

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  def current_user?(user)
    user == current_user
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end

  # Redirects to stored location (or to the default).
  def redirect_back_or(default)
    redirect_to(root_url)
    session.delete(:forwarding_url)
  end

  # Stores the URL trying to be accessed.
  def store_location
    session[:forwarding_url] = request.url if request.get?
  end
end

user.rb

class User < ActiveRecord::Base
  has_many :cars
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :phone, presence:true
  validates :password, length: { minimum: 6 }, allow_blank: true

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  def forget
    update_attribute(:remember_digest, nil)
  end

  def feed
    Car.where("user_id = ?", id)
  end
end
        cookies.permanent.signed[:user_id] = user.id
        cookies.permanent[:remember_token] = user.remember_token
      end

      def current_user?(user)
        user == current_user
      end

      # Returns the user corresponding to the remember token cookie.
      def current_user
        if (user_id = session[:user_id])
          @current_user ||= User.find_by(id: user_id)
        elsif (user_id = cookies.signed[:user_id])
          user = User.find_by(id: user_id)
          if user && user.authenticated?(cookies[:remember_token])
            log_in user
            @current_user = user
          end
        end
      end

      # Returns true if the user is logged in, false otherwise.
      def logged_in?
        !current_user.nil?
      end

      def forget(user)
        user.forget
        cookies.delete(:user_id)
        cookies.delete(:remember_token)
      end

      # Logs out the current user.
      def log_out
        forget(current_user)
        session.delete(:user_id)
        @current_user = nil
      end

      # Redirects to stored location (or to the default).
      def redirect_back_or(default)
        redirect_to(root_url)
        session.delete(:forwarding_url)
      end

      # Stores the URL trying to be accessed.
      def store_location
        session[:forwarding_url] = request.url if request.get?
      end
    end

4 Answers 4

2

I recommend thinking about your setup slightly differently by separating authentication from authorization. User, Driver and Mechanic are separate but related concepts. A user is anyone who can access your application mechanics and drivers are roles assigned to a user (what they are authorized to do).

There are a variety of different ways to approach this and not knowing the exact nature of your application it would be hard to suggest a particular solution, but I think if you untangle these concerns you'll be much better off in the long run.

Here is a link to a good resource to get you started:

http://railsapps.github.io/rails-authorization.html

0

Use cancan gem .. you can find an episode of it in railscasts.com

1
  • cancan isn't supported by rails 4. Feb 27, 2015 at 6:45
0

I think, devise gem should help.

Check the getting started section (https://github.com/plataformatec/devise/blob/master/README.md#getting-started), where you can find information how to create different types of users.

Hope that helps!

0

Check out Pundit gem: https://github.com/elabs/pundit I used it on a recent project and liked it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.