repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/spec/models/user_spec.rb | spec/models/user_spec.rb | require 'spec_helper'
describe User do
it { should have_db_column(:email).of_type(:string) }
it { should have_db_column(:encrypted_password).of_type(:string) }
it { should have_db_column(:reset_password_token).of_type(:string) }
it { should have_db_column(:remember_created_at).of_type(:datetime) }
it { should have_db_column(:sign_in_count).of_type(:integer) }
it { should have_db_column(:current_sign_in_at).of_type(:datetime) }
it { should have_db_column(:last_sign_in_at).of_type(:datetime) }
it { should have_db_column(:current_sign_in_ip).of_type(:string) }
it { should have_db_column(:last_sign_in_ip).of_type(:string) }
it { should have_and_belong_to_many(:roles) }
let(:user) { create(:user) }
let(:admin_role) { create(:role, :name => "admin") }
let(:customer_role) { create(:role, :name => "customer") }
describe ".role?" do
context "user has asked role" do
before do
user.roles.clear
user.roles << admin_role
end
it "returns true" do
user.role?(admin_role.name).should be_true
end
end
context "user doesn't have asked role" do
before do
user.roles.clear
user.roles << customer_role
end
it "returns false" do
user.role?(admin_role.name).should be_false
end
end
end
describe ".make_admin" do
before do
Role.find_or_create_by(:name => "admin")
user.make_admin
end
it "adds admin role to user" do
user.should be_admin
end
end
describe ".revoke_admin" do
before do
Role.find_or_create_by(:name => "admin")
user.make_admin
user.revoke_admin
end
it "removes admin role from user" do
user.should_not be_admin
end
end
describe ".admin?" do
before do
user.roles.clear
end
it "returns true if user is admin" do
user.roles << admin_role
user.admin?.should be_true
end
it "returns false is user is not admin" do
user.roles << customer_role
user.admin?.should be_false
end
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/application.rb | config/application.rb | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemdile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module BaseApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
config.i18n.enforce_available_locales = true
# Enable the asset pipeline
config.assets.enabled = true
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Heroku required setting
config.assets.initialize_on_precompile = false
end
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/environment.rb | config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
BaseApp::Application.initialize!
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/routes.rb | config/routes.rb | BaseApp::Application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
get "pages/index"
get "/admin" => "admin/base#index", :as => "admin"
namespace "admin" do
resources :users
end
root :to => "pages#index"
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/boot.rb | config/boot.rb | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/session_store.rb | config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
BaseApp::Application.config.session_store :cookie_store, :key => '_base-app_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# BaseApp::Application.config.session_store :active_record_store
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/devise.rb | config/initializers/devise.rb | # Use this hook to configure devise mailer, warden hooks and so forth. The first
# four configuration values can also be set straight in your models.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in DeviseMailer.
config.mailer_sender = "please-change-me@config-initializers-devise.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
config.stretches = 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "e548d5d4c56a6243d2f1be0558c4ffc1783f61ce073066901a8d8e80073f7c57e2d5ac617fc089fe22526dbe6a5b6c31c9d4931476d52aa85a99b99b17947f16"
# ==> Configuration for :confirmable
# The time you want to give your user to confirm his account. During this time
# he will be able to access your application without confirming. Default is 0.days
# When confirm_within is zero, the user won't be able to sign in without confirming.
# You can use this to let your user access some features of your application
# without confirming the account, but blocking it after a certain period
# (ie 2 days).
# config.allow_unconfirmed_access_for = 2.days
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# ==> Configuration for :validatable
# Range for password length. Default is 6..20.
# config.password_length = 6..20
# Regex to use to validate the email address
# config.email_regexp = /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
#
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# If true, authentication through token does not store user in session and needs
# to be supplied on each request. Useful if you are using the token as API token.
# config.skip_session_storage << :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Configure sign_out behavior.
# Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
# The default is true, which means any logout action will sign out all active scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The :"*/*" and "*/*" formats below is required to match Internet
# Explorer requests.
# config.navigational_formats = [:"*/*", "*/*", :html]
# The default HTTP method used to sign out a resource. Default is :get.
# config.sign_out_via = :get
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET']
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.failure_app = AnotherApp
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
config.secret_key = ENV["DEVISE_SECRET_KEY"] || '696acf756fc36cde5c1654ade4ff0449fc095863a4bdccbc6cb55f5321d7268337128e5deee3771d5bee26a21f31bd160b2e91dfdec9dcd4d354b5e9404b6455'
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/inflections.rb | config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/initializers/secret_token.rb | config/initializers/secret_token.rb | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
BaseApp::Application.config.secret_token = '187c3a1a542c273651401faf9be7e8142500c678170398c3a561c37621938038f69640a66cdab4e253819c058f78217a05e4a81321ca509f9cc67a6f74e60e44'
BaseApp::Application.config.secret_key_base = 'd913d9884865b84bd09f22265129ad0c6a3725598d730560002d84f1a9eb33c0bdd479637a9916993b4c777724f3d886e9ac7f25d539054ac1ccc95b3b06a466'
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/environments/test.rb | config/environments/test.rb | BaseApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = { :host => 'localhost' }
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/environments/development.rb | config/environments/development.rb | BaseApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
renderedtext/base-app | https://github.com/renderedtext/base-app/blob/a90c8bb8649cff2b05de8ae59ea07b40cde392bd/config/environments/production.rb | config/environments/production.rb | BaseApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
| ruby | MIT | a90c8bb8649cff2b05de8ae59ea07b40cde392bd | 2026-01-04T17:58:16.689142Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/unauthorized_controller.rb | app/controllers/unauthorized_controller.rb | class UnauthorizedController < ActionController::Metal
def self.call(env)
@respond ||= action(:respond)
@respond.call(env)
end
def respond
self.response_body = "Unauthorized Action"
self.status = :unauthorized
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/concerns/rails_jwt_auth/params_helper.rb | app/controllers/concerns/rails_jwt_auth/params_helper.rb | module RailsJwtAuth
module ParamsHelper
private
def registration_create_params
params.require(RailsJwtAuth.model_name.underscore).permit(
RailsJwtAuth.auth_field_name, :password, :password_confirmation
)
end
def confirmation_create_params
params.require(:confirmation).permit(RailsJwtAuth.email_field_name)
end
def session_create_params
params.require(:session).permit(RailsJwtAuth.auth_field_name, :password)
end
def reset_password_create_params
params.require(:reset_password).permit(RailsJwtAuth.email_field_name)
end
def reset_password_update_params
params.require(:reset_password).permit(:password, :password_confirmation)
end
def invitation_create_params
params.require(:invitation).permit(RailsJwtAuth.email_field_name)
end
def invitation_update_params
params.require(:invitation).permit(:password, :password_confirmation)
end
def profile_update_params
params.require(:profile).except(
RailsJwtAuth.auth_field_name, :current_password, :password, :password_confirmation
)
end
def profile_update_password_params
params.require(:profile).permit(:current_password, :password, :password_confirmation)
end
def profile_update_email_params
params.require(:profile).permit(RailsJwtAuth.auth_field_name, :password)
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/concerns/rails_jwt_auth/render_helper.rb | app/controllers/concerns/rails_jwt_auth/render_helper.rb | module RailsJwtAuth
module RenderHelper
def render_session(jwt, user)
auth_field = RailsJwtAuth.auth_field_name
render json: {session: {jwt: jwt, auth_field => user[auth_field]}}, status: 201
end
def render_registration(resource)
render json: resource, root: true, status: 201
end
def render_profile(resource)
render json: resource, root: true, status: 200
end
def render_204
head 204
end
def render_404
head 404
end
def render_410
head 410
end
def render_422(errors)
render json: {errors: errors}, status: 422
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/concerns/rails_jwt_auth/authenticable_helper.rb | app/controllers/concerns/rails_jwt_auth/authenticable_helper.rb | module RailsJwtAuth
NotAuthorized = Class.new(StandardError)
module AuthenticableHelper
def current_user
@current_user
end
def jwt_payload
@jwt_payload
end
def signed_in?
!current_user.nil?
end
def get_jwt_from_request
request.env['HTTP_AUTHORIZATION']&.split&.last
end
def authenticate!
begin
@jwt_payload = RailsJwtAuth::JwtManager.decode(get_jwt_from_request).first
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
unauthorize!
end
if !@current_user = RailsJwtAuth.model.from_token_payload(@jwt_payload)
unauthorize!
else
track_request
end
end
def authenticate
begin
@jwt_payload = RailsJwtAuth::JwtManager.decode(get_jwt_from_request).first
@current_user = RailsJwtAuth.model.from_token_payload(@jwt_payload)
rescue JWT::ExpiredSignature, JWT::VerificationError, JWT::DecodeError
@current_user = nil
end
track_request
end
def unauthorize!
raise NotAuthorized
end
def track_request
if @current_user&.respond_to? :update_tracked_request_info
@current_user.update_tracked_request_info(request)
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/profiles_controller.rb | app/controllers/rails_jwt_auth/profiles_controller.rb | module RailsJwtAuth
class ProfilesController < ApplicationController
include AuthenticableHelper
include ParamsHelper
include RenderHelper
PASSWORD_PARAMS = %i[current_password password password_confirmation].freeze
before_action :authenticate!
def show
render_profile current_user
end
def update
if current_user.update(profile_update_params)
render_204
else
render_422(current_user.errors.details)
end
end
def password
if current_user.update_password(update_password_params)
render_204
else
render_422(current_user.errors.details)
end
end
def email
return update unless current_user.is_a?(RailsJwtAuth::Confirmable)
if current_user.update_email(profile_update_email_params)
render_204
else
render_422(current_user.errors.details)
end
end
protected
def changing_password?
profile_update_params.values_at(*PASSWORD_PARAMS).any?(&:present?)
end
def update_password_params
profile_update_password_params.merge(current_auth_token: jwt_payload['auth_token'])
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/unlock_accounts_controller.rb | app/controllers/rails_jwt_auth/unlock_accounts_controller.rb | module RailsJwtAuth
class UnlockAccountsController < ApplicationController
include ParamsHelper
include RenderHelper
def update
return render_404 unless
params[:id] &&
(user = RailsJwtAuth.model.where(unlock_token: params[:id]).first)
user.unlock_access ? render_204 : render_422(user.errors.details)
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/invitations_controller.rb | app/controllers/rails_jwt_auth/invitations_controller.rb | module RailsJwtAuth
class InvitationsController < ApplicationController
include AuthenticableHelper
include ParamsHelper
include RenderHelper
before_action :authenticate!, only: [:create]
before_action :set_user_from_token, only: [:show, :update]
# used to verify token
def show
return render_404 unless @user
@user.expired_invitation_token? ? render_410 : render_204
end
# used to invite a user, if user is invited send new invitation
def create
user = RailsJwtAuth.model.invite(invitation_create_params)
user.errors.empty? ? render_204 : render_422(user.errors.details)
end
# used to accept invitation
def update
return render_404 unless @user
if @user.accept_invitation(invitation_update_params)
render_204
else
render_422(@user.errors.details)
end
end
private
def set_user_from_token
return if params[:id].blank?
@user = RailsJwtAuth.model.where(invitation_token: params[:id]).first
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/reset_passwords_controller.rb | app/controllers/rails_jwt_auth/reset_passwords_controller.rb | module RailsJwtAuth
class ResetPasswordsController < ApplicationController
include ParamsHelper
include RenderHelper
before_action :set_user_from_token, only: [:show, :update]
before_action :set_user_from_email, only: [:create]
# used to verify token
def show
return render_404 unless @user
if @user.reset_password_sent_at < RailsJwtAuth.reset_password_expiration_time.ago
return render_410
end
render_204
end
# used to request restore password
def create
unless @user
if RailsJwtAuth.avoid_email_errors
return render_204
else
return render_422(RailsJwtAuth.email_field_name => [{error: :not_found}])
end
end
@user.send_reset_password_instructions ? render_204 : render_422(@user.errors.details)
end
# used to set new password
def update
return render_404 unless @user
if @user.set_reset_password(reset_password_update_params)
render_204
else
render_422(@user.errors.details)
end
end
private
def set_user_from_token
return if params[:id].blank?
@user = RailsJwtAuth.model.where(reset_password_token: params[:id]).first
end
def set_user_from_email
email = (reset_password_create_params[RailsJwtAuth.email_field_name] || '').strip
email.downcase! if RailsJwtAuth.downcase_auth_field
if email.blank?
return render_422(RailsJwtAuth.email_field_name => [{error: :blank}])
elsif !email.match?(RailsJwtAuth.email_regex)
return render_422(RailsJwtAuth.email_field_name => [{error: :format}])
end
@user = RailsJwtAuth.model.where(RailsJwtAuth.email_field_name => email).first
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/registrations_controller.rb | app/controllers/rails_jwt_auth/registrations_controller.rb | module RailsJwtAuth
class RegistrationsController < ApplicationController
include ParamsHelper
include RenderHelper
def create
user = RailsJwtAuth.model.new(registration_create_params)
user.save ? render_registration(user) : render_422(user.errors.details)
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/confirmations_controller.rb | app/controllers/rails_jwt_auth/confirmations_controller.rb | module RailsJwtAuth
class ConfirmationsController < ApplicationController
include ParamsHelper
include RenderHelper
before_action :set_user_from_token, only: [:show, :update]
before_action :set_user_from_email, only: [:create]
# used to verify token
def show
return render_404 unless @user
if user.confirmation_sent_at < RailsJwtAuth.confirmation_expiration_time.ago
return render_410
end
render_204
end
# used to resend confirmation
def create
unless @user
if RailsJwtAuth.avoid_email_errors
return render_204
else
return render_422(RailsJwtAuth.email_field_name => [{error: :not_found}])
end
end
@user.send_confirmation_instructions ? render_204 : render_422(@user.errors.details)
end
# used to accept confirmation
def update
return render_404 unless @user
@user.confirm ? render_204 : render_422(@user.errors.details)
end
private
def set_user_from_token
return if params[:id].blank?
@user = RailsJwtAuth.model.where(confirmation_token: params[:id]).first
end
def set_user_from_email
email = (confirmation_create_params[RailsJwtAuth.email_field_name] || '').strip
email.downcase! if RailsJwtAuth.downcase_auth_field
if email.blank?
return render_422(RailsJwtAuth.email_field_name => [{error: :blank}])
elsif !email.match?(RailsJwtAuth.email_regex)
return render_422(RailsJwtAuth.email_field_name => [{error: :format}])
end
@user = RailsJwtAuth.model.where(RailsJwtAuth.email_field_name => email).first
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/controllers/rails_jwt_auth/sessions_controller.rb | app/controllers/rails_jwt_auth/sessions_controller.rb | module RailsJwtAuth
class SessionsController < ApplicationController
include AuthenticableHelper
include ParamsHelper
include RenderHelper
def create
se = Session.new(session_create_params)
if se.generate!(request)
render_session se.jwt, se.user
else
render_422 se.errors.details
end
end
def destroy
return render_404 unless RailsJwtAuth.simultaneous_sessions.positive?
authenticate!
current_user.destroy_auth_token @jwt_payload['auth_token']
render_204
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/lockable.rb | app/models/concerns/rails_jwt_auth/lockable.rb | module RailsJwtAuth
module Lockable
BOTH_UNLOCK_STRATEGIES = %i[time email].freeze
def self.included(base)
base.class_eval do
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
field :failed_attempts, type: Integer
field :unlock_token, type: String
field :first_failed_attempt_at, type: Time
field :locked_at, type: Time
end
end
end
def lock_access
self.locked_at = Time.current
save(validate: false).tap do |result|
send_unlock_instructions if result && unlock_strategy_enabled?(:email)
end
end
def clean_lock
self.locked_at = nil
self.unlock_token = nil
reset_attempts
end
def unlock_access
clean_lock
save(validate: false) if changed?
end
def access_locked?
locked_at && !lock_expired?
end
def failed_attempt
return if access_locked?
reset_attempts if attempts_expired?
self.failed_attempts ||= 0
self.failed_attempts += 1
self.first_failed_attempt_at = Time.current if failed_attempts == 1
save(validate: false).tap do |result|
lock_access if result && attempts_exceeded?
end
end
protected
def send_unlock_instructions
self.unlock_token = generate_unlock_token
save(validate: false)
RailsJwtAuth.send_email(:unlock_instructions, self)
end
def lock_expired?
if unlock_strategy_enabled?(:time)
locked_at && locked_at < RailsJwtAuth.unlock_in.ago
else
false
end
end
def reset_attempts
self.failed_attempts = 0
self.first_failed_attempt_at = nil
end
def remaining_attempts
RailsJwtAuth.maximum_attempts - failed_attempts.to_i
end
def attempts_exceeded?
!remaining_attempts.positive?
end
def attempts_expired?
first_failed_attempt_at && first_failed_attempt_at < RailsJwtAuth.reset_attempts_in.ago
end
protected
def generate_unlock_token
loop do
token = RailsJwtAuth.friendly_token
return token unless self.class.where(unlock_token: token).exists?
end
end
def lock_strategy_enabled?(strategy)
RailsJwtAuth.lock_strategy == strategy
end
def unlock_strategy_enabled?(strategy)
RailsJwtAuth.unlock_strategy == strategy ||
(RailsJwtAuth.unlock_strategy == :both && BOTH_UNLOCK_STRATEGIES.include?(strategy))
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/invitable.rb | app/models/concerns/rails_jwt_auth/invitable.rb | module RailsJwtAuth
module Invitable
def self.included(base)
base.extend ClassMethods
base.class_eval do
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
# include GlobalID::Identification to use deliver_later method
# http://edgeguides.rubyonrails.org/active_job_basics.html#globalid
include GlobalID::Identification if RailsJwtAuth.deliver_later
field :invitation_token, type: String
field :invitation_sent_at, type: Time
field :invitation_accepted_at, type: Time
end
end
end
module ClassMethods
# Creates an user and sends an invitation to him.
def invite(attributes={})
attrs = ActiveSupport::HashWithIndifferentAccess.new(attributes.to_h)
auth_field = RailsJwtAuth.auth_field_name
auth_attribute = attrs.delete(auth_field)
record = RailsJwtAuth.model.find_or_initialize_by(auth_field => auth_attribute)
record.assign_attributes(attrs)
record.invite
record
end
end
# Sends an invitation to user
# If the user has pending invitation, new one is sent
def invite
if persisted? && !invitation_token
errors.add(RailsJwtAuth.auth_field_name, :registered)
return false
end
@inviting = true
self.invitation_token = generate_invitation_token
self.invitation_sent_at = Time.current
return false unless save_without_password
RailsJwtAuth.send_email(:invitation_instructions, self)
true
ensure
@inviting = false
end
# Finishes invitation process setting user password
def accept_invitation(params)
return false unless invitation_token.present?
self.assign_attributes(params)
valid?
errors.add(:password, :blank) if params[:password].blank?
errors.add(:invitation_token, :expired) if expired_invitation_token?
return false unless errors.empty?
self.invitation_accepted_at = Time.current
self.invitation_token = nil
self.invitation_sent_at = nil
self.confirmed_at = Time.current if respond_to?(:confirmed_at) && confirmed_at.nil?
save
end
def inviting?
@inviting || false
end
def valid_for_invite?
@inviting = true
valid_without_password?
ensure
@inviting = false
end
def expired_invitation_token?
expiration_time = RailsJwtAuth.invitation_expiration_time
return false if expiration_time.to_i.zero?
invitation_sent_at && invitation_sent_at < expiration_time.ago
end
protected
def generate_invitation_token
loop do
token = RailsJwtAuth.friendly_token
return token unless self.class.where(invitation_token: token).exists?
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/authenticatable.rb | app/models/concerns/rails_jwt_auth/authenticatable.rb | include ActiveModel::SecurePassword
module RailsJwtAuth
module Authenticatable
def self.included(base)
base.extend(ClassMethods)
base.class_eval do
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
field :password_digest, type: String
field :auth_tokens, type: Array, default: [] if RailsJwtAuth.simultaneous_sessions > 0
elsif defined?(ActiveRecord) && ancestors.include?(ActiveRecord::Base)
serialize :auth_tokens, type: Array
end
has_secure_password
before_validation do
if RailsJwtAuth.downcase_auth_field &&
public_send("#{RailsJwtAuth.auth_field_name}_changed?")
self[RailsJwtAuth.auth_field_name]&.downcase!
end
end
end
end
def load_auth_token
new_token = SecureRandom.base58(24)
if RailsJwtAuth.simultaneous_sessions > 1
tokens = (auth_tokens || []).last(RailsJwtAuth.simultaneous_sessions - 1)
self.auth_tokens = (tokens + [new_token]).uniq
else
self.auth_tokens = [new_token]
end
new_token
end
def regenerate_auth_token(token=nil)
self.auth_tokens -= [token] if token
token = load_auth_token
save ? token : false
end
def destroy_auth_token(token)
if RailsJwtAuth.simultaneous_sessions > 1
tokens = auth_tokens || []
update_attribute(:auth_tokens, tokens - [token])
else
update_attribute(:auth_tokens, [])
end
end
def to_token_payload(_request=nil)
if RailsJwtAuth.simultaneous_sessions > 0
auth_tokens&.last ? {auth_token: auth_tokens.last} : false
else
{id: id.to_s}
end
end
def save_without_password
# when set password to nil only password_digest is setted to nil
# https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb#L97
instance_variable_set("@password", nil)
self.password_confirmation = nil
self.password_digest = nil
return false unless valid_without_password?
save(validate: false)
end
def valid_without_password?
valid?
errors.delete(:password) # allow register without pass
errors.delete(:password_confirmation)
errors.empty?
end
def update_password(params)
current_password_error = if (current_password = params.delete(:current_password)).blank?
'blank'
elsif !authenticate(current_password)
'invalid'
end
# if recoberable module is enabled ensure clean recovery to allow save
if self.respond_to? :reset_password_token
self.reset_password_token = self.reset_password_sent_at = nil
end
# close all sessions or other sessions when pass current_auth_token
current_auth_token = params.delete :current_auth_token
self.auth_tokens = current_auth_token ? [current_auth_token] : []
assign_attributes(params)
valid? # validates first other fields
errors.add(:current_password, current_password_error) if current_password_error
errors.add(:password, 'blank') if params[:password].blank?
return false unless errors.empty?
return false unless save
deliver_password_changed_notification
true
end
protected
def deliver_password_changed_notification
return unless RailsJwtAuth.send_password_changed_notification
RailsJwtAuth.send_email(:password_changed_notification, self)
end
module ClassMethods
def from_token_payload(payload)
if RailsJwtAuth.simultaneous_sessions > 0
get_by_token(payload['auth_token'])
else
where(id: payload['id']).first
end
end
def get_by_token(token)
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
where(auth_tokens: token).first
elsif defined?(ActiveRecord) && ancestors.include?(ActiveRecord::Base)
where('auth_tokens like ?', "%#{token}%").first
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/recoverable.rb | app/models/concerns/rails_jwt_auth/recoverable.rb | module RailsJwtAuth
module Recoverable
def self.included(base)
base.class_eval do
if defined?(Mongoid) && base.ancestors.include?(Mongoid::Document)
# include GlobalID::Identification to use deliver_later method
# http://edgeguides.rubyonrails.org/active_job_basics.html#globalid
include GlobalID::Identification if RailsJwtAuth.deliver_later
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
end
end
end
def send_reset_password_instructions
email_field = RailsJwtAuth.email_field_name # ensure email field es valid
if self.class.ancestors.include?(RailsJwtAuth::Confirmable) && !confirmed?
errors.add(email_field, :unconfirmed)
return false
end
if self.class.ancestors.include?(RailsJwtAuth::Lockable) &&
lock_strategy_enabled?(:failed_attempts) && access_locked?
errors.add(email_field, :locked)
return false
end
self.reset_password_token = generate_reset_password_token
self.reset_password_sent_at = Time.current
return false unless save
RailsJwtAuth.send_email(:reset_password_instructions, self)
end
def set_reset_password(params)
self.assign_attributes(params)
valid?
errors.add(:password, :blank) if params[:password].blank?
errors.add(:reset_password_token, :expired) if expired_reset_password_token?
return false unless errors.empty?
clean_reset_password
self.auth_tokens = [] # reset all sessions
save
end
def expired_reset_password_token?
expiration_time = RailsJwtAuth.reset_password_expiration_time
return false if expiration_time.to_i.zero?
reset_password_sent_at && reset_password_sent_at < expiration_time.ago
end
def clean_reset_password
self.reset_password_sent_at = nil
self.reset_password_token = nil
end
protected
def generate_reset_password_token
loop do
token = RailsJwtAuth.friendly_token
return token unless self.class.where(reset_password_token: token).exists?
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/confirmable.rb | app/models/concerns/rails_jwt_auth/confirmable.rb | # frozen_string_literal: true
module RailsJwtAuth
module Confirmable
def self.included(base)
base.class_eval do
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
# include GlobalID::Identification to use deliver_later method
# http://edgeguides.rubyonrails.org/active_job_basics.html#globalid
include GlobalID::Identification if RailsJwtAuth.deliver_later
field :unconfirmed_email, type: String
field :confirmation_token, type: String
field :confirmation_sent_at, type: Time
field :confirmed_at, type: Time
end
validate :validate_confirmation, if: :confirmed_at_changed?
after_create do
unless confirmed_at || confirmation_sent_at || self['invitation_token']
send_confirmation_instructions
end
end
end
end
def send_confirmation_instructions
if confirmed? && !unconfirmed_email
errors.add(RailsJwtAuth.email_field_name, :already_confirmed)
return false
end
self.confirmation_token = generate_confirmation_token
self.confirmation_sent_at = Time.current
return false unless save
RailsJwtAuth.send_email(:confirmation_instructions, self)
true
end
def confirmed?
confirmed_at.present?
end
def confirm
self.confirmed_at = Time.current
self.confirmation_token = nil
if unconfirmed_email
email_field = RailsJwtAuth.email_field_name
self[email_field] = unconfirmed_email
self.unconfirmed_email = nil
# supports email confirmation attr_accessor validation
if respond_to?("#{email_field}_confirmation")
instance_variable_set("@#{email_field}_confirmation", self[email_field])
end
end
save
end
def skip_confirmation
self.confirmed_at = Time.current
self.confirmation_token = nil
end
def update_email(params)
email_field = RailsJwtAuth.email_field_name.to_sym
params = HashWithIndifferentAccess.new(params)
# email change must be protected by password
password_error = if (password = params[:password]).blank?
:blank
elsif !authenticate(password)
:invalid
end
self.email = params[email_field]
self.confirmation_token = generate_confirmation_token
self.confirmation_sent_at = Time.current
valid? # validates first other fields
errors.add(:password, password_error) if password_error
errors.add(email_field, :not_change) unless email_changed?
return false unless errors.empty?
# move email to unconfirmed_email field and restore
self.unconfirmed_email = email
self.email = email_was
return false unless save
deliver_email_changed_emails
true
end
protected
def generate_confirmation_token
loop do
token = RailsJwtAuth.friendly_token
return token unless self.class.where(confirmation_token: token).exists?
end
end
def validate_confirmation
return true unless confirmed_at
email_field = RailsJwtAuth.email_field_name
if confirmed_at_was && !public_send("#{email_field}_changed?")
errors.add(email_field, :already_confirmed)
elsif confirmation_sent_at &&
(confirmation_sent_at < (Time.current - RailsJwtAuth.confirmation_expiration_time))
errors.add(:confirmation_token, :expired)
end
end
def deliver_email_changed_emails
# send confirmation to new email
RailsJwtAuth.send_email(:confirmation_instructions, self)
# send notify to old email
if RailsJwtAuth.send_email_change_requested_notification
RailsJwtAuth.send_email(:email_change_requested_notification, self)
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/models/concerns/rails_jwt_auth/trackable.rb | app/models/concerns/rails_jwt_auth/trackable.rb | module RailsJwtAuth
module Trackable
def track_session_info(request)
return unless request
self.last_sign_in_at = Time.current
self.last_sign_in_ip = request.respond_to?(:remote_ip) ? request.remote_ip : request.ip
end
def update_tracked_request_info(request)
return unless request
self.last_request_at = Time.current
self.last_request_ip = request.respond_to?(:remote_ip) ? request.remote_ip : request.ip
self.save(validate: false)
end
def self.included(base)
base.class_eval do
if defined?(Mongoid) && ancestors.include?(Mongoid::Document)
field :last_sign_in_at, type: Time
field :last_sign_in_ip, type: String
field :last_request_at, type: Time
field :last_request_ip, type: String
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/app/mailers/rails_jwt_auth/mailer.rb | app/mailers/rails_jwt_auth/mailer.rb | if defined?(ActionMailer)
class RailsJwtAuth::Mailer < ApplicationMailer
default from: RailsJwtAuth.mailer_sender
before_action do
@user = RailsJwtAuth.model.find(params[:user_id])
@to = @user[RailsJwtAuth.email_field_name]
@subject = I18n.t("rails_jwt_auth.mailer.#{action_name}.subject")
end
def confirmation_instructions
raise RailsJwtAuth::NotConfirmationsUrl unless RailsJwtAuth.confirm_email_url.present?
@confirm_email_url = add_param_to_url(
RailsJwtAuth.confirm_email_url,
'confirmation_token',
@user.confirmation_token
)
mail(to: @user.unconfirmed_email || @to, subject: @subject)
end
def email_change_requested_notification
mail(to: @to, subject: @subject)
end
def reset_password_instructions
raise RailsJwtAuth::NotResetPasswordsUrl unless RailsJwtAuth.reset_password_url.present?
@reset_password_url = add_param_to_url(
RailsJwtAuth.reset_password_url,
'reset_password_token',
@user.reset_password_token
)
mail(to: @to, subject: @subject)
end
def password_changed_notification
mail(to: @to, subject: @subject)
end
def invitation_instructions
raise RailsJwtAuth::NotInvitationsUrl unless RailsJwtAuth.accept_invitation_url.present?
@accept_invitation_url = add_param_to_url(
RailsJwtAuth.accept_invitation_url,
'invitation_token',
@user.invitation_token
)
mail(to: @to, subject: @subject)
end
def unlock_instructions
raise RailsJwtAuth::NotUnlockUrl unless RailsJwtAuth.unlock_account_url.present?
@unlock_account_url = add_param_to_url(RailsJwtAuth.unlock_account_url, 'unlock_token', @user.unlock_token)
mail(to: @to, subject: @subject)
end
protected
def add_param_to_url(url, param_name, param_value)
path, params = url.split '?'
params = params ? params.split('&') : []
params.push("#{param_name}=#{param_value}")
"#{path}?#{params.join('&')}"
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/rails_helper.rb | spec/rails_helper.rb | # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../dummy/config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# require 'rails_jwt_auth/spec/helpers'
Dir['spec/factories/**/*.rb'].each { |f| require "./#{f}" }
require 'rails_jwt_auth/spec_helpers'
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = '#{::Rails.root}/spec/fixtures'
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace('gem name')
#config.include RailsJwtAuth::Spec::Helpers
config.include ActiveSupport::Testing::TimeHelpers
config.before(:each) do
MongoidUser.destroy_all
ActiveRecordUser.destroy_all
ActionMailer::Base.deliveries.clear
RailsJwtAuth.simultaneous_sessions = 1
RailsJwtAuth.confirm_email_url = 'http://example.com/confirmations'
RailsJwtAuth.accept_invitation_url = 'http://example.com/invitations'
RailsJwtAuth.reset_password_url = 'http://example.com/reset_passwords'
RailsJwtAuth.avoid_email_errors = true
# Configuration for Lockable module
RailsJwtAuth.maximum_attempts = 3
RailsJwtAuth.lock_strategy = :failed_attempts
RailsJwtAuth.unlock_strategy = :both
RailsJwtAuth.unlock_in = 60.minutes
RailsJwtAuth.reset_attempts_in = 60.minutes
RailsJwtAuth.unlock_account_url = 'http://example.com/unlock-account'
end
end
def initialize_orm(orm)
RailsJwtAuth.model_name = "#{orm}User"
end
def get_record_error(record, field)
return nil unless record && field
field_error = record.errors&.details[field]&.first
field_error ? field_error[:error] : nil
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/spec_helper.rb | spec/spec_helper.rb | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/factories/sequences.rb | spec/factories/sequences.rb | FactoryBot.define do
sequence :email do |n|
"user#{n}@email.com"
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/factories/mongoid_user.rb | spec/factories/mongoid_user.rb | FactoryBot.define do
factory :mongoid_unconfirmed_user, class: MongoidUser do
email
password { '12345678' }
sequence(:username) { |n| "user_#{n}" }
end
factory :mongoid_user, parent: :mongoid_unconfirmed_user do
before :create do |user|
user.skip_confirmation
end
end
factory :mongoid_user_without_password, class: MongoidUser do
email
sequence(:username) { |n| "user_#{n}" }
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/factories/active_record_user.rb | spec/factories/active_record_user.rb | FactoryBot.define do
factory :active_record_unconfirmed_user, class: ActiveRecordUser do
email
password { '12345678' }
sequence(:username) { |n| "user_#{n}" }
end
factory :active_record_user, parent: :active_record_unconfirmed_user do
before :create do |user|
user.skip_confirmation
end
end
factory :active_record_user_without_password, class: ActiveRecordUser do
email
sequence(:username) { |n| "user_#{n}" }
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/registrations_controller_spec.rb | spec/controllers/registrations_controller_spec.rb | require 'rails_helper'
describe RailsJwtAuth::RegistrationsController do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
before do
allow_any_instance_of(RailsJwtAuth.model)
.to(receive(:send_confirmation_instructions).and_return(true))
end
let(:root) { RailsJwtAuth.model_name.underscore }
describe 'POST #create' do
before do
RailsJwtAuth.model.destroy_all
end
let(:json) { JSON.parse(response.body)['errors'] }
context 'when parameters are blank' do
before do
post :create, params: {root => {email: '', password: ''}}
end
it 'returns 422 status code' do
expect(response.status).to eq(422)
end
it 'returns errors messages' do
expect(json['email'].first['error']).to eq 'blank'
expect(json['password'].first['error']).to eq 'blank'
end
end
context 'when parameters are valid' do
before do
params = {email: 'user@email.com', password: '12345678'}
post :create, params: {root => params}
end
let(:json) { JSON.parse(response.body)[root] }
it 'creates new user' do
expect(RailsJwtAuth.model.count).to eq(1)
end
it 'returns 201 status code' do
expect(response.status).to eq(201)
end
it 'returns user info' do
expect(json['email']).to eq('user@email.com')
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/invitations_controller_spec.rb | spec/controllers/invitations_controller_spec.rb | require 'rails_helper'
RSpec.describe RailsJwtAuth::InvitationsController do
%w[ActiveRecord Mongoid].each do |orm|
context "Using #{orm}" do
before(:all) { initialize_orm(orm) }
let(:invited_user) { RailsJwtAuth.model.invite email: 'valid@example.com' }
let(:json) { JSON.parse(response.body) }
describe 'GET #show' do
context 'when token is valid' do
it 'returns 204 http status code' do
get :show, params: {id: invited_user.invitation_token}
expect(response).to have_http_status(204)
end
end
context 'when token is invalid' do
it 'returns 404 http status code' do
get :show, params: {id: 'invalid'}
expect(response).to have_http_status(404)
end
end
context 'when token is expired' do
it 'returns 410 http status code' do
travel_to(RailsJwtAuth.invitation_expiration_time.ago - 1.second) do
invited_user
end
get :show, params: {id: invited_user.invitation_token}
expect(response).to have_http_status(410)
end
end
end
describe 'POST #create' do
context 'when user is authenticated' do
before do
allow(subject).to receive(:authenticate!).and_return(true)
end
context 'without passing email as param' do
it 'raises ActiveRecord::ParameterMissing' do
expect { post :create, params: {} }.to raise_error ActionController::ParameterMissing
end
end
let(:email) { 'valid@example.com' }
context 'passing email as param' do
context 'without existing user' do
it 'returns HTTP 201 Created' do
post :create, params: {invitation: {email: 'test@example.com'}}
expect(response).to have_http_status(:no_content)
end
end
context 'with already invited user' do
it 'returns HTTP 201 Created' do
post :create, params: {invitation: {email: invited_user.email}}
expect(response).to have_http_status(:no_content)
end
end
context 'with already registered user' do
let(:registered_user) { FactoryBot.create "#{orm.underscore}_user" }
it 'returns HTTP 422 Unprocessable Entity' do
post :create, params: {invitation: {email: registered_user.email}}
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
end
context 'when user is not authenticated' do
it 'raises RailsJwtAuth::NotAuthorized' do
expect { post :create, params: {} }.to raise_error RailsJwtAuth::NotAuthorized
end
end
end
describe 'PUT #update' do
context 'when invited user' do
context 'with all params' do
before do
put :update, params: {
id: invited_user.invitation_token,
invitation: {password: 'abcdef', password_confirmation: 'abcdef'}
}
end
it 'returns HTTP 204 No content' do
expect(response).to have_http_status(:no_content)
end
it 'updates users password' do
expect(invited_user.password_digest).to_not eq(invited_user.reload.password_digest)
end
it 'deletes the token of the user' do
expect(invited_user.reload.invitation_token).to be_nil
end
end
context 'with invalid token' do
before do
put :update, params: {
id: 'invalid_token',
invitation: {password: 'abcdef', password_confirmation: 'abcdef'}
}
end
it 'returns HTTP 404' do
expect(response).to have_http_status(404)
end
end
context 'without password' do
before do
put :update, params: {
id: invited_user.invitation_token,
invitation: {password: ''}
}
end
it 'returns HTTP 422 with password error' do
expect(response).to have_http_status(422)
expect(json['errors']['password'].first['error']).to eq 'blank'
end
end
context 'with expired invitation' do
it 'returns HTTP 422 Unprocessable Entity' do
id = invited_user.invitation_token
travel_to(3.days.from_now) do
put :update, params: {
id: id,
invitation: {password: 'abcdef', password_confirmation: 'abcdef'}
}
end
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'with mismatching passwords' do
before do
put :update, params: {
id: invited_user.invitation_token,
invitation: {password: 'abcdef', password_confirmation: ''}
}
end
it 'returns HTTP 422 Unprocessable Entity' do
expect(response).to have_http_status(:unprocessable_entity)
end
it 'the token keeps in the user' do
expect(invited_user.invitation_token).to eq(invited_user.reload.invitation_token)
end
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/sessions_controller_spec.rb | spec/controllers/sessions_controller_spec.rb | require 'rails_helper'
require 'rails_jwt_auth/jwt_manager'
describe RailsJwtAuth::SessionsController do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:json) { JSON.parse(response.body) }
let(:user) { FactoryBot.create("#{orm.underscore}_user") }
let(:unconfirmed_user) { FactoryBot.create("#{orm.underscore}_unconfirmed_user") }
let(:locked_user) { FactoryBot.create("#{orm.underscore}_user", locked_at: 2.minutes.ago) }
describe 'POST #create' do
context 'when all is ok' do
before do
post :create, params: {session: {email: user.email, password: '12345678'}}
end
it 'returns 201 status code' do
expect(response.status).to eq(201)
end
it 'returns valid authentication token' do
jwt = json['session']['jwt']
token = RailsJwtAuth::JwtManager.decode(jwt)[0]['auth_token']
expect(token).to eq(user.reload.auth_tokens.last)
end
end
context 'when simultaneous sessions are 0' do
it 'returns id instead of token' do
allow(RailsJwtAuth).to receive(:simultaneous_sessions).and_return(0)
post :create, params: {session: {email: user.email, password: '12345678'}}
jwt = json['session']['jwt']
payload = RailsJwtAuth::JwtManager.decode(jwt)[0]
expect(payload['auth_token']).to be_nil
expect(payload['id']).to eq(user.id.to_s)
end
end
context 'when use diferent auth_field' do
before { RailsJwtAuth.auth_field_name = 'username' }
after { RailsJwtAuth.auth_field_name = 'email' }
it 'returns 201 status code' do
post :create, params: {session: {username: user.username, password: '12345678'}}
expect(response.status).to eq(201)
end
end
context 'when parameters are blank' do
it 'raises ActionController::ParameterMissing' do
expect { post :create, params: {} }.to raise_error ActionController::ParameterMissing
end
end
context 'when email is invalid' do
before do
post :create, params: {session: {email: 'invalid@email.com', password: '12345678'}}
end
it 'returns 422 status code' do
expect(response.status).to eq(422)
end
it 'returns error message' do
expect(json['errors']['session'].first['error']).to eq 'invalid'
end
end
context 'when password is invalid' do
before do
post :create, params: {session: {email: user.email, password: 'invalid'}}
end
it 'returns 422 status code' do
expect(response.status).to eq(422)
end
it 'returns error message' do
expect(json['errors']['session'].first['error']).to eq 'invalid'
end
end
context 'when user is not confirmed' do
before do
post :create, params: {session: {email: unconfirmed_user.email, password: '12345678'}}
end
it 'returns 422 status code' do
expect(response.status).to eq(422)
end
it 'returns error message' do
expect(json['errors']['email'].first['error']).to eq 'unconfirmed'
end
end
context 'when user is locked' do
before do
post :create, params: {session: {email: locked_user.email, password: '12345678'}}
end
it 'returns 422 status code' do
expect(response.status).to eq(422)
end
it 'returns error message' do
expect(json['errors']['email'].first['error']).to eq 'locked'
end
end
end
describe 'Delete #destroy' do
context 'when user is logged' do
before do
user.regenerate_auth_token
jwt_info = [{'auth_token' => user.auth_tokens.first}]
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_return(jwt_info)
delete :destroy
end
it 'returns 204 status code' do
expect(response.status).to eq(204)
end
it 'removes user token' do
expect(user.reload.auth_tokens).to eq([])
end
end
context 'when user is not logged' do
it 'raises RailsJwtAuth::NotAuthorized exception' do
expect { delete :destroy }.to raise_error RailsJwtAuth::NotAuthorized
end
end
context 'when simultaneous sessions are 0' do
it 'returns 404 status code' do
allow(RailsJwtAuth).to receive(:simultaneous_sessions).and_return(0)
delete :destroy
expect(response.status).to eq(404)
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/reset_passwords_controller_spec.rb | spec/controllers/reset_passwords_controller_spec.rb | require 'rails_helper'
describe RailsJwtAuth::ResetPasswordsController do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:json) { JSON.parse(response.body) }
let(:user) { FactoryBot.create("#{orm.underscore}_user", password: '12345678') }
let(:unconfirmed_user) { FactoryBot.create("#{orm.underscore}_unconfirmed_user") }
describe 'GET #show' do
context 'when token is valid' do
it 'returns 204 http status code' do
user.send_reset_password_instructions
get :show, params: {id: user.reset_password_token}
expect(response).to have_http_status(204)
end
end
context 'when token is invalid' do
it 'returns 404 http status code' do
get :show, params: {id: 'invalid'}
expect(response).to have_http_status(404)
end
end
context 'when token is expired' do
it 'returns 410 http status code' do
travel_to(RailsJwtAuth.reset_password_expiration_time.ago - 1.second) do
user.send_reset_password_instructions
end
get :show, params: {id: user.reset_password_token}
expect(response).to have_http_status(410)
end
end
end
describe 'POST #create' do
context 'when sends valid email' do
it 'returns 204 http status code' do
post :create, params: {reset_password: {email: user.email}}
expect(response).to have_http_status(204)
end
it 'upper case and down case are ignored' do
post :create, params: {reset_password: {email: user.email.upcase}}
expect(response).to have_http_status(204)
end
it 'leading and trailing spaces are ignored' do
post :create, params: {reset_password: {email: " #{user.email} "}}
expect(response).to have_http_status(204)
end
it 'sends new reset_password email with new token' do
expect(RailsJwtAuth).to receive(:send_email)
.with(:reset_password_instructions, anything)
old_token = user.reset_password_token
post :create, params: {reset_password: {email: user.email}}
expect(user.reload.reset_password_token).not_to eq(old_token)
end
context 'when user is unconfirmed' do
it 'returns 422 http status code' do
post :create, params: {reset_password: {email: unconfirmed_user.email}}
expect(response).to have_http_status(422)
end
it 'returns unconfirmed error message' do
post :create, params: {reset_password: {email: unconfirmed_user.email}}
expect(json['errors']['email'].first['error']).to eq 'unconfirmed'
end
end
end
context 'when send not registered email and avoid_email_errors is false' do
before do
RailsJwtAuth.avoid_email_errors = false
post :create, params: {reset_password: {email: 'not.found@email.com'}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns not found error' do
expect(json['errors']['email'].first['error']).to eq 'not_found'
end
end
context 'when send invalid email and avoid_email_errors is false' do
before do
RailsJwtAuth.avoid_email_errors = false
post :create, params: {reset_password: {email: 'invalid'}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns format error' do
expect(json['errors']['email'].first['error']).to eq 'format'
end
end
context 'when send not registered email and avoid_email_errors is true' do
before do
post :create, params: {reset_password: {email: 'not.found@email.com'}}
end
it 'returns 204 http status code' do
expect(response).to have_http_status(204)
end
end
context 'when send invalid email and avoid_email_errors is true' do
before do
post :create, params: {reset_password: {email: 'invalid'}}
end
it 'returns 204 http status code' do
expect(response).to have_http_status(422)
end
it 'returns format error' do
expect(json['errors']['email'].first['error']).to eq 'format'
end
end
context 'when send empty email' do
before do
post :create, params: {reset_password: {email: ''}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns not found error' do
expect(json['errors']['email'].first['error']).to eq 'blank'
end
end
end
describe 'PUT #update' do
context 'when send all params correctly' do
before do
user.send_reset_password_instructions
put :update, params: {
id: user.reset_password_token,
reset_password: {password: 'new_password'}
}
end
it 'returns 204 http status code' do
expect(response).to have_http_status 204
end
it 'updates password' do
expect(user.reload.authenticate('new_password')).to be_truthy
end
end
context 'when reset_password_token is invalid' do
before do
put :update, params: {id: 'invalid'}
end
it 'returns 404 http status code' do
expect(response).to have_http_status 404
end
end
context 'when password confirmation is invalid' do
before do
user.send_reset_password_instructions
put :update, params: {
id: user.reset_password_token,
reset_password: {password: 'a', password_confirmation: 'b'}
}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns confirmation error message' do
expect(json['errors']['password_confirmation'].first['error']).to eq 'confirmation'
end
end
context 'when password is blank' do
before do
user.send_reset_password_instructions
put :update, params: {
id: user.reset_password_token,
reset_password: {password: ''}
}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns blank error message' do
expect(json['errors']['password'].first['error']).to eq 'blank'
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/confirmations_controller_spec.rb | spec/controllers/confirmations_controller_spec.rb | require 'rails_helper'
describe RailsJwtAuth::ConfirmationsController do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:json) { JSON.parse(response.body) }
let!(:user) { FactoryBot.create("#{orm.underscore}_unconfirmed_user") }
describe 'POST #create' do
context 'when sends valid email' do
it 'returns 201 http status code' do
post :create, params: {confirmation: {email: user.email}}
expect(response).to have_http_status(204)
end
it 'sends new confirmation email with new token' do
expect(RailsJwtAuth).to receive(:send_email).with(:confirmation_instructions, anything)
old_token = user.confirmation_token
post :create, params: {confirmation: {email: user.email}}
expect(user.reload.confirmation_token).not_to eq(old_token)
end
end
context 'when send not registered email and avoid_email_errors is false' do
before do
RailsJwtAuth.avoid_email_errors = false
post :create, params: {confirmation: {email: 'not.found@email.com'}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns not found error' do
expect(json['errors']['email'].first['error']).to eq 'not_found'
end
end
context 'when send invalid email and avoid_email_errors is false' do
before do
RailsJwtAuth.avoid_email_errors = false
post :create, params: {confirmation: {email: 'invalid'}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns format error' do
expect(json['errors']['email'].first['error']).to eq 'format'
end
end
context 'when send not registered email and avoid_email_errors is true' do
before do
post :create, params: {confirmation: {email: 'not.found@email.com'}}
end
it 'returns 204 http status code' do
expect(response).to have_http_status(204)
end
end
context 'when send invalid email and avoid_email_errors is true' do
before do
post :create, params: {confirmation: {email: 'invalid'}}
end
it 'returns 204 http status code' do
expect(response).to have_http_status(422)
end
it 'returns format error' do
expect(json['errors']['email'].first['error']).to eq 'format'
end
end
context 'when email is already confirmed' do
before do
user.confirm
post :create, params: {confirmation: {email: user.email}}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns expiration confirmation error message' do
expect(json['errors']['email'].first['error']).to eq 'already_confirmed'
end
end
end
describe 'PUT #update' do
context 'when sends valid confirmation token' do
before do
put :update, params: {id: user.confirmation_token}
end
it 'returns 204 http status code' do
expect(response).to have_http_status(204)
end
it 'confirms user' do
expect(user.reload.confirmed?).to be_truthy
end
end
context 'when sends invalid confirmation token' do
before do
put :update, params: {id: 'invalid'}
end
it 'returns 404 http status code' do
expect(response).to have_http_status(404)
end
end
context 'when sends expired confirmation token' do
before do
user.update(confirmation_sent_at: Time.current - 1.month)
put :update, params: {id: user.confirmation_token}
end
it 'returns 422 http status code' do
expect(response).to have_http_status(422)
end
it 'returns expiration confirmation error message' do
expect(json['errors']['confirmation_token'].first['error']).to eq 'expired'
end
it 'does not confirm user' do
expect(user.reload.confirmed?).to be_falsey
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/unlock_accounts_controller_spec.rb | spec/controllers/unlock_accounts_controller_spec.rb | require 'rails_helper'
describe RailsJwtAuth::UnlockAccountsController do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:user) {
FactoryBot.create(
"#{orm.underscore}_user",
locked_at: 2.minutes.ago,
failed_attempts: 3,
first_failed_attempt_at: 3.minutes.ago,
unlock_token: SecureRandom.base58(24)
)
}
describe 'PUT #update' do
context 'when send a valid unlock_token' do
before do
put :update, params: {id: user.unlock_token}
end
it 'returns 204 http status code' do
expect(response).to have_http_status 204
end
it 'unlocks access' do
user.reload
expect(user.locked_at).to be_nil
expect(user.failed_attempts).to eq 0
expect(user.first_failed_attempt_at).to be_nil
expect(user.unlock_token).to be_nil
end
end
context 'when unlock_token is invalid' do
before do
put :update, params: {id: 'invalid'}
end
it 'returns 404 http status code' do
expect(response).to have_http_status 404
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/profiles_controller_spec.rb | spec/controllers/profiles_controller_spec.rb | require 'rails_helper'
include RailsJwtAuth::SpecHelpers
RSpec.describe RailsJwtAuth::ProfilesController do
%w[ActiveRecord Mongoid].each do |orm|
context "Using #{orm}" do
before(:all) { initialize_orm(orm) }
let(:password) { '12345678' }
let(:new_password) { 'new12345678' }
let(:json) { JSON.parse(response.body).first[1] }
let(:errors) { JSON.parse(response.body)['errors'] }
let(:user) { FactoryBot.create("#{orm.underscore}_user", password: password) }
describe 'GET #show' do
context 'when user is logged' do
before do
sign_in user
end
it 'returns user info' do
get :show
expect(response).to have_http_status(200)
expect(json['email']).to eq user.email
end
end
context 'when user is not logged' do
it 'raises RailsJwtAuth::NotAuthorized exception' do
expect { get :show }.to raise_error RailsJwtAuth::NotAuthorized
end
end
end
describe 'PUT #update' do
context 'when user is logged' do
before do
sign_in user
end
it 'allows update normal fields' do
allow(controller).to receive(:profile_update_params).and_return(username: 'blue')
put :update, params: {profile: {username: 'blue'}}
expect(response).to have_http_status(204)
expect(user.reload.username).to eq('blue')
end
it 'ignore email and password fields' do
put :update, params: {profile: {
email: 'new@email.com',
current_password: password,
password: new_password,
password_confirmation: new_password
}}
expect(response).to have_http_status(204)
expect(user.reload.unconfirmed_email).to be_nil
expect(user.authenticate(password)).not_to be_falsey
end
end
context 'when user is not logged' do
it 'raises RailsJwtAuth::NotAuthorized exception' do
expect { put :update, params: {} }.to raise_error RailsJwtAuth::NotAuthorized
end
end
end
describe 'PUT #password' do
before do
allow_any_instance_of(RailsJwtAuth::AuthenticableHelper)
.to receive(:jwt_payload).and_return('auth_token' => 'xxx')
end
context 'when user is logged' do
before do
sign_in user
end
it 'allows update password' do
put :password, params: {profile: {current_password: password, password: new_password}}
expect(response).to have_http_status(204)
end
it 'validates current password presence' do
put :password, params: {profile: {password: new_password}}
expect(response).to have_http_status(422)
expect(errors['current_password'].first['error']).to eq 'blank'
end
it 'validates current password match' do
put :password, params: {profile: {current_password: 'invalid', password: new_password}}
expect(response).to have_http_status(422)
expect(errors['current_password'].first['error']).to eq 'invalid'
end
it 'validates password confirmation' do
put :password, params: {profile: {
current_password: 'invalid',
password: new_password,
password_confirmation: 'invalid'
}}
expect(response).to have_http_status(422)
expect(errors['password_confirmation'].first['error']).to eq 'confirmation'
end
it 'close other sessions' do
put :password, params: {profile: {current_password: password, password: new_password}}
expect(user.reload.auth_tokens).to eq(['xxx'])
end
end
context 'when user is not logged' do
it 'raises RailsJwtAuth::NotAuthorized exception' do
expect { put :password, params: {} }.to raise_error RailsJwtAuth::NotAuthorized
end
end
end
describe 'PUT #email' do
context 'when user is logged' do
before do
sign_in user
end
it 'allows update email' do
put :email, params: {profile: {password: password, email: 'new@email.com'}}
expect(response).to have_http_status(204)
expect(user.reload.unconfirmed_email).to eq('new@email.com')
end
end
context 'when user is not logged' do
it 'raises RailsJwtAuth::NotAuthorized exception' do
expect { put :email, params: {} }.to raise_error RailsJwtAuth::NotAuthorized
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/controllers/concerns/authenticable_helper_spec.rb | spec/controllers/concerns/authenticable_helper_spec.rb | require 'rails_helper'
require 'rails_jwt_auth/jwt_manager'
describe RailsJwtAuth::AuthenticableHelper, type: :helper do
describe '#current_user' do
it 'returns current user' do
@current_user = {name: 'name'}
expect(helper.current_user).to eq(@current_user)
end
end
describe '#jwt_payload' do
it 'returns current jwt payload info' do
@jwt_payload = {name: 'name'}
expect(helper.jwt_payload).to eq(@jwt_payload)
end
end
describe '#authenticate!' do
before :all do
RailsJwtAuth.model_name = ActiveRecordUser.to_s
RailsJwtAuth.simultaneous_sessions = 1
end
let(:user) { FactoryBot.create(:active_record_user) }
context 'when jwt is valid' do
before do
token = user.regenerate_auth_token
jwt = RailsJwtAuth::JwtManager.encode(auth_token: token)
@payload = RailsJwtAuth::JwtManager.decode(jwt)[0]
helper.request.env['HTTP_AUTHORIZATION'] = "Bearer #{jwt}"
freeze_time
helper.authenticate!
end
it 'success!' do
expect(helper.current_user).to eq(user)
expect(helper.jwt_payload).to eq(@payload)
end
it 'track request' do
user.reload
expect(user.last_request_at).to eq(Time.current)
expect(user.last_request_ip).to eq(helper.request.ip)
end
end
context 'when jwt is invalid' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::DecodeError)
expect { helper.authenticate! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
context 'when jwt is expired' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::ExpiredSignature)
expect { helper.authenticate! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
context 'when jwt verification fail' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::VerificationError)
expect { helper.authenticate! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
context 'when session_token is invalid' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_return([{auth_token: 'invalid'}])
expect { helper.authenticate! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
context 'when user is not found' do
it 'fail!' do
token = user.regenerate_auth_token
jwt = RailsJwtAuth::JwtManager.encode(auth_token: token)
helper.request.env['HTTP_AUTHORIZATION'] = "Bearer #{jwt}"
user.delete
expect { helper.authenticate! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
end
describe '#authenticate' do
before :all do
RailsJwtAuth.model_name = ActiveRecordUser.to_s
RailsJwtAuth.simultaneous_sessions = 1
end
let(:user) { FactoryBot.create(:active_record_user) }
context 'when jwt is valid' do
before do
token = user.regenerate_auth_token
jwt = RailsJwtAuth::JwtManager.encode(auth_token: token)
@payload = RailsJwtAuth::JwtManager.decode(jwt)[0]
helper.request.env['HTTP_AUTHORIZATION'] = "Bearer #{jwt}"
freeze_time
helper.authenticate
end
it 'success!' do
expect(helper.current_user).to eq(user)
expect(helper.jwt_payload).to eq(@payload)
end
it 'track request' do
user.reload
expect(user.last_request_at).to eq(Time.current)
expect(user.last_request_ip).to eq(helper.request.ip)
end
end
context 'when jwt is invalid' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::DecodeError)
expect { helper.authenticate }.not_to raise_error
expect(helper.current_user).to eq(nil)
end
end
context 'when jwt is expired' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::ExpiredSignature)
expect { helper.authenticate }.not_to raise_error
expect(helper.current_user).to eq(nil)
end
end
context 'when jwt verification fail' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_raise(JWT::VerificationError)
expect { helper.authenticate }.not_to raise_error
expect(helper.current_user).to eq(nil)
end
end
context 'when session_token is invalid' do
it 'fail!' do
allow(RailsJwtAuth::JwtManager).to receive(:decode).and_return([{auth_token: 'invalid'}])
expect { helper.authenticate }.not_to raise_error
expect(helper.current_user).to eq(nil)
end
end
context 'when user is not found' do
it 'fail!' do
token = user.regenerate_auth_token
jwt = RailsJwtAuth::JwtManager.encode(auth_token: token)
helper.request.env['HTTP_AUTHORIZATION'] = "Bearer #{jwt}"
user.delete
expect { helper.authenticate }.not_to raise_error
expect(helper.current_user).to eq(nil)
end
end
end
describe '#unauthorize!' do
it 'throws NotAuthorized exception' do
expect { helper.unauthorize! }.to raise_error(RailsJwtAuth::NotAuthorized)
end
end
describe '#signed_in?' do
it 'returns if there is current user' do
expect(helper.signed_in?).to be_falsey
@current_user = Object.new
expect(helper.signed_in?).to be_truthy
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/confirmable_spec.rb | spec/models/concerns/confirmable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Confirmable do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:password) { '12345678' }
let(:user) { FactoryBot.create("#{orm.underscore}_user", password: password) }
let(:unconfirmed_user) { FactoryBot.create("#{orm.underscore}_unconfirmed_user") }
describe '#attributes' do
it { expect(user).to have_attributes(confirmation_token: user.confirmation_token) }
it { expect(user).to have_attributes(confirmation_sent_at: user.confirmation_sent_at) }
it { expect(user).to have_attributes(confirmed_at: user.confirmed_at) }
end
describe '#confirmed?' do
it 'returns if user is confirmed' do
expect(user.confirmed?).to be_truthy
expect(unconfirmed_user.confirmed?).to be_falsey
end
end
describe '#confirm' do
it 'confirms user' do
unconfirmed_user.confirm
expect(unconfirmed_user.confirmed?).to be_truthy
end
context 'when unconfirmed_email exists' do
it 'confirms new email' do
user.update_email(email: 'new@email.com', password: password)
user.confirm
expect(user.reload.email).to eq('new@email.com')
expect(user.confirmed?).to be_truthy
end
end
context 'when new_email confirmation token has expired' do
it 'adds expiration error' do
user.update_email(email: 'new@email.com', password: password)
travel_to(Time.current + RailsJwtAuth.confirmation_expiration_time + 1.second) do
expect(user.confirm).to be_falsey
expect(get_record_error(user, :confirmation_token)).to eq :expired
end
end
end
context 'when user has email confirmation field' do
it 'fill in with email' do
user.update_email(email: 'new@email.com', password: password)
user.confirm
expect(user.email_confirmation).to eq(user.email)
end
end
end
describe '#skip_confirmation' do
it 'skips user confirmation after create' do
new_user = FactoryBot.build("#{orm.underscore}_user")
new_user.skip_confirmation
new_user.save
expect(new_user.confirmed?).to be_truthy
end
end
describe '#send_confirmation_instructions' do
it 'fills confirmation fields' do
unconfirmed_user.send_confirmation_instructions
expect(unconfirmed_user.confirmation_token).not_to be_nil
expect(unconfirmed_user.confirmation_sent_at).not_to be_nil
end
it 'avoid to repeat token' do
other_user = FactoryBot.create("#{orm.underscore}_user")
other_user.update(confirmation_token: 'xxx')
allow(RailsJwtAuth).to receive(:friendly_token).and_return('xxx', 'yyy')
expect(unconfirmed_user.confirmation_token).to eq('yyy')
end
it 'sends confirmation email' do
new_user = FactoryBot.build("#{orm.underscore}_unconfirmed_user")
expect(RailsJwtAuth).to receive(:send_email).with(:confirmation_instructions, new_user)
new_user.send_confirmation_instructions
end
context 'when user is confirmed' do
it 'returns false' do
expect(user.send_confirmation_instructions).to eq(false)
end
it 'addds error to user' do
user.send_confirmation_instructions
expect(get_record_error(user, :email)).to eq :already_confirmed
end
it 'does not send confirmation email' do
expect(RailsJwtAuth).not_to receive(:send_email).with(:confirmation_instructions, user)
user.send_confirmation_instructions
end
context 'when user has unconfirmed_email' do
it 'return true' do
user.update_email(email: 'new@email.com', password: password)
expect(user.unconfirmed_email).to eq('new@email.com')
expect(user.send_confirmation_instructions).to eq(true)
end
end
end
end
describe '#update_email' do
it 'fills in unconfirmed_email and token fields' do
old_email = user.email
expect(user.update_email(email: 'new@email.com', password: password)).to be_truthy
expect(user.reload.unconfirmed_email).to eq('new@email.com')
expect(user.email).to eq(old_email)
expect(user.confirmation_token).not_to be_nil
expect(user.confirmation_sent_at).not_to be_nil
end
it 'avoid to repeat token' do
allow(RailsJwtAuth).to receive(:friendly_token).and_return('xxx', 'yyy')
expect(unconfirmed_user.confirmation_token).to eq('xxx')
expect(user.update_email(email: 'new@email.com', password: password)).to be_truthy
expect(user.reload.unconfirmed_email).to eq('new@email.com')
expect(user.confirmation_token).to eq('yyy')
end
it 'checks email' do
expect(user.update_email(email: '')).to be_falsey
expect(get_record_error(user, :email)).to eq(:blank)
expect(user.update_email(email: 'invalid')).to be_falsey
expect(get_record_error(user, :email)).to eq(:invalid)
end
it 'checks password' do
expect(user.update_email(email: 'new@email.com')).to be_falsey
expect(get_record_error(user, :password)).to eq(:blank)
expect(user.update_email(email: 'new@email.com', password: :invalid)).to be_falsey
expect(get_record_error(user, :password)).to eq(:invalid)
end
it 'checks that email has changed' do
expect(user.update_email(email: user.email)).to be_falsey
expect(get_record_error(user, :email)).to eq(:not_change)
end
context 'when send_email_change_requested_notification option is false' do
it 'sends only confirmation email' do
allow(RailsJwtAuth).to receive(:send_email_change_requested_notification).and_return(false)
expect(RailsJwtAuth).to receive(:send_email).with(:confirmation_instructions, user)
expect(RailsJwtAuth).not_to receive(:send_email).with(:email_change_requested_notification, user)
user.update_email(email: 'new@email.com', password: password)
end
end
context 'when send_email_change_requested_notification option is true' do
it 'sends confirmation and nofication email' do
allow(RailsJwtAuth).to receive(:send_email_change_requested_notification).and_return(true)
expect(RailsJwtAuth).to receive(:send_email).with(:confirmation_instructions, user)
expect(RailsJwtAuth).to receive(:send_email).with(:email_change_requested_notification, user)
user.update_email(email: 'new@email.com', password: password)
end
end
end
describe '#after_create' do
it 'sends confirmation instructions' do
new_user = FactoryBot.build("#{orm.underscore}_user")
expect(new_user).to receive(:send_confirmation_instructions)
new_user.save
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/lockable_spec.rb | spec/models/concerns/lockable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Lockable do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:each) { initialize_orm(orm) }
let(:user) { FactoryBot.create("#{orm.underscore}_user") }
let(:locked_user) {
FactoryBot.create(
"#{orm.underscore}_user",
locked_at: 2.minutes.ago,
failed_attempts: 3,
first_failed_attempt_at: 3.minutes.ago,
unlock_token: SecureRandom.base58(24)
)
}
describe '#attributes' do
it { expect(user).to have_attributes(failed_attempts: nil) }
it { expect(user).to have_attributes(unlock_token: nil) }
it { expect(user).to have_attributes(first_failed_attempt_at: nil) }
it { expect(user).to have_attributes(locked_at: nil) }
end
describe '#lock_access' do
context 'when unlock strategy is by time' do
before do
RailsJwtAuth.unlock_strategy = :time
end
it 'locks the user' do
user.lock_access
expect(user.locked_at).not_to be_nil
end
it 'avoid to repeat token' do
other_user = FactoryBot.create("#{orm.underscore}_user")
other_user.update(unlock_token: 'xxx')
allow(RailsJwtAuth).to receive(:friendly_token).and_return('xxx', 'yyy')
allow(user).to receive(:unlock_strategy_enabled?).and_return(true)
user.lock_access
expect(user.unlock_token).to eq('yyy')
end
end
%i[email both].each do |unlock_strategy|
context "when unlock strategy is #{unlock_strategy}" do
before do
RailsJwtAuth.unlock_strategy = unlock_strategy
end
it 'locks the user' do
user.lock_access
expect(user.locked_at).not_to be_nil
end
it 'sends unlock instructions' do
expect(RailsJwtAuth).to receive(:send_email).with(:unlock_instructions, user)
user.lock_access
end
end
end
end
describe '#access_locked?' do
it 'returns if user is locked' do
expect(user.access_locked?).to be_falsey
user.lock_access
expect(user.access_locked?).to be_truthy
end
end
describe '#unlock_access' do
it 'unlocks the user and reset attempts' do
expect(locked_user.failed_attempts).to be > 0
expect(locked_user.access_locked?).to be_truthy
locked_user.unlock_access
expect(locked_user.locked_at).to be_nil
expect(locked_user.failed_attempts).to eq 0
expect(locked_user.first_failed_attempt_at).to be_nil
expect(locked_user.unlock_token).to be_nil
end
end
describe '#failed_attempt' do
context 'when is first time' do
it 'increase failed attempts and set first_failed_attempt_at' do
travel_to Time.now do
user.failed_attempt
expect(user.failed_attempts).to eq 1
expect(user.first_failed_attempt_at).to eq(Time.current)
expect(user.access_locked?).to be_falsey
end
end
end
context 'when is penultimate opportunity' do
it 'increase failed attempts' do
user.first_failed_attempt_at = Time.current
user.failed_attempts = RailsJwtAuth.maximum_attempts - 2
first_failed_attempt_at = user.first_failed_attempt_at
travel_to Time.current + 5.seconds do
user.failed_attempt
expect(user.failed_attempts).to eq RailsJwtAuth.maximum_attempts - 1
expect(user.first_failed_attempt_at).to eq(first_failed_attempt_at)
expect(user.access_locked?).to be_falsey
end
end
end
context 'when is last oportunity' do
it 'increase failed attempts and lock account' do
user.first_failed_attempt_at = Time.current
user.failed_attempts = RailsJwtAuth.maximum_attempts - 1
travel_to Time.current + 5.seconds do
user.failed_attempt
expect(user.failed_attempts).to eq RailsJwtAuth.maximum_attempts
expect(user.access_locked?).to be_truthy
end
end
end
context 'when attempts are expired' do
it 'reset attempts' do
travel_to Time.current - RailsJwtAuth.unlock_in - 5.seconds do
user.failed_attempt
end
expect(user.failed_attempts).to eq 1
user.failed_attempt
expect(user.failed_attempts).to eq 1
end
end
context 'whe user is locked' do
it 'does nothing' do
user.lock_access
user.failed_attempt
expect(user.failed_attempts).to eq nil
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/trackable_spec.rb | spec/models/concerns/trackable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Trackable do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:user) do
FactoryBot.create(
"#{orm.underscore}_user",
last_sign_in_at: Time.current,
last_sign_in_ip: '127.0.0.1'
)
end
describe '#attributes' do
it { expect(user).to have_attributes(last_sign_in_at: user.last_sign_in_at) }
it { expect(user).to have_attributes(last_sign_in_ip: user.last_sign_in_ip) }
end
describe '#track_session_info' do
it 'fill in tracked fields' do
user = FactoryBot.create(:active_record_user)
request = OpenStruct.new(ip: '127.0.0.1')
user.track_session_info(request)
expect(user.last_sign_in_at).not_to eq(Time.current)
expect(user.last_sign_in_ip).to eq('127.0.0.1')
expect(user.changed?).to be_truthy
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/authenticatable_spec.rb | spec/models/concerns/authenticatable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Authenticatable do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:user) { FactoryBot.create("#{orm.underscore}_user", auth_tokens: %w[abcd]) }
describe '#attributes' do
it { expect(user).to have_attributes(password: user.password) }
it { expect(user).to have_attributes(auth_tokens: user.auth_tokens) }
end
describe '#before_validation' do
it 'downcase auth field when downcase_auth_field options is actived' do
user = FactoryBot.create("#{orm.underscore}_user", email: 'AAA@email.com')
expect(user.reload.email).to eq('AAA@email.com')
allow(RailsJwtAuth).to receive(:downcase_auth_field).and_return(true)
user = FactoryBot.create("#{orm.underscore}_user", email: 'BBB@email.com')
expect(user.reload.email).to eq('bbb@email.com')
end
it 'does not fail when auth field is blank and apply downcase!' do
allow(RailsJwtAuth).to receive(:downcase_auth_field).and_return(true)
user = FactoryBot.create("#{orm.underscore}_user", email: 'BBB@email.com')
user.email = nil
expect { user.valid? }.not_to raise_exception
end
end
describe '#authenticate' do
it 'authenticates user valid password' do
user = FactoryBot.create("#{orm.underscore}_user", password: '12345678')
expect(user.authenticate('12345678')).not_to eq(false)
expect(user.authenticate('invalid')).to eq(false)
end
end
describe '#update_password' do
let(:current_password) { '12345678' }
let(:user) { FactoryBot.create("#{orm.underscore}_user", password: current_password) }
let(:new_password) { 'new_password' }
let(:new_password_params) { {current_password: current_password, password: new_password} }
context 'when curren_password is blank' do
it 'returns false' do
expect(user.update_password(password: 'new_password')).to be_falsey
end
it 'addd blank error message' do
user.update_password(password: 'new_password')
expect(user.errors.messages[:current_password].first).to eq 'blank'
end
it 'validates other fields' do
user.update_password(password: 'new_password', email: '')
expect(user.errors.messages[:email].first).not_to be 'nil'
end
it "don't updates password" do
user.update_password(password: 'new_password')
expect(user.reload.authenticate('new_password')).to be_falsey
end
end
context 'when curren_password is invalid' do
it 'returns false' do
expect(user.update_password(current_password: 'invalid')).to be_falsey
end
it 'addd blank error message' do
user.update_password(current_password: 'invalid')
expect(user.errors.messages[:current_password].first).to eq 'invalid'
end
it "don't updates password" do
user.update_password(current_password: 'invalid')
expect(user.authenticate('new_password')).to be_falsey
end
end
context 'when curren_password is valid' do
it 'returns true' do
expect(
user.update_password(current_password: '12345678', password: 'new_password')
).to be_truthy
end
it 'updates password' do
user.update_password(current_password: '12345678', password: 'new_password')
expect(user.authenticate('new_password')).to be_truthy
end
it 'clean sessions' do
user.update_password(current_password: '12345678', password: 'new_password')
expect(user.auth_tokens).to be_empty
user.update_password(
current_password: '12345678',
password: 'new_password',
current_auth_token: 'xxx'
)
expect(user.auth_tokens).to eq(['xxx'])
end
end
context 'when password is blank' do
it 'addd blank error message' do
user.update_password(password: '')
expect(user.errors.messages[:password].first).to eq 'blank'
end
end
context 'when send_password_changed_notification option is false' do
it 'does not send notify email' do
allow(RailsJwtAuth).to receive(:send_password_changed_notification).and_return(false)
expect(RailsJwtAuth).not_to receive(:send_email)
.with(:password_changed_notification, user)
user.update_password(new_password_params)
end
end
context 'when send_password_changed_notification option is true' do
it 'sends confirmation and nofication email' do
expect(RailsJwtAuth).to receive(:send_email).with(:password_changed_notification, user)
user.update_password(new_password_params)
end
end
context 'when RailsJwtAuth::Authenticable is used with RailsJwtAuth::Recoverable' do
context 'when reset_password_sent_at is expired' do
before do
@user = FactoryBot.create("#{orm.underscore}_user",
password: current_password,
reset_password_token: 'xxx',
reset_password_sent_at: Time.current)
travel(RailsJwtAuth.reset_password_expiration_time)
end
after do
travel_back
end
it 'reset recoverable fields' do
@user.update_password(new_password_params)
@user.reload
expect(@user.reset_password_sent_at).to be_nil
expect(@user.reset_password_token).to be_nil
end
it 'updates password' do
expect(@user.update_password(new_password_params)).to be_truthy
expect(@user.reload.authenticate(new_password)).to be_truthy
end
end
context 'when reset_password_sent_at is valid' do
before do
@user = FactoryBot.create("#{orm.underscore}_user",
password: current_password,
reset_password_token: 'xxxx',
reset_password_sent_at: Time.current)
end
it 'reset recoverable fields' do
@user.update_password(new_password_params)
@user.reload
expect(@user.reset_password_sent_at).to be_nil
expect(@user.reset_password_token).to be_nil
end
it 'updates password' do
expect(@user.update_password(new_password_params)).to be_truthy
expect(@user.reload.authenticate(new_password)).to be_truthy
end
end
end
end
describe '#regenerate_auth_token' do
context 'when simultaneous_sessions = 1' do
before do
RailsJwtAuth.simultaneous_sessions = 1
end
it 'creates new authentication token' do
old_token = user.auth_tokens.first
user.regenerate_auth_token
expect(user.auth_tokens.length).to eq(1)
expect(user.auth_tokens.first).not_to eq(old_token)
end
end
context 'when simultaneous_sessions = 2' do
before do
RailsJwtAuth.simultaneous_sessions = 2
end
context 'when don\'t pass token' do
it 'creates new authentication token' do
old_token = user.auth_tokens.first
user.regenerate_auth_token
expect(user.auth_tokens.length).to eq(2)
expect(user.auth_tokens.first).to eq(old_token)
new_old_token = user.auth_tokens.last
user.regenerate_auth_token
expect(user.auth_tokens.length).to eq(2)
expect(user.auth_tokens).not_to include(old_token)
expect(user.auth_tokens.first).to eq(new_old_token)
end
end
context 'when pass token' do
it 'regeneates this token' do
old_token = user.auth_tokens.first
user.regenerate_auth_token old_token
expect(user.auth_tokens.length).to eq(1)
expect(user.auth_tokens.first).not_to eq(old_token)
end
end
end
end
describe '#destroy_auth_token' do
before do
RailsJwtAuth.simultaneous_sessions = 2
end
it 'destroy specified token from user auth tokens array' do
user.regenerate_auth_token
expect(user.auth_tokens.length).to eq(2)
token = user.auth_tokens.first
user.destroy_auth_token token
expect(user.auth_tokens.length).to eq(1)
expect(user.auth_tokens.first).not_to eq(token)
end
end
describe '#to_token_payload' do
context 'when auth_tokens is empty' do
it 'returns false' do
user_without_tokens = FactoryBot.create("#{orm.underscore}_user")
expect(user_without_tokens.to_token_payload).to be_falsey
end
end
context 'when use simultaneous sessions' do
it 'returns payload with auth_token' do
payload = user.to_token_payload
expect(payload[:auth_token]).to eq(user.auth_tokens.first)
end
end
context 'when simultaneous sessions are 0' do
it 'returns payload with user id' do
allow(RailsJwtAuth).to receive(:simultaneous_sessions).and_return(0)
payload = user.to_token_payload
expect(payload[:auth_token]).to be_nil
expect(payload[:id]).to eq(user.id.to_s)
end
end
end
describe '#save_without_password' do
it 'avoid password validation' do
u = FactoryBot.build("#{orm.underscore}_user_without_password")
expect(u.save).to be_falsey
expect(u.save_without_password).to be_truthy
end
it 'remove password and password_confirmation before save' do
u = FactoryBot.build(
"#{orm.underscore}_user",
password: 'invalid',
password_confirmation: 'invalid_confirmation'
)
expect(u.save_without_password).to be_truthy
expect(u.password).to be_nil
expect(u.password_confirmation).to be_nil
expect(u.reload.password_digest).to be_nil
end
end
describe '#valid_without_password?' do
it 'avoid validates password' do
u = FactoryBot.build("#{orm.underscore}_user_without_password")
expect(u.valid?).to be_falsey
expect(u.valid_without_password?).to be_truthy
end
end
describe '.from_token_payload' do
context 'when use simultaneous sessions' do
it 'returns user by auth token' do
user.regenerate_auth_token
expect(
RailsJwtAuth.model.from_token_payload({'auth_token' => user.auth_tokens.last})
).to eq(user)
end
end
context 'when simultaneous sessions are 0' do
it 'returns user by id' do
allow(RailsJwtAuth).to receive(:simultaneous_sessions).and_return(0)
expect(RailsJwtAuth.model.from_token_payload({'id' => user.id.to_s})).to eq(user)
end
end
end
describe '.get_by_token' do
it 'returns user with specified token' do
user = FactoryBot.create("#{orm.underscore}_user", auth_tokens: %w[abcd efgh])
expect(user.class.get_by_token('aaaa')).to eq(nil)
expect(user.class.get_by_token('abcd')).to eq(user)
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/recoverable_spec.rb | spec/models/concerns/recoverable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Recoverable do
%w(ActiveRecord Mongoid).each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:user) { FactoryBot.create("#{orm.underscore}_user") }
describe '#attributes' do
it { expect(user).to respond_to(:reset_password_token) }
it { expect(user).to respond_to(:reset_password_sent_at) }
end
describe '#send_reset_password_instructions' do
it 'fills reset password fields' do
user.send_reset_password_instructions
user.reload
expect(user.reset_password_token).not_to be_nil
expect(user.reset_password_sent_at).not_to be_nil
end
it 'avoid to repeat token' do
other_user = FactoryBot.create("#{orm.underscore}_user")
other_user.update(reset_password_token: 'xxx')
allow(RailsJwtAuth).to receive(:friendly_token).and_return('xxx', 'yyy')
user.send_reset_password_instructions
user.reload
expect(user.reset_password_token).to eq('yyy')
end
it 'sends reset password email' do
expect(RailsJwtAuth).to receive(:send_email).with(:reset_password_instructions, user)
user.send_reset_password_instructions
end
context 'when user is unconfirmed' do
let(:user) { FactoryBot.create("#{orm.underscore}_unconfirmed_user") }
it 'returns false' do
expect(user.send_reset_password_instructions).to be_falsey
end
it 'does not fill reset password fields' do
user.send_reset_password_instructions
user.reload
expect(user.reset_password_token).to be_nil
expect(user.reset_password_sent_at).to be_nil
end
it 'doe not send reset password email' do
expect(RailsJwtAuth).not_to receive(:send_email)
.with(:reset_password_instructions, user)
user.send_reset_password_instructions
end
end
context 'when user is locked' do
let(:user) { FactoryBot.create("#{orm.underscore}_user", locked_at: 2.minutes.ago) }
it 'returns false' do
expect(user.send_reset_password_instructions).to be_falsey
end
it 'does not fill reset password fields' do
user.send_reset_password_instructions
user.reload
expect(user.reset_password_token).to be_nil
expect(user.reset_password_sent_at).to be_nil
end
it 'doe not send reset password email' do
expect(RailsJwtAuth).not_to receive(:send_email)
.with(:reset_password_instructions, user)
user.send_reset_password_instructions
end
end
end
describe '#set_reset_password' do
it 'validates password presence' do
expect(user.set_reset_password({})).to be_falsey
expect(get_record_error(user, :password)).to eq(:blank)
end
it 'validates reset_password_token' do
allow(user).to receive(:expired_reset_password_token?).and_return(true)
expect(user.set_reset_password({})).to be_falsey
expect(get_record_error(user, :reset_password_token)).to eq(:expired)
end
it 'cleans reset password token and sessions' do
user.reset_password_token = 'abcd'
user.reset_password_sent_at = Time.current
user.auth_tokens = ['test']
user.save
user.set_reset_password(password: 'newpassword')
user.reload
expect(user.reset_password_token).to be_nil
expect(user.auth_tokens).to be_empty
end
end
describe '#expired_reset_password_token?' do
context 'when reset password token has expired' do
it 'returns true' do
user.reset_password_token = 'abcd'
user.reset_password_sent_at = Time.current
user.save
travel_to(Time.current + RailsJwtAuth.reset_password_expiration_time + 1.second) do
expect(user.expired_reset_password_token?).to be_truthy
end
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/models/concerns/invitable_spec.rb | spec/models/concerns/invitable_spec.rb | require 'rails_helper'
describe RailsJwtAuth::Invitable do
%w[ActiveRecord Mongoid].each do |orm|
context "Using #{orm}" do
before(:all) { initialize_orm(orm) }
before(:each) { ActionMailer::Base.deliveries.clear }
let(:pass) { 'new_password' }
let(:email) { 'valid@email.com' }
let(:username) { 'TestName' }
let(:invited_user) { RailsJwtAuth.model.invite email: email, username: username }
let(:user) { FactoryBot.create "#{orm.underscore}_user", email: email }
describe '#attributes' do
it { expect(user).to respond_to(:invitation_token) }
it { expect(user).to respond_to(:invitation_sent_at) }
it { expect(user).to respond_to(:invitation_accepted_at) }
end
describe '.invite' do # Class method
context 'when auth field is blank' do
it 'returns record with auth field error' do
user = RailsJwtAuth.model.invite
expect(get_record_error(user, :email)).to eq(:blank)
end
end
context 'when is new valid user' do
it 'creates a record' do
expect { invited_user }.to change { RailsJwtAuth.model.count }.by 1
end
it 'sends the invitation mail' do
expect(RailsJwtAuth).to receive(:send_email).with(:invitation_instructions, anything)
invited_user
end
it 'assign attributes' do
expect(invited_user.username).to eq('TestName')
end
it 'returns new record' do
expect(invited_user.class).to eq(RailsJwtAuth.model)
end
end
context 'when user already exists' do
context 'with pending invitation' do
it 'resets invitation' do
first_invitation_date = Time.current
second_invitation_date = nil
travel_to(first_invitation_date) do
invited_user
end
travel_to(Time.current + 30.days) do
RailsJwtAuth.model.invite email: invited_user.email
second_invitation_date = Time.current.to_i
end
expect(first_invitation_date).not_to eq(second_invitation_date)
expect(invited_user.reload.invitation_sent_at.to_i).to eq(second_invitation_date)
end
it 'sends new invitation mail' do
invited_user
expect(ActionMailer::Base.deliveries.count).to eq(1)
end
end
context 'with register completed' do
before { user }
it 'returns record with registered error' do
expect(RailsJwtAuth.model.find_by(email: user.email)).not_to be_nil
expect(get_record_error(invited_user, :email)).to eq(:registered)
end
end
end
end
describe '#invite' do
context 'when user is new' do
before do
@user = FactoryBot.build("#{orm.underscore}_user_without_password")
@user.invite
end
it 'fill in invitation fields' do
expect(@user.invitation_token).to_not be_nil
expect(@user.invitation_sent_at).to_not be_nil
expect(@user.invitation_accepted_at).to be_nil
end
it 'avoid to repeat token' do
other_user = FactoryBot.create("#{orm.underscore}_user")
other_user.update(invitation_token: 'xxx')
allow(RailsJwtAuth).to receive(:friendly_token).and_return('xxx', 'yyy')
expect(invited_user.invitation_token).to eq('yyy')
end
it 'sends new invitation mail' do
expect(ActionMailer::Base.deliveries.count).to eq(1)
end
end
context 'when user has pending invitation' do
it 'resets invitation' do
first_invitation_date = Time.current
second_invitation_date = nil
travel_to(first_invitation_date) do
invited_user
end
travel_to(Time.current + 30.days) do
invited_user.invite
second_invitation_date = Time.current.to_i
end
expect(first_invitation_date).not_to eq(second_invitation_date)
expect(invited_user.reload.invitation_sent_at.to_i).to eq(second_invitation_date)
end
it 'sends new invitation mail' do
invited_user
expect(ActionMailer::Base.deliveries.count).to eq(1)
invited_user.invite
expect(ActionMailer::Base.deliveries.count).to eq(2)
end
end
context 'when user register is completed' do
before { user }
it 'returns record with registered error' do
expect(RailsJwtAuth.model.find_by(email: user.email)).not_to be_nil
user.invite
expect(get_record_error(user, :email)).to eq(:registered)
end
end
end
describe '#accept_invitation' do
let(:accept_attrs) { {password: pass, password_confirmation: pass} }
context 'with invited user' do
it 'completes invitation' do
invited_user
expect(invited_user.invitation_token).not_to be_nil
expect(invited_user.invitation_sent_at).not_to be_nil
expect(invited_user.invitation_accepted_at).to be_nil
invited_user.accept_invitation(accept_attrs)
expect(invited_user.invitation_token).to be_nil
expect(invited_user.invitation_sent_at).to be_nil
expect(invited_user.invitation_accepted_at).not_to be_nil
expect(invited_user.confirmed_at).not_to be_nil
end
it 'validates password' do
invited_user.accept_invitation({})
expect(get_record_error(invited_user, :password)).to eq(:blank)
end
it 'validates token' do
invited_user.invitation_sent_at = Time.now - 1.year
invited_user.accept_invitation(accept_attrs)
expect(get_record_error(invited_user, :invitation_token)).to eq(:expired)
end
it 'does not send password changed email' do
invited_user
ActionMailer::Base.deliveries.clear
invited_user.accept_invitation(accept_attrs)
expect(ActionMailer::Base.deliveries.count).to eq(0)
end
end
context 'with non-invited user' do
it 'doesn\'t set invitation_accepted_at' do
expect(user.accept_invitation({})).to be_falsey
expect(user.reload.invitation_accepted_at).to be_nil
end
end
end
describe '#valid_for_invite?' do
it 'returns when record is valid for invite' do
u = FactoryBot.build("#{orm.underscore}_user_without_password")
expect(u.valid_for_invite?).to be_truthy
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/jobs/application_job.rb | spec/dummy/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/helpers/application_helper.rb | spec/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/controllers/application_controller.rb | spec/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/models/application_record.rb | spec/dummy/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/models/mongoid_user.rb | spec/dummy/app/models/mongoid_user.rb | class MongoidUser
include Mongoid::Document
include RailsJwtAuth::Authenticatable
include RailsJwtAuth::Confirmable
include RailsJwtAuth::Recoverable
include RailsJwtAuth::Trackable
include RailsJwtAuth::Invitable
include RailsJwtAuth::Lockable
attr_accessor :email_confirmation
field :username, type: String
field :email, type: String
validates :email, presence: true,
uniqueness: true,
format: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/models/active_record_user.rb | spec/dummy/app/models/active_record_user.rb | class ActiveRecordUser < ApplicationRecord
include RailsJwtAuth::Authenticatable
include RailsJwtAuth::Confirmable
include RailsJwtAuth::Recoverable
include RailsJwtAuth::Trackable
include RailsJwtAuth::Invitable
include RailsJwtAuth::Lockable
attr_accessor :email_confirmation
validates :email, presence: true,
uniqueness: true,
format: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/mailers/application_mailer.rb | spec/dummy/app/mailers/application_mailer.rb | class ApplicationMailer < ActionMailer::Base
default from: 'from@example.com'
layout 'mailer'
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/channels/application_cable/channel.rb | spec/dummy/app/channels/application_cable/channel.rb | module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/app/channels/application_cable/connection.rb | spec/dummy/app/channels/application_cable/connection.rb | module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/db/schema.rb | spec/dummy/db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define do
create_table 'active_record_users', force: :cascade do |t|
t.string 'username'
t.string 'email'
t.string 'password_digest'
t.string 'auth_tokens'
t.string 'unconfirmed_email'
t.string 'confirmation_token'
t.datetime 'confirmation_sent_at'
t.datetime 'confirmed_at'
t.string 'reset_password_token'
t.datetime 'reset_password_sent_at'
t.datetime 'last_sign_in_at'
t.string 'last_sign_in_ip'
t.datetime 'last_request_at'
t.string 'last_request_ip'
t.string 'invitation_token'
t.datetime 'invitation_sent_at'
t.datetime 'invitation_accepted_at'
t.integer 'failed_attempts'
t.string 'unlock_token'
t.datetime 'first_failed_attempt_at'
t.datetime 'locked_at'
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/application.rb | spec/dummy/config/application.rb | require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
# require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "rails_jwt_auth"
module Dummy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
config.api_only = true
config.action_mailer.delivery_job = 'ActionMailer::MailDeliveryJob'
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/environment.rb | spec/dummy/config/environment.rb | # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/puma.rb | spec/dummy/config/puma.rb | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/routes.rb | spec/dummy/config/routes.rb | Rails.application.routes.draw do
resource :session, controller: 'rails_jwt_auth/sessions', only: %i[create destroy]
resource :registration, controller: 'rails_jwt_auth/registrations', only: %i[create]
resource :profile, controller: 'rails_jwt_auth/profiles', only: %i[show update] do
collection do
put :email
put :password
end
end
resources :confirmations, controller: 'rails_jwt_auth/confirmations', only: [:create, :update]
resources :reset_passwords, controller: 'rails_jwt_auth/reset_passwords', only: [:show, :create, :update]
resources :invitations, controller: 'rails_jwt_auth/invitations', only: [:show, :create, :update]
resources :unlock_accounts, controller: 'rails_jwt_auth/unlock_accounts', only: %i[update]
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/spring.rb | spec/dummy/config/spring.rb | %w[
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
].each { |path| Spring.watch(path) }
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/boot.rb | spec/dummy/config/boot.rb | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/content_security_policy.rb | spec/dummy/config/initializers/content_security_policy.rb | # Be sure to restart your server when you modify this file.
# Define an application-wide content security policy
# For further information see the following documentation
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
# Rails.application.config.content_security_policy do |policy|
# policy.default_src :self, :https
# policy.font_src :self, :https, :data
# policy.img_src :self, :https, :data
# policy.object_src :none
# policy.script_src :self, :https
# policy.style_src :self, :https
# # Specify URI for violation reports
# # policy.report_uri "/csp-violation-report-endpoint"
# end
# If you are using UJS then enable automatic nonce generation
# Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Report CSP violations to a specified URI
# For further information see the following documentation:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
# Rails.application.config.content_security_policy_report_only = true
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/filter_parameter_logging.rb | spec/dummy/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/application_controller_renderer.rb | spec/dummy/config/initializers/application_controller_renderer.rb | # Be sure to restart your server when you modify this file.
# ActiveSupport::Reloader.to_prepare do
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/wrap_parameters.rb | spec/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/rails_jwt_auth.rb | spec/dummy/config/initializers/rails_jwt_auth.rb | RailsJwtAuth.setup do |config|
# authentication model class name
config.model_name = 'ActiveRecordUser'
# field name used to authentication with password
#config.auth_field_name = 'email'
# define email field name used to send emails
#config.email_field_name = 'email'
# expiration time for generated tokens
#config.jwt_expiration_time = 7.days
# the "iss" (issuer) claim identifies the principal that issued the JWT
#config.jwt_issuer = 'RailsJwtAuth'
# number of simultaneously sessions for an user
#config.simultaneous_sessions = 2
# mailer sender
#config.mailer_sender = 'initialize-mailer_sender@example.com'
# url used to create email link with confirmation token
#config.confirm_email_url = 'http://frontend.com/confirmation'
# expiration time for confirmation tokens
#config.confirmation_expiration_time = 1.day
# url used to create email link with reset password token
#config.reset_password_url = 'http://frontend.com/reset_password'
# expiration time for reset password tokens
#config.reset_password_expiration_time = 1.day
# uses deliver_later to send emails instead of deliver method
#config.deliver_later = false
# time an invitation is valid after sent
# config.invitation_expiration_time = 2.days
# url used to create email link with activation token parameter to accept invitation
#config.accept_invitation_url = 'http://frontend.com/accept_invitation'
# maximum login attempts before locking an account
#config.maximum_attempts = 3
# strategy to lock an account: :none or :failed_attempts
#config.lock_strategy = :failed_attempts
# strategy to use when unlocking accounts: :time, :email or :both
#config.unlock_strategy = :time
# interval to unlock an account if unlock_strategy is :time
#config.unlock_in = 60.minutes
# interval after which to reset failed attempts counter of an account
#config.reset_attempts_in = 60.minutes
# url used to create email link with unlock token
#config.unlock_account_url = 'http://frontend.com/unlock-account'
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/inflections.rb | spec/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/cookies_serializer.rb | spec/dummy/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/assets.rb | spec/dummy/config/initializers/assets.rb | # Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
# Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
# Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/backtrace_silencers.rb | spec/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/mime_types.rb | spec/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/initializers/cors.rb | spec/dummy/config/initializers/cors.rb | # Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
# Rails.application.config.middleware.insert_before 0, Rack::Cors do
# allow do
# origins 'example.com'
#
# resource '*',
# headers: :any,
# methods: [:get, :post, :put, :patch, :delete, :options, :head]
# end
# end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/environments/test.rb | spec/dummy/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{1.hour.to_i}"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Store uploaded files on the local file system in a temporary directory
config.active_storage.service = :test
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {host: 'localhost:3000'}
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/environments/development.rb | spec/dummy/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/dummy/config/environments/production.rb | spec/dummy/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "dummy_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/lib/rails_jwt_auth_spec.rb | spec/lib/rails_jwt_auth_spec.rb | require 'rails_helper'
describe RailsJwtAuth do
before(:all) { initialize_orm('ActiveRecord') }
describe '#send_email' do
let(:unconfirmed_user) { FactoryBot.create(:active_record_unconfirmed_user) }
after { RailsJwtAuth.deliver_later = false }
context 'when deliver_later options is false' do
before { RailsJwtAuth.deliver_later = false }
it 'uses deliver method' do
mock2 = OpenStruct.new(deliver: true)
mock = OpenStruct.new(confirmation_instructions: mock2)
expect(RailsJwtAuth.mailer).to receive(:with).with(user_id: unconfirmed_user.id.to_s)
.and_return(mock)
expect(mock2).to receive(:deliver)
RailsJwtAuth.send_email(:confirmation_instructions, unconfirmed_user)
end
end
context 'when deliver_later options is false' do
before { RailsJwtAuth.deliver_later = true }
it 'uses deliver method' do
mock2 = OpenStruct.new(deliver_later: true)
mock = OpenStruct.new(confirmation_instructions: mock2)
expect(RailsJwtAuth.mailer).to receive(:with).with(user_id: unconfirmed_user.id.to_s)
.and_return(mock)
expect(mock2).to receive(:deliver_later)
RailsJwtAuth.send_email(:confirmation_instructions, unconfirmed_user)
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/lib/session_spec.rb | spec/lib/session_spec.rb | require 'rails_helper'
require 'rails_jwt_auth/session'
module RailsJwtAuth
describe Session do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:pass) { '12345678' }
let(:user) { FactoryBot.create("#{orm.underscore}_user", password: pass) }
let(:unconfirmed_user) {
FactoryBot.create("#{orm.underscore}_unconfirmed_user", password: pass)
}
describe '#initialize' do
it 'does not fail when pass empty hash' do
allow(RailsJwtAuth).to receive(:downcase_auth_field).and_return(true)
expect { Session.new }.not_to raise_exception
end
it 'downcase auth_field when options is enabled' do
session = Session.new('email' => 'AAA@email.com', password: pass)
expect(session.instance_variable_get(:@auth_field_value)).to eq('AAA@email.com')
allow(RailsJwtAuth).to receive(:downcase_auth_field).and_return(true)
session = Session.new('email' => 'AAA@email.com', password: pass)
expect(session.instance_variable_get(:@auth_field_value)).to eq('aaa@email.com')
end
end
describe '#valid?' do
it 'returns true when session is valid' do
session = Session.new('email' => user.email, password: pass)
expect(session.valid?).to be_truthy
end
it 'returns false when session is invalid' do
session = Session.new('email' => user.email, password: 'invalid')
expect(session.valid?).to be_falsey
end
it 'validates auth field and password presence' do
session = Session.new
expect(session.valid?).to be_falsey
expect(get_record_error(session, :email)).to eq(:blank)
expect(get_record_error(session, :password)).to eq(:blank)
end
it 'validates auth field' do
session = Session.new('email' => 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :session)).to eq(:invalid)
RailsJwtAuth.avoid_email_errors = false
session = Session.new('email' => 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :email)).to eq(:invalid)
end
it 'validates password' do
session = Session.new('email' => user.email, password: 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :session)).to eq(:invalid)
RailsJwtAuth.avoid_email_errors = false
session = Session.new('email' => user.email, password: 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :password)).to eq(:invalid)
end
it 'validates user is valid' do
session = Session.new('email' => user.email, password: pass)
allow(session.user).to receive(:save).and_return(false)
expect(session.generate!(nil)).to be_falsey
expect(get_record_error(session, "#{orm.underscore}_user".to_sym)).to eq(:invalid)
end
it 'validates user is unconfirmed' do
session = Session.new('email' => unconfirmed_user.email, password: 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :email)).to eq(:unconfirmed)
end
it 'validates user is not locked' do
user.lock_access
session = Session.new('email' => user.email, password: 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :email)).to eq(:locked)
end
it 'avoid validates password when exist other errors' do
session = Session.new('email' => unconfirmed_user.email, password: 'invalid')
expect(session.valid?).to be_falsey
expect(get_record_error(session, :password)).to be_nil
end
end
describe '#generate!' do
it 'increase failed attemps' do
Session.new('email' => user.email, password: 'invalid').generate!(nil)
expect(user.reload.failed_attempts).to eq(1)
end
it 'unlock access when lock is expired' do
travel_to(Date.today - 30.days) { user.lock_access }
session = Session.new('email' => user.email, password: pass)
expect(session.generate!(nil)).to be_truthy
expect(user.reload.locked_at).to be_nil
end
it 'resets recovery password' do
travel_to(Date.today - 30.days) { user.send_reset_password_instructions }
session = Session.new('email' => user.email, password: pass)
expect(session.generate!(nil)).to be_truthy
expect(user.reload.reset_password_token).to be_nil
expect(user.reload.reset_password_sent_at).to be_nil
end
it 'track session' do
freeze_time
request = OpenStruct.new(ip: '127.0.0.1')
session = Session.new('email' => user.email, password: pass)
expect(session.generate!(request)).to be_truthy
expect(user.reload.last_sign_in_at).to eq(Time.current)
expect(user.reload.last_sign_in_ip).to eq('127.0.0.1')
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/spec/mailers/mailer_spec.rb | spec/mailers/mailer_spec.rb | require 'rails_helper'
RSpec.describe RailsJwtAuth::Mailer, type: :mailer do
%w[ActiveRecord Mongoid].each do |orm|
context "when use #{orm}" do
before(:all) { initialize_orm(orm) }
let(:mail_params) { {user_id: user.id.to_s } }
describe '#confirmation_instructions' do
let(:user) do
FactoryBot.create("#{orm.underscore}_unconfirmed_user",
confirmation_token: 'abcd', confirmation_sent_at: Time.current)
end
let(:mail) { described_class.with(mail_params).confirmation_instructions.deliver_now }
let(:url) { "#{RailsJwtAuth.confirm_email_url}?confirmation_token=#{user.confirmation_token}" }
it 'sends email with correct info' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq(I18n.t('rails_jwt_auth.mailer.confirmation_instructions.subject'))
expect(mail.to).to include(user.email)
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
expect(mail.body).to include(url)
end
context 'when confirm_email_url option is defined with hash url' do
before do
RailsJwtAuth.confirm_email_url = 'http://www.host.com/#/url?param=value'
end
it 'uses this to generate confirmation url' do
url = "#{RailsJwtAuth.confirm_email_url}&confirmation_token=#{user.confirmation_token}"
expect(mail.body).to include(url)
end
end
context 'when confirmation_url option is not defined' do
it 'raises NotConfirmationsUrl exception' do
allow(RailsJwtAuth).to receive(:confirm_email_url).and_return(nil)
expect { mail }.to raise_error(RailsJwtAuth::NotConfirmationsUrl)
end
end
context 'when model has unconfirmed_email' do
it 'sends email with correct info' do
user.unconfirmed_email = 'new@email.com'
user.save
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq(I18n.t('rails_jwt_auth.mailer.confirmation_instructions.subject'))
expect(mail.to).to include('new@email.com')
end
end
end
describe '#email_chage_notification' do
let(:user) { FactoryBot.create("#{orm.underscore}_user") }
let(:mail) { described_class.with(mail_params).email_change_requested_notification.deliver_now }
it 'sends email with notification' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq('Email change')
expect(mail.to).to eq([user.email])
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
end
end
describe '#reset_password_instructions' do
let(:user) do
FactoryBot.create("#{orm.underscore}_user", reset_password_token: 'abcd',
reset_password_sent_at: Time.current)
end
let(:mail) { described_class.with(mail_params).reset_password_instructions.deliver_now }
let(:url) { "#{RailsJwtAuth.reset_password_url}?reset_password_token=#{user.reset_password_token}" }
it 'sends email with correct info' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq(I18n.t('rails_jwt_auth.mailer.reset_password_instructions.subject'))
expect(mail.to).to include(user.email)
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
expect(mail.body).to include(url)
end
context 'when reset_password_url option is defined with hash url' do
before do
RailsJwtAuth.reset_password_url = 'http://www.host.com/#/url?param=value'
end
it 'uses this to generate confirmation url' do
url = "#{RailsJwtAuth.reset_password_url}&reset_password_token=#{user.reset_password_token}"
expect(mail.body).to include(url)
end
end
context 'when reset_password_url option is not defined' do
it 'raises NotResetPasswordsUrl exception' do
allow(RailsJwtAuth).to receive(:reset_password_url).and_return(nil)
expect { mail }.to raise_error(RailsJwtAuth::NotResetPasswordsUrl)
end
end
end
describe '#password_chaged_notification' do
let(:user) { FactoryBot.create("#{orm.underscore}_user") }
let(:mail) { described_class.with(mail_params).password_changed_notification.deliver_now }
it 'sends email with notification' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq('Password changed')
expect(mail.to).to eq([user.email])
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
end
end
describe 'invitation_instructions' do
let(:user) do
FactoryBot.create("#{orm.underscore}_user", invitation_token: 'abcd')
end
let(:mail) { described_class.with(mail_params).invitation_instructions.deliver_now }
let(:url) { "#{RailsJwtAuth.accept_invitation_url}?invitation_token=#{user.invitation_token}" }
it 'sends email with correct info' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq(I18n.t('rails_jwt_auth.mailer.invitation_instructions.subject'))
expect(mail.to).to include(user.email)
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
expect(mail.body).to include(url)
end
context 'when accept_invitation_url option is defined with hash url' do
before do
RailsJwtAuth.accept_invitation_url = 'http://www.host.com/#/url?param=value'
end
it 'uses this to generate invitation url' do
url = "#{RailsJwtAuth.accept_invitation_url}&invitation_token=#{user.invitation_token}"
expect(mail.body).to include(url)
end
end
context 'when accept_invitation_url option is not defined' do
it 'raises NotInvitationsUrl exception' do
allow(RailsJwtAuth).to receive(:accept_invitation_url).and_return(nil)
expect { mail }.to raise_error(RailsJwtAuth::NotInvitationsUrl)
end
end
end
describe 'unlock_instructions' do
let(:user) do
FactoryBot.create(
"#{orm.underscore}_user",
locked_at: 2.minutes.ago,
unlock_token: SecureRandom.base58(24)
)
end
let(:mail) { described_class.with(mail_params).unlock_instructions.deliver_now }
let(:url) { "#{RailsJwtAuth.unlock_account_url}?unlock_token=#{user.unlock_token}" }
it 'sends email with correct info' do
expect { mail }.to change { ActionMailer::Base.deliveries.count }.by(1)
expect(mail.subject).to eq(I18n.t('rails_jwt_auth.mailer.unlock_instructions.subject'))
expect(mail.to).to include(user.email)
expect(mail.from).to include(RailsJwtAuth.mailer_sender)
expect(mail.body).to include(url)
end
context 'when unlock_account_url option is defined with hash url' do
before do
RailsJwtAuth.unlock_account_url = 'http://www.host.com/#/url?param=value'
end
it 'uses this to generate unlock url' do
url = "#{RailsJwtAuth.unlock_account_url}&unlock_token=#{user.unlock_token}"
expect(mail.body).to include(url)
end
end
context 'when unlock_account_url option is not defined' do
it 'raises NotUnlockUrl exception' do
allow(RailsJwtAuth).to receive(:unlock_account_url).and_return(nil)
expect { mail }.to raise_error(RailsJwtAuth::NotUnlockUrl)
end
end
end
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth.rb | lib/rails_jwt_auth.rb | require 'active_support/core_ext/integer/time'
require 'bcrypt'
require 'rails_jwt_auth/engine'
require 'rails_jwt_auth/jwt_manager'
require 'rails_jwt_auth/session'
module RailsJwtAuth
NotConfirmationsUrl = Class.new(StandardError)
NotInvitationsUrl = Class.new(StandardError)
NotResetPasswordsUrl = Class.new(StandardError)
NotUnlockUrl = Class.new(StandardError)
InvalidJwtPayload = Class.new(StandardError)
mattr_accessor :model_name
self.model_name = 'User'
mattr_accessor :auth_field_name
self.auth_field_name = 'email'
mattr_accessor :email_field_name
self.email_field_name = 'email'
mattr_accessor :email_regex
self.email_regex = URI::MailTo::EMAIL_REGEXP
mattr_accessor :downcase_auth_field
self.downcase_auth_field = false
mattr_accessor :jwt_expiration_time
self.jwt_expiration_time = 7.days
mattr_accessor :jwt_issuer
self.jwt_issuer = 'RailsJwtAuth'
mattr_accessor :simultaneous_sessions
self.simultaneous_sessions = 2
mattr_accessor :mailer_name
self.mailer_name = 'RailsJwtAuth::Mailer'
mattr_accessor :mailer_sender
self.mailer_sender = 'initialize-mailer_sender@example.com'
mattr_accessor :send_email_change_requested_notification
self.send_email_change_requested_notification = true
mattr_accessor :send_password_changed_notification
self.send_password_changed_notification = true
mattr_accessor :confirmation_expiration_time
self.confirmation_expiration_time = 1.day
mattr_accessor :reset_password_expiration_time
self.reset_password_expiration_time = 1.day
mattr_accessor :invitation_expiration_time
self.invitation_expiration_time = 2.days
mattr_accessor :deliver_later
self.deliver_later = false
mattr_accessor :maximum_attempts
self.maximum_attempts = 3
mattr_accessor :lock_strategy
self.lock_strategy = :none
mattr_accessor :unlock_strategy
self.unlock_strategy = :time
mattr_accessor :unlock_in
self.unlock_in = 60.minutes
mattr_accessor :reset_attempts_in
self.reset_attempts_in = 60.minutes
mattr_accessor :confirm_email_url
self.confirm_email_url = nil
mattr_accessor :reset_password_url
self.reset_password_url = nil
mattr_accessor :accept_invitation_url
self.accept_invitation_url = nil
mattr_accessor :unlock_account_url
self.unlock_account_url = nil
mattr_accessor :avoid_email_errors
self.avoid_email_errors = true
def self.setup
yield self
end
def self.model
model_name.constantize
end
def self.mailer
mailer_name.constantize
end
def self.table_name
model_name.underscore.pluralize
end
# Thanks to https://github.com/heartcombo/devise/blob/master/lib/devise.rb#L496
def self.friendly_token(length = 24)
# To calculate real characters, we must perform this operation.
# See SecureRandom.urlsafe_base64
rlength = (length * 3 / 4) - 1
SecureRandom.urlsafe_base64(rlength, true).tr('lIO0', 'sxyz')
end
def self.send_email(method, user)
mailer = RailsJwtAuth.mailer.with(user_id: user.id.to_s).public_send(method)
RailsJwtAuth.deliver_later ? mailer.deliver_later : mailer.deliver
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth/session.rb | lib/rails_jwt_auth/session.rb | module RailsJwtAuth
class Session
attr_reader :user, :errors, :jwt
Errors = Struct.new :details # simulate ActiveModel::Errors
def initialize(params={})
@auth_field_value = (params[RailsJwtAuth.auth_field_name] || '').strip
@auth_field_value.downcase! if RailsJwtAuth.downcase_auth_field
@password = params[:password]
find_user if @auth_field_value.present?
end
def valid?
validate!
!errors?
end
def generate!(request)
if valid?
user.clean_reset_password if recoverable?
user.clean_lock if lockable?
user.track_session_info(request) if trackable?
user.load_auth_token
unless user.save
add_error(RailsJwtAuth.model_name.underscore, :invalid)
return false
end
generate_jwt(request)
true
else
user.failed_attempt if lockable?
false
end
end
private
def validate!
# Can't use ActiveModel::Validations since we have dynamic fields
@errors = Errors.new({})
validate_auth_field_presence
validate_password_presence
validate_user_exist
validate_user_is_confirmed if confirmable?
validate_user_is_not_locked if lockable?
validate_user_password unless errors?
validate_custom
end
def find_user
@user = RailsJwtAuth.model.where(RailsJwtAuth.auth_field_name => @auth_field_value).first
end
def confirmable?
@user&.kind_of?(RailsJwtAuth::Confirmable)
end
def lockable?
@user&.kind_of?(RailsJwtAuth::Lockable)
end
def recoverable?
@user&.kind_of?(RailsJwtAuth::Recoverable)
end
def trackable?
@user&.kind_of?(RailsJwtAuth::Trackable)
end
def user?
@user.present?
end
def field_error(field)
RailsJwtAuth.avoid_email_errors ? :session : field
end
def validate_auth_field_presence
add_error(RailsJwtAuth.auth_field_name, :blank) if @auth_field_value.blank?
end
def validate_password_presence
add_error(:password, :blank) if @password.blank?
end
def validate_user_exist
add_error(field_error(RailsJwtAuth.auth_field_name), :invalid) unless @user
end
def validate_user_password
add_error(field_error(:password), :invalid) unless @user.authenticate(@password)
end
def validate_user_is_confirmed
add_error(RailsJwtAuth.email_field_name, :unconfirmed) unless @user.confirmed?
end
def validate_user_is_not_locked
add_error(RailsJwtAuth.email_field_name, :locked) if @user.access_locked?
end
def validate_custom
# allow add custom validations overwriting this method
end
def add_error(field, detail)
@errors.details[field.to_sym] ||= []
@errors.details[field.to_sym].push({error: detail})
end
def errors?
@errors.details.any?
end
def generate_jwt(request)
@jwt = JwtManager.encode(user.to_token_payload(request))
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth/version.rb | lib/rails_jwt_auth/version.rb | module RailsJwtAuth
VERSION = '2.0.3'
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth/spec_helpers.rb | lib/rails_jwt_auth/spec_helpers.rb | module RailsJwtAuth
module SpecHelpers
def sign_in(user)
allow_any_instance_of(RailsJwtAuth::AuthenticableHelper)
.to receive(:authenticate!).and_return(true)
allow_any_instance_of(RailsJwtAuth::AuthenticableHelper)
.to receive(:current_user).and_return(user.class.find(user.id))
end
def sign_out
allow_any_instance_of(RailsJwtAuth::AuthenticableHelper)
.to receive(:authenticate!).and_call_original
allow_any_instance_of(RailsJwtAuth::AuthenticableHelper)
.to receive(:current_user).and_call_original
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth/jwt_manager.rb | lib/rails_jwt_auth/jwt_manager.rb | require 'jwt'
module RailsJwtAuth
module JwtManager
def self.secret_key_base
Rails.application.secret_key_base
end
# Encodes and signs JWT Payload with expiration
def self.encode(payload)
raise InvalidJwtPayload unless payload
payload.reverse_merge!(meta)
JWT.encode(payload, secret_key_base)
end
# Decodes the JWT with the signed secret
# [{"auth_token"=>"xxx", "exp"=>148..., "iss"=>"RJA"}, {"typ"=>"JWT", "alg"=>"HS256"}]
def self.decode(token)
JWT.decode(token, secret_key_base)
end
# Default options to be encoded in the token
def self.meta
{
exp: RailsJwtAuth.jwt_expiration_time.from_now.to_i,
iss: RailsJwtAuth.jwt_issuer
}
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/rails_jwt_auth/engine.rb | lib/rails_jwt_auth/engine.rb | module RailsJwtAuth
class Engine < ::Rails::Engine
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/generators/rails_jwt_auth/migrate_generator.rb | lib/generators/rails_jwt_auth/migrate_generator.rb | class RailsJwtAuth::MigrateGenerator < Rails::Generators::Base
include Rails::Generators::Migration
source_root File.expand_path('../templates', __dir__)
def self.next_migration_number(_dir)
Time.current.strftime('%Y%m%d%H%M%S')
end
def create_initializer_file
migration_template 'migration.rb', "db/migrate/create_#{RailsJwtAuth.table_name}.rb"
end
def migration_version
"[#{Rails.version.split('.')[0..1].join('.')}]"
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/generators/rails_jwt_auth/install_generator.rb | lib/generators/rails_jwt_auth/install_generator.rb | class RailsJwtAuth::InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../../templates', __FILE__)
def create_initializer_file
copy_file 'initializer.rb', 'config/initializers/rails_jwt_auth.rb'
end
def create_routes
route "resource :session, controller: 'rails_jwt_auth/sessions', only: [:create, :destroy]"
route "resource :registration, controller: 'rails_jwt_auth/registrations', only: [:create]"
route %q(
resource :profile, controller: 'rails_jwt_auth/profiles', only: %i[show update] do
collection do
put :email
put :password
end
end
)
route "resources :confirmations, controller: 'rails_jwt_auth/confirmations', only: [:create, :update]"
route "resources :reset_passwords, controller: 'rails_jwt_auth/reset_passwords', only: [:show, :create, :update]"
route "resources :invitations, controller: 'rails_jwt_auth/invitations', only: [:show, :create, :update]"
route "resources :unlock_accounts, controller: 'rails_jwt_auth/unlock_accounts', only: %i[update]"
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/generators/templates/initializer.rb | lib/generators/templates/initializer.rb | RailsJwtAuth.setup do |config|
# authentication model class name
# config.model_name = 'User'
# field name used to authentication with password
# config.auth_field_name = 'email'
# define email field name used to send emails
# config.email_field_name = 'email'
# Regex used to validate email input on requests like reset password
# config.email_regex = URI::MailTo::EMAIL_REGEXP
# apply downcase to auth field when save user and when init session
# config.downcase_auth_field = false
# expiration time for generated tokens
# config.jwt_expiration_time = 7.days
# the "iss" (issuer) claim identifies the principal that issued the JWT
# config.jwt_issuer = 'RailsJwtAuth'
# number of simultaneously sessions for an user
# config.simultaneous_sessions = 2
# mailer class name
# config.mailer_name = 'RailsJwtAuth::Mailer'
# mailer sender
# config.mailer_sender = 'initialize-mailer_sender@example.com'
# activate email notification when email is changed
# config.send_email_change_requested_notification = true
# activate email notification when password is changed
# config.send_password_changed_notification = true
# expiration time for confirmation tokens
# config.confirmation_expiration_time = 1.day
# expiration time for reset password tokens
# config.reset_password_expiration_time = 1.day
# time an invitation is valid after sent
# config.invitation_expiration_time = 2.days
# uses deliver_later to send emails instead of deliver method
# config.deliver_later = false
# maximum login attempts before locking an account
# config.maximum_attempts = 3
# strategy to lock an account: :none or :failed_attempts
# config.lock_strategy = :failed_attempts
# strategy to use when unlocking accounts: :time, :email or :both
# config.unlock_strategy = :time
# interval to unlock an account if unlock_strategy is :time
# config.unlock_in = 60.minutes
# interval after which to reset failed attempts counter of an account
# config.reset_attempts_in = 60.minutes
#
# url used to create email link with confirmation token
# config.confirm_email_url = 'http://frontend.com/confirm-email'
# url used to create email link with reset password token
# config.reset_password_url = 'http://frontend.com/reset-password'
# url used to create email link with activation token parameter to accept invitation
# config.accept_invitation_url = 'http://frontend.com/accept-invitation'
# url used to create email link with unlock token
# config.unlock_account_url = 'http://frontend.com/unlock-account'
# set false to avoid giving clue about the existing emails with errors
# config.avoid_email_errors = true
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
rjurado01/rails_jwt_auth | https://github.com/rjurado01/rails_jwt_auth/blob/9726ea4cfe2c27c728a5a1926545cc98d82b025c/lib/generators/templates/migration.rb | lib/generators/templates/migration.rb | class Create<%= RailsJwtAuth.model_name.pluralize %> < ActiveRecord::Migration<%= migration_version %>
def change
create_table :<%= RailsJwtAuth.table_name %> do |t|
t.string :email
t.string :password_digest
t.string :auth_tokens
## Confirmable
# t.string :unconfirmed_email
# t.string :confirmation_token
# t.datetime :confirmation_sent_at
# t.datetime :confirmed_at
## Recoverable
# t.string :reset_password_token
# t.datetime :reset_password_sent_at
## Trackable
# t.string :last_sign_in_ip
# t.datetime :last_sign_in_at
# t.string :last_request_ip
# t.datetime :last_request_at
## Invitable
# t.string :invitation_token
# t.datetime :invitation_sent_at
# t.datetime :invitation_accepted_at
## Lockable
# t.integer :failed_attempts
# t.string :unlock_token
# t.datetime :first_failed_attempt_at
# t.datetime :locked_at
end
end
end
| ruby | MIT | 9726ea4cfe2c27c728a5a1926545cc98d82b025c | 2026-01-04T17:58:16.101421Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-sidekiq/error_worker.rb | ruby/sentry-sidekiq/error_worker.rb | # frozen_string_literal: true
require "sidekiq"
require "sentry-sidekiq"
Sentry.init do |config|
config.breadcrumbs_logger = [:sentry_logger]
# replace it with your sentry dsn
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
end
class ErrorWorker
include Sidekiq::Worker
sidekiq_options retry: 0
def perform
1 / 0
end
end
ErrorWorker.perform_async
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-ruby/without_integrations/app.rb | ruby/sentry-ruby/without_integrations/app.rb | require "sentry-ruby"
Sentry.init do |config|
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
end
Sentry.capture_message("test Sentry", hint: { background: false })
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-ruby/sinatra/app.rb | ruby/sentry-ruby/sinatra/app.rb | require 'sentry-ruby'
Sentry.init do |config|
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
config.traces_sample_rate = 1.0
# skips handled exceptions
config.before_send = lambda do |event, hint|
handled_errors = Sinatra::Application.errors.keys.grep(Class) # skip status codes
should_skip = false
handled_errors.each do |error|
if hint[:exception].is_a?(error)
should_skip = true
end
end
event unless should_skip
end
end
# this needs to be placed **after** SDK is initialized
# see https://github.com/getsentry/sentry-ruby/issues/1778 for more information
require 'sinatra'
use Sentry::Rack::CaptureExceptions
error RuntimeError do
halt 400, "this error will not be reported"
end
get "/handled_exception" do
raise "foo"
end
get "/" do
1/0
end
get "/connect_trace" do
event = Sentry.capture_message("sentry-trace test")
event.event_id
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-ruby/crons/Rakefile.rb | ruby/sentry-ruby/crons/Rakefile.rb | require "sentry-ruby"
Sentry.init do |config|
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
end
# Create a config from an interval schedule (every 10 minutes)
monitor_config = Sentry::Cron::MonitorConfig.from_interval(
1,
:hour,
checkin_margin: 15, # Optional check-in margin in minutes
max_runtime: 15 # Optional max runtime in minutes
)
task :successful_cron do
# This check-in will tell Sentry that the cron job started and is in-progress.
# Sentry will expect it to send a :ok check-in within max_runtime minutes.
check_in_id = Sentry.capture_check_in(
"rake-task-example",
:in_progress,
monitor_config: monitor_config
)
puts "rake task is running"
Sentry.capture_check_in(
"rake-task-example",
:ok,
check_in_id: check_in_id,
monitor_config: monitor_config
)
end
task :failed_cron do
check_in_id = Sentry.capture_check_in(
"rake-task-example",
:in_progress,
monitor_config: monitor_config
)
puts "rake task is running"
# Sending an :error check-in will mark the cron job as errored on Sentry,
# and this will also create a new Issue on Sentry linked to that cron job.
Sentry.capture_check_in(
"rake-task-example",
:error,
check_in_id: check_in_id,
monitor_config: monitor_config
)
end
task :heartbeat do
puts "rake task is running"
# Heartbeat check-in sends :ok status
# without the parent check_in_id.
# This will tell Sentry that this cron run was successful.
Sentry.capture_check_in(
"rake-task-example",
:ok,
monitor_config: monitor_config
)
end
task :raise_exception do
check_in_id = Sentry.capture_check_in(
"rake-task-example",
:in_progress,
monitor_config: monitor_config
)
puts "rake task is running"
# If you raise an error within the job, Sentry will report it and link
# the issue to the cron job. But the job itself will be marked as "in progress"
# until either your job sends another check-in, or it timeouts.
raise "This job errored out"
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-ruby/rake/Rakefile.rb | ruby/sentry-ruby/rake/Rakefile.rb | require "sentry-ruby"
Sentry.init do |config|
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
end
# bundle exec rake raise_exception
task :raise_exception do
1/0
end
# bundle exec rake send_message[foo]
task :send_message, ['name'] do |_task, args|
Sentry.capture_message("message from #{args[:name]}")
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
getsentry/examples | https://github.com/getsentry/examples/blob/02dbc89a35fe1804dbe00e481716a9dd79920cf5/ruby/sentry-resque/app.rb | ruby/sentry-resque/app.rb | # frozen_string_literal: true
require "active_job"
require "resque"
require "sentry-resque"
Sentry.init do |config|
config.breadcrumbs_logger = [:sentry_logger]
# replace it with your sentry dsn
config.dsn = 'https://2fb45f003d054a7ea47feb45898f7649@o447951.ingest.sentry.io/5434472'
end
class MyJob < ActiveJob::Base
self.queue_adapter = :resque
def perform
raise "foo"
end
end
worker = Resque::Worker.new(:default)
MyJob.perform_later
begin
worker.work(0)
rescue => e
puts("active job failed because of \"#{e.message}\"")
end
class Foo
def self.perform
1 / 0
end
end
Resque::Job.create(:default, Foo)
begin
worker.work(0)
rescue => e
puts("inline job failed because of \"#{e.message}\"")
end
| ruby | MIT | 02dbc89a35fe1804dbe00e481716a9dd79920cf5 | 2026-01-04T17:57:20.388692Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.