Convert Figma logo to code with AI

Sorcery logosorcery

Magical Authentication

1,448
228
1,448
71

Top Related Projects

2,314

Magical authentication for Rails 3 & 4

23,904

Flexible authentication solution for Rails with Warden.

A simple ruby authentication solution.

Rails authentication with email & password.

OmniAuth is a flexible authentication system utilizing Rack middleware.

Quick Overview

Sorcery is a flexible authentication library for Ruby on Rails applications. It provides a modular approach to authentication, allowing developers to customize and extend functionality as needed. Sorcery aims to be simple to use while offering advanced features for more complex authentication scenarios.

Pros

  • Highly modular and customizable
  • Easy to set up and use for basic authentication
  • Supports various authentication methods (e.g., password, external providers)
  • Active development and community support

Cons

  • Less opinionated than some alternatives, which may require more configuration
  • Documentation can be overwhelming for beginners due to the many options
  • Some advanced features may require additional setup or plugins

Code Examples

  1. Basic user authentication:
class User < ApplicationRecord
  authenticates_with_sorcery!
end

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      auto_login(@user)
      redirect_to root_path
    else
      render :new
    end
  end
end
  1. Logging in a user:
class SessionsController < ApplicationController
  def create
    if login(params[:email], params[:password])
      redirect_back_or_to root_path, notice: 'Logged in successfully'
    else
      flash.now[:alert] = 'Login failed'
      render :new
    end
  end
end
  1. Requiring authentication for specific actions:
class ProtectedController < ApplicationController
  before_action :require_login

  def index
    @protected_data = "This is only visible to logged-in users"
  end
end

Getting Started

  1. Add Sorcery to your Gemfile:
gem 'sorcery'
  1. Run bundle install:
bundle install
  1. Run the Sorcery installer:
rails generate sorcery:install
  1. Run migrations:
rails db:migrate
  1. Add authentication to your User model:
class User < ApplicationRecord
  authenticates_with_sorcery!
end
  1. Implement login and logout actions in your controllers, and add appropriate views for user registration and login forms.

Competitor Comparisons

2,314

Magical authentication for Rails 3 & 4

Pros of sorcery (NoamB)

  • Original repository with longer history and established community
  • More comprehensive documentation and examples
  • Wider range of authentication options and integrations

Cons of sorcery (NoamB)

  • Less frequent updates and maintenance
  • Potentially outdated dependencies and compatibility issues
  • Fewer recent contributions from the community

Code Comparison

sorcery (NoamB):

class User < ActiveRecord::Base
  authenticates_with_sorcery!
end

sorcery (Sorcery):

class User < ApplicationRecord
  authenticates_with_sorcery!
end

The code snippets are nearly identical, with the main difference being the base class (ActiveRecord::Base vs ApplicationRecord). This reflects the evolution of Rails conventions over time.

Both repositories provide similar core functionality for authentication in Ruby on Rails applications. The Sorcery repository is a more recent fork that aims to maintain and update the original sorcery gem. It offers more frequent updates, improved compatibility with newer Rails versions, and active community support.

While the NoamB repository has a longer history and more comprehensive documentation, the Sorcery repository is likely to be more suitable for modern Rails applications due to its ongoing maintenance and compatibility efforts.

23,904

Flexible authentication solution for Rails with Warden.

Pros of Devise

  • More comprehensive out-of-the-box features, including password reset, account confirmation, and session management
  • Larger community and ecosystem, with more plugins and extensions available
  • Better integration with other popular Rails gems and frameworks

Cons of Devise

  • Can be complex and overwhelming for simple authentication needs
  • Less flexible and customizable compared to Sorcery's modular approach
  • Heavier footprint and potential performance impact on larger applications

Code Comparison

Devise configuration:

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :validatable

Sorcery configuration:

authenticates_with_sorcery!

Devise offers a more declarative approach with built-in modules, while Sorcery provides a simpler, more customizable setup. Devise's configuration is more verbose but includes more features by default, whereas Sorcery's minimal configuration allows for greater flexibility in choosing which authentication features to implement.

Both gems provide robust authentication solutions for Rails applications, but Devise is better suited for projects requiring a full-featured authentication system out of the box, while Sorcery is ideal for developers who prefer a lightweight, modular approach with more control over the authentication process.

A simple ruby authentication solution.

Pros of Authlogic

  • More mature and established, with a longer history in the Rails ecosystem
  • Offers a wider range of authentication options out-of-the-box
  • Provides more granular control over authentication processes

Cons of Authlogic

  • More complex configuration and setup process
  • Heavier codebase with more dependencies
  • Less actively maintained in recent years

Code Comparison

Authlogic configuration:

class UserSession < Authlogic::Session::Base
  # Configuration options here
end

Sorcery configuration:

Rails.application.config.sorcery.submodules = [:remember_me, :reset_password]
Rails.application.config.sorcery.configure do |config|
  # Configuration options here
end

Authlogic tends to use more object-oriented approaches, while Sorcery favors a more modular configuration style. Authlogic requires more setup code, but offers more flexibility. Sorcery aims for simplicity and ease of use, with a more streamlined configuration process.

Both libraries provide robust authentication solutions for Rails applications, but Sorcery has gained popularity in recent years due to its simplicity and active maintenance. Authlogic remains a solid choice for projects requiring more complex authentication scenarios or those already using it in legacy applications.

Rails authentication with email & password.

Pros of Clearance

  • Simpler setup and configuration out of the box
  • Maintained by thoughtbot, a well-known Ruby consultancy
  • Includes built-in views and controllers for common authentication actions

Cons of Clearance

  • Less flexible and customizable than Sorcery
  • Fewer authentication options and strategies available
  • Tightly coupled to Rails, making it less suitable for non-Rails projects

Code Comparison

Clearance user model:

class User < ApplicationRecord
  include Clearance::User
end

Sorcery user model:

class User < ApplicationRecord
  authenticates_with_sorcery!
end

Both Clearance and Sorcery aim to simplify authentication in Ruby applications, but they take different approaches. Clearance provides a more opinionated and streamlined solution, while Sorcery offers greater flexibility and customization options.

Clearance is ideal for developers who want a quick and easy authentication setup with minimal configuration. It works well for standard Rails applications and provides a solid foundation for basic authentication needs.

Sorcery, on the other hand, is better suited for developers who require more control over their authentication process or need to implement complex authentication scenarios. It supports various authentication methods and can be used in non-Rails Ruby applications.

Ultimately, the choice between Clearance and Sorcery depends on the specific requirements of your project and your preferred level of customization.

OmniAuth is a flexible authentication system utilizing Rack middleware.

Pros of OmniAuth

  • Supports a wide range of authentication providers out-of-the-box
  • Highly modular and extensible architecture
  • Large community and extensive ecosystem of strategies

Cons of OmniAuth

  • Requires additional setup for basic authentication scenarios
  • Can be overkill for simple authentication needs
  • Slightly steeper learning curve for beginners

Code Comparison

OmniAuth configuration:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
  provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET']
end

Sorcery configuration:

Rails.application.config.sorcery.submodules = [:external]
Rails.application.config.sorcery.configure do |config|
  config.external_providers = [:github, :google]
end

OmniAuth focuses on providing a unified interface for multiple authentication providers, making it ideal for applications that require various login options. Sorcery, on the other hand, offers a more streamlined approach for basic authentication scenarios while still providing flexibility for external providers.

While OmniAuth excels in its extensive provider support and modularity, Sorcery shines in its simplicity and ease of use for common authentication tasks. The choice between the two depends on the specific requirements of your project and the level of complexity you're willing to manage.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Sorcery: Magical Authentication

Gem Version Gem Downloads Build Status

Magical Authentication for Rails. Supports ActiveRecord, DataMapper, Mongoid and MongoMapper.

Inspired by Restful Authentication, Authlogic and Devise. Crypto code taken almost unchanged from Authlogic. OAuth code inspired by OmniAuth and Ryan Bates's Railscast about it.

Philosophy

Sorcery is a stripped-down, bare-bones authentication library, with which you can write your own authentication flow. It was built with a few goals in mind:

  • Less is more - less than 20 public methods to remember for the entire feature-set make the lib easy to 'get'.
  • No built-in or generated code - use the library's methods inside your own MVC structures, and don't fight to fix someone else's.
  • Magic yes, Voodoo no - the lib should be easy to hack for most developers.
  • Configuration over Confusion - Centralized (1 file), Simple & short configuration as possible, not drowning in syntactic sugar.
  • Keep MVC cleanly separated - DB is for models, sessions are for controllers. Models stay unaware of sessions.

Table of Contents

  1. Useful Links
  2. API Summary
  3. Installation
  4. Configuration
  5. Full Features List by Module
  6. Planned Features
  7. Contributing
  8. Contact
  9. License

Useful Links

Check out the tutorials in the wiki for more:

API Summary

Below is a summary of the library methods. Most method names are self explaining and the rest are commented:

Core

require_login # This is a before action
login(email, password, remember_me = false)
auto_login(user) # Login without credentials
logout
logged_in? # Available in views
current_user # Available in views
redirect_back_or_to # Use when a user tries to access a page while logged out, is asked to login, and we want to return him back to the page he originally wanted
@user.external? # Users who signed up using Facebook, Twitter, etc.
@user.active_for_authentication? # Add this method to define behaviour that will prevent selected users from signing in
@user.valid_password?('secret') # Compares 'secret' with the actual user's password, returns true if they match
User.authenticates_with_sorcery!

HTTP Basic Auth

require_login_from_http_basic # This is a before action

External

login_at(provider) # Sends the user to an external service (Facebook, Twitter, etc.) to authenticate
login_from(provider) # Tries to login from the external provider's callback
create_from(provider) # Create the user in the local app database
build_from(provider) # Build user instance using user_info_mappings

Remember Me

auto_login(user, should_remember = false) # Login without credentials, optional remember_me
remember_me!
forget_me!
force_forget_me! # Forgets all sessions by clearing the token, even if remember_me_token_persist_globally is set to true

Reset Password

User.load_from_reset_password_token(token)
@user.generate_reset_password_token! # Use if you want to send the email by yourself
@user.deliver_reset_password_instructions! # Generates the token and sends the email
@user.change_password(new_password)
@user.change_password!(new_password) # Same as change_password but raises exception on save

Session Timeout

invalidate_active_sessions! #Invalidate all sessions with a login_time or last_action_time before the current time. Must Opt-in

User Activation

User.load_from_activation_token(token)
@user.setup_activation
@user.activate!

Please see the tutorials in the github wiki for detailed usage information.

Installation

Add this line to your application's Gemfile:

gem 'sorcery'

And then execute:

$ bundle

Or install it yourself as:

$ gem install sorcery

Configuration

Run the following command to generate the core migration file, the initializer file and the User model class.

$ rails generate sorcery:install

Run the following command generate the migrations files for remember_me and reset_password submodules and will create the initializer file (and add submodules to it), and create the User model class.

$ rails generate sorcery:install remember_me reset_password

Run the following command to generate the core migration file, the initializer and change the model class (in the initializer and migration files) to the class Person (and its pluralized version, 'people')

$ rails generate sorcery:install --model Person

Run the following command to generate only the migration files for the specified submodules and will add them to the initializer file.

$ rails generate sorcery:install http_basic_auth external remember_me --only-submodules

Inside the initializer, the comments will tell you what each setting does.

Full Features List by Module

Core (see lib/sorcery/model.rb and lib/sorcery/controller.rb):

  • Login / logout, optional return user to requested url on login, configurable redirect for non-logged-in users.
  • Password encryption, algorithms: bcrypt (default), MD5, SHA-1, SHA-256, SHA-512, AES or custom. Configurable stretches and salt.
  • Configurable attribute names for username, password and email.
  • Allow multiple fields to serve as username.

User Activation (see lib/sorcery/model/submodules/user_activation.rb):

  • User activation by email with optional success email
  • Configurable attribute names
  • Configurable mailer, method name, and attribute name
  • Configurable temporary token expiration
  • Optionally prevent non-active users to login

Reset Password (see lib/sorcery/model/submodules/reset_password.rb):

  • Reset password with email verification
  • Configurable mailer, method name, and attribute name
  • Configurable temporary token expiration
  • Configurable time between emails (hammering protection)

Remember Me (see lib/sorcery/model/submodules/remember_me.rb):

  • Remember me with configurable expiration
  • Configurable attribute names
  • Configurable to persist globally (supporting multiple browsers at the same time), or starting anew after each login

Session Timeout (see lib/sorcery/controller/submodules/session_timeout.rb):

  • Configurable session timeout
  • Optionally session timeout will be calculated from last user action
  • Optionally enable a method to clear all active sessions, expects an invalidate_sessions_before datetime attribute.

Brute Force Protection (see lib/sorcery/model/submodules/brute_force_protection.rb):

  • Brute force login hammering protection
  • configurable logins before lock and lock duration

Basic HTTP Authentication (see lib/sorcery/controller/submodules/http_basic_auth.rb):

  • A before action for requesting authentication with HTTP Basic
  • Automatic login from HTTP Basic
  • Automatic login is disabled if session key changed

Activity Logging (see lib/sorcery/model/submodules/activity_logging.rb):

  • Automatic logging of last login, last logout, last activity time and IP address for last login
  • Configurable timeout by which to decide whether to include a user in the list of logged in users

External (see lib/sorcery/controller/submodules/external.rb):

  • OAuth1 and OAuth2 support (currently: Twitter, Facebook, Github, Google, Heroku, LinkedIn, VK, LiveID, Xing, Salesforce)
  • Configurable database column names
  • Authentications table

Planned Features

  • Passing a block to encrypt, allowing the developer to define his own mix of salting and encrypting
  • Forgot username, maybe as part of the reset_password module
  • Scoping logins (to a subdomain or another arbitrary field)
  • Allowing storing the salt and encrypted password in the same DB field for extra security
  • Other reset password strategies (security questions?)
  • Other brute force protection strategies (captcha)

Have an idea? Let us know, and it might get into the gem!

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Sorcery/sorcery.

Contact

Feel free to ask questions using these contact details:

Current Maintainers:

Past Maintainers:

License

The gem is available as open source under the terms of the MIT License.