Skip to content

Custom user model

Justin Tomich edited this page Jul 3, 2017 · 4 revisions

If you have a model named something other than User, you can use authenticate with it, and all built-in features and generators will still function normally. Just tell authenticate about your alternate model class when you invoke the install generator.

For example, if you want to create a model named User::Profile, you can create the model and run it's migrations:

rails generate model User::Profile
rake db:migrate

Authenticate doesn't 'care' what your model class is named or how it's namespaced. When you run the authenticate install generator, use the model flag. This will install the authenticate initializer, with config.user_model set to your model class, and will generate all database migrations for your model's table. Run the migrations after the install generator runs, like so:

rails generate authenticate:install --model User::Profile
rake db:migrate

The authenticate initializer you just generated will look like this:

Authenticate.configure do |config|
  config.user_model = 'User::Profile' 

  # config.user_model = 'User'
  # config.cookie_name = 'authenticate_session_token'
  # config.cookie_expiration = { 1.month.from_now.utc }
  # config.cookie_domain = nil
  # config.cookie_path = '/'
  # config.secure_cookie = false   # set to true in production https environments
  # config.cookie_http_only = false # set to true if you can
  # config.mailer_sender = 'reply@example.com'
  # config.crypto_provider = Authenticate::Model::BCrypt
  # config.timeout_in = 45.minutes
  # config.max_session_lifetime = 8.hours
  # config.max_consecutive_bad_logins_allowed = 4
  # config.bad_login_lockout_period = 10.minutes
  # config.authentication_strategy = :email
  # config.redirect_url = '/'
  # config.allow_sign_up = true
  # config.routes = true
  # config.reset_password_within = 2.days
  # config.modules = []
end

Authenticate's built-in routes for signup and user creation will use your User::Profile class. If you wish to dump a copy of authenticate's routes into your config/routes.rb, use the routes generator.

rails generate authenticate:routes

The routes dumped into your config/routes.rb will feature your model class:

Rails.application.routes.draw do
  resource :session, controller: 'authenticate/sessions', only: [:create, :new, :destroy]
  resources :passwords, controller: 'authenticate/passwords', only: [:new, :create]

  resource :user_profiles, controller: 'authenticate/users', only: [:new, :create] do
    resources :passwords, controller: 'authenticate/passwords', only: [:edit, :update]
  end

  get '/sign_up', to: 'authenticate/users#new', as: 'sign_up'
  get '/sign_in', to: 'authenticate/sessions#new', as: 'sign_in'
  get '/sign_out', to: 'authenticate/sessions#destroy', as: 'sign_out'

  # other routes...
end
Clone this wiki locally