mirror of
https://github.com/we-promise/sure.git
synced 2026-04-08 06:44:52 +00:00
* Add mobile SSO support to sessions controller
Add /auth/mobile/:provider route and mobile_sso_start action that
captures device params in session and renders an auto-submitting POST
form to OmniAuth (required by omniauth-rails_csrf_protection).
Modify openid_connect callback to detect mobile_sso session, issue
Doorkeeper tokens via MobileDevice, and redirect to sureapp://oauth/callback
with tokens. Handles MFA users and unlinked accounts with error redirects.
Validates provider name against configured SSO providers and device info
before proceeding.
* Add SSO auth flow to Flutter service and provider
Add buildSsoUrl() and handleSsoCallback() to AuthService for
constructing the mobile SSO URL and parsing tokens from the deep
link callback.
Add startSsoLogin() and handleSsoCallback() to AuthProvider for
launching browser-based SSO and processing the redirect.
* Register deep link listener for SSO callback
Listen for sureapp://oauth/* deep links via app_links package,
handling both cold start (getInitialLink) and warm (uriLinkStream)
scenarios. Routes callbacks to AuthProvider.handleSsoCallback().
* Add Google Sign-In button to Flutter login screen
Add "or" divider and outlined Google Sign-In button that triggers
browser-based SSO via startSsoLogin('google_oauth2').
Add app_links and url_launcher dependencies to pubspec.yaml.
* Fix mobile SSO failure handling to redirect back to app
When OmniAuth fails during mobile SSO flow, redirect to
sureapp://oauth/callback with the error instead of the web login page.
Cleans up mobile_sso session data on failure.
* Address PR review feedback for mobile SSO flow
- Use strong params for device info in mobile_sso_start
- Guard against nil session data in handle_mobile_sso_callback
- Add error handling for AppLinks initialization and stream
- Handle launchUrl false return value in SSO login
- Use user-friendly error messages instead of exposing exceptions
- Reject empty token strings in SSO callback validation
* Consolidate mobile device token logic into MobileDevice model
Extract duplicated device upsert and token issuance code from
AuthController and SessionsController into MobileDevice. Add
CALLBACK_URL constant and URL builder helpers to eliminate repeated
deep-link strings. Add mobile SSO integration tests covering the
full flow, MFA rejection, unlinked accounts, and failure handling.
* Fix CI: resolve Brakeman redirect warnings and rubocop empty line
Move mobile SSO redirect into a private controller method with an
inline string literal so Brakeman can statically verify the target.
Remove unused URL builder helpers from MobileDevice. Fix extra empty
line at end of AuthController class body.
* Use authorization code exchange for mobile SSO and add signup error handling
Replace passing plaintext tokens in mobile SSO redirect URLs with a
one-time authorization code pattern. Tokens are now stored server-side
in Rails.cache (5min TTL) and exchanged via a secure POST to
/api/v1/auth/sso_exchange. Also wraps device/token creation in the
signup action with error handling and sanitizes device error messages.
* Add error handling for login device registration and blank SSO code guard
* Address PR #860 review: fix SSO race condition, add OpenAPI spec, and cleanup
- Fix race condition in sso_exchange by checking Rails.cache.delete return
value to ensure only one request can consume an authorization code
- Use strong parameters (params.require) for sso_exchange code param
- Move inline HTML from mobile_sso_start to a proper view template
- Clear stale session[:mobile_sso] flag on web login paths to prevent
abandoned mobile flows from hijacking subsequent web SSO logins
- Add OpenAPI/rswag spec for all auth API endpoints
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix mobile SSO test to match authorization code exchange pattern
The test was asserting tokens directly in the callback URL, but the code
uses an authorization code exchange pattern. Updated to exchange the code
via the sso_exchange API endpoint. Also swaps in a MemoryStore for this
test since the test environment uses null_store which discards writes.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Refactor mobile OAuth to use single shared application
Replace per-device Doorkeeper::Application creation with a shared
"Sure Mobile" OAuth app. Device tracking uses mobile_device_id on
access tokens instead of oauth_application_id on mobile_devices.
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
235 lines
7.7 KiB
Ruby
235 lines
7.7 KiB
Ruby
module Api
|
|
module V1
|
|
class AuthController < BaseController
|
|
include Invitable
|
|
|
|
skip_before_action :authenticate_request!
|
|
skip_before_action :check_api_key_rate_limit
|
|
skip_before_action :log_api_access
|
|
|
|
def signup
|
|
# Check if invite code is required
|
|
if invite_code_required? && params[:invite_code].blank?
|
|
render json: { error: "Invite code is required" }, status: :forbidden
|
|
return
|
|
end
|
|
|
|
# Validate invite code if provided
|
|
if params[:invite_code].present? && !InviteCode.exists?(token: params[:invite_code]&.downcase)
|
|
render json: { error: "Invalid invite code" }, status: :forbidden
|
|
return
|
|
end
|
|
|
|
# Validate password
|
|
password_errors = validate_password(params[:user][:password])
|
|
if password_errors.any?
|
|
render json: { errors: password_errors }, status: :unprocessable_entity
|
|
return
|
|
end
|
|
|
|
# Validate device info
|
|
unless valid_device_info?
|
|
render json: { error: "Device information is required" }, status: :bad_request
|
|
return
|
|
end
|
|
|
|
user = User.new(user_signup_params)
|
|
|
|
# Create family for new user
|
|
# First user of an instance becomes super_admin
|
|
family = Family.new
|
|
user.family = family
|
|
user.role = User.role_for_new_family_creator
|
|
|
|
if user.save
|
|
# Claim invite code if provided
|
|
InviteCode.claim!(params[:invite_code]) if params[:invite_code].present?
|
|
|
|
# Create device and OAuth token
|
|
begin
|
|
device = MobileDevice.upsert_device!(user, device_params)
|
|
token_response = device.issue_token!
|
|
rescue ActiveRecord::RecordInvalid => e
|
|
render json: { error: "Failed to register device: #{e.message}" }, status: :unprocessable_entity
|
|
return
|
|
end
|
|
|
|
render json: token_response.merge(
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
first_name: user.first_name,
|
|
last_name: user.last_name
|
|
}
|
|
), status: :created
|
|
else
|
|
render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
|
|
end
|
|
end
|
|
|
|
def login
|
|
user = User.find_by(email: params[:email])
|
|
|
|
if user&.authenticate(params[:password])
|
|
# Check MFA if enabled
|
|
if user.otp_required?
|
|
unless params[:otp_code].present? && user.verify_otp?(params[:otp_code])
|
|
render json: {
|
|
error: "Two-factor authentication required",
|
|
mfa_required: true
|
|
}, status: :unauthorized
|
|
return
|
|
end
|
|
end
|
|
|
|
# Validate device info
|
|
unless valid_device_info?
|
|
render json: { error: "Device information is required" }, status: :bad_request
|
|
return
|
|
end
|
|
|
|
# Create device and OAuth token
|
|
begin
|
|
device = MobileDevice.upsert_device!(user, device_params)
|
|
token_response = device.issue_token!
|
|
rescue ActiveRecord::RecordInvalid => e
|
|
render json: { error: "Failed to register device: #{e.message}" }, status: :unprocessable_entity
|
|
return
|
|
end
|
|
|
|
render json: token_response.merge(
|
|
user: {
|
|
id: user.id,
|
|
email: user.email,
|
|
first_name: user.first_name,
|
|
last_name: user.last_name
|
|
}
|
|
)
|
|
else
|
|
render json: { error: "Invalid email or password" }, status: :unauthorized
|
|
end
|
|
end
|
|
|
|
def sso_exchange
|
|
code = sso_exchange_params
|
|
|
|
if code.blank?
|
|
render json: { error: "invalid_or_expired_code", message: "Authorization code is required" }, status: :unauthorized
|
|
return
|
|
end
|
|
|
|
cache_key = "mobile_sso:#{code}"
|
|
cached = Rails.cache.read(cache_key)
|
|
|
|
unless cached.present?
|
|
render json: { error: "invalid_or_expired_code", message: "Authorization code is invalid or expired" }, status: :unauthorized
|
|
return
|
|
end
|
|
|
|
# Atomic delete — only the request that successfully deletes the key may proceed.
|
|
# This prevents a race where two concurrent requests both read the same code.
|
|
unless Rails.cache.delete(cache_key)
|
|
render json: { error: "invalid_or_expired_code", message: "Authorization code is invalid or expired" }, status: :unauthorized
|
|
return
|
|
end
|
|
|
|
render json: {
|
|
access_token: cached[:access_token],
|
|
refresh_token: cached[:refresh_token],
|
|
token_type: cached[:token_type],
|
|
expires_in: cached[:expires_in],
|
|
created_at: cached[:created_at],
|
|
user: {
|
|
id: cached[:user_id],
|
|
email: cached[:user_email],
|
|
first_name: cached[:user_first_name],
|
|
last_name: cached[:user_last_name]
|
|
}
|
|
}
|
|
end
|
|
|
|
def refresh
|
|
# Find the refresh token
|
|
refresh_token = params[:refresh_token]
|
|
|
|
unless refresh_token.present?
|
|
render json: { error: "Refresh token is required" }, status: :bad_request
|
|
return
|
|
end
|
|
|
|
# Find the access token associated with this refresh token
|
|
access_token = Doorkeeper::AccessToken.by_refresh_token(refresh_token)
|
|
|
|
if access_token.nil? || access_token.revoked?
|
|
render json: { error: "Invalid refresh token" }, status: :unauthorized
|
|
return
|
|
end
|
|
|
|
# Create new access token
|
|
new_token = Doorkeeper::AccessToken.create!(
|
|
application: access_token.application,
|
|
resource_owner_id: access_token.resource_owner_id,
|
|
mobile_device_id: access_token.mobile_device_id,
|
|
expires_in: 30.days.to_i,
|
|
scopes: access_token.scopes,
|
|
use_refresh_token: true
|
|
)
|
|
|
|
# Revoke old access token
|
|
access_token.revoke
|
|
|
|
# Update device last seen
|
|
user = User.find(access_token.resource_owner_id)
|
|
device = user.mobile_devices.find_by(device_id: params[:device][:device_id])
|
|
device&.update_last_seen!
|
|
|
|
render json: {
|
|
access_token: new_token.plaintext_token,
|
|
refresh_token: new_token.plaintext_refresh_token,
|
|
token_type: "Bearer",
|
|
expires_in: new_token.expires_in,
|
|
created_at: new_token.created_at.to_i
|
|
}
|
|
end
|
|
|
|
private
|
|
|
|
def user_signup_params
|
|
params.require(:user).permit(:email, :password, :first_name, :last_name)
|
|
end
|
|
|
|
def validate_password(password)
|
|
errors = []
|
|
|
|
if password.blank?
|
|
errors << "Password can't be blank"
|
|
return errors
|
|
end
|
|
|
|
errors << "Password must be at least 8 characters" if password.length < 8
|
|
errors << "Password must include both uppercase and lowercase letters" unless password.match?(/[A-Z]/) && password.match?(/[a-z]/)
|
|
errors << "Password must include at least one number" unless password.match?(/\d/)
|
|
errors << "Password must include at least one special character" unless password.match?(/[!@#$%^&*(),.?":{}|<>]/)
|
|
|
|
errors
|
|
end
|
|
|
|
def valid_device_info?
|
|
device = params[:device]
|
|
return false if device.nil?
|
|
|
|
required_fields = %w[device_id device_name device_type os_version app_version]
|
|
required_fields.all? { |field| device[field].present? }
|
|
end
|
|
|
|
def device_params
|
|
params.require(:device).permit(:device_id, :device_name, :device_type, :os_version, :app_version)
|
|
end
|
|
|
|
def sso_exchange_params
|
|
params.require(:code)
|
|
end
|
|
end
|
|
end
|
|
end
|