Performance: Token-based authentication
This affects page load speed and interaction responsiveness by how authentication tokens are handled in requests and responses.
class ApplicationController < ActionController::API before_action :authenticate_user def authenticate_user token = request.headers['Authorization']&.split(' ')&.last payload = JwtService.decode(token) rescue JWT::DecodeError render json: { error: 'Unauthorized' }, status: :unauthorized end end
class ApplicationController < ActionController::API before_action :authenticate_user def authenticate_user token = request.headers['Authorization']&.split(' ')&.last user = User.find_by(token: token) render json: { error: 'Unauthorized' }, status: :unauthorized unless user end end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Database token lookup per request | N/A | N/A | Blocks rendering until response | [X] Bad |
| Stateless JWT token validation | N/A | N/A | Faster response, less blocking | [OK] Good |
has_secure_token to add a secure token to models easily.has_secure_password is for passwords, not tokens; others are not valid Rails methods.class User < ApplicationRecord has_secure_token :auth_token end user = User.new user.save puts user.auth_token.nil?
auth_token, so it won't be nil.puts user.auth_token.nil?auth_token is set, nil? returns false, so output is false.class ApiUser < ApplicationRecord has_secure_token :auth_token end user = ApiUser.new user.auth_token = nil user.save puts user.auth_token.nil?
has_secure_token :auth_token generates a token if auth_token.blank? before save (nil.blank? returns true).user.auth_token = nil keeps it blank, so save generates the token. user.auth_token.nil? returns false. No error.request.headers['Authorization'] to find the user.before_action to find user by auth_token from request.headers['Authorization'] and reject if not found correctly uses before_action to authenticate by token. Options B and C misuse cookies and password helpers. Generate a new token on every request and compare with stored token is insecure and impractical.Pass the test and this pattern moves unknown