| 1 | # frozen_string_literal: true |
| 2 | |
| 3 | class RegistrationsController < ApplicationController |
| 4 | before_action :noindex! |
| 5 | before_action :redirect_if_signed_in |
| 6 | |
| 7 | # GET /auth/signup |
| 8 | def new |
| 9 | end |
| 10 | |
| 11 | # POST /auth/signup |
| 12 | def create |
| 13 | email = params[:email].to_s.strip.downcase |
| 14 | password = params[:password].to_s |
| 15 | password_confirm = params[:password_confirmation].to_s |
| 16 | |
| 17 | if email.blank? || password.blank? |
| 18 | flash.now[:alert] = "Email and password are required." |
| 19 | return render :new, status: :unprocessable_entity |
| 20 | end |
| 21 | |
| 22 | if password != password_confirm |
| 23 | flash.now[:alert] = "Passwords do not match." |
| 24 | return render :new, status: :unprocessable_entity |
| 25 | end |
| 26 | |
| 27 | if password.length < 8 |
| 28 | flash.now[:alert] = "Password must be at least 8 characters." |
| 29 | return render :new, status: :unprocessable_entity |
| 30 | end |
| 31 | |
| 32 | # Step 1 — create the account on smbCloud |
| 33 | SmbcloudAuthService.signup(email: email, password: password) |
| 34 | |
| 35 | # Step 2 — log straight in |
| 36 | access_token = SmbcloudAuthService.login(email: email, password: password) |
| 37 | profile = SmbcloudAuthService.me(access_token: access_token) |
| 38 | user = User.find_or_create_from_smbcloud(profile.merge(access_token: access_token)) |
| 39 | |
| 40 | reset_session |
| 41 | session[:user_id] = user.id |
| 42 | |
| 43 | redirect_to root_path, notice: "Welcome to siGit, #{user.display_name_or_username}!" |
| 44 | |
| 45 | rescue SmbcloudAuthService::AccountIncompleteError |
| 46 | # Account created but requires email verification before first login |
| 47 | redirect_to signin_path, |
| 48 | notice: "Account created. Check your email to verify it, then sign in." |
| 49 | |
| 50 | rescue SmbcloudAuthService::AuthenticationError => e |
| 51 | flash.now[:alert] = e.message.presence || "Sign-up failed. Please try again." |
| 52 | render :new, status: :unprocessable_entity |
| 53 | |
| 54 | rescue KeyError => e |
| 55 | Rails.logger.error("smbCloud configuration error during signup: #{e.message}") |
| 56 | flash.now[:alert] = "Authentication service is not configured. Please contact support." |
| 57 | render :new, status: :internal_server_error |
| 58 | |
| 59 | rescue => e |
| 60 | Rails.logger.error("Unexpected signup error for #{email.inspect}: #{e.message}\n" \ |
| 61 | "#{e.backtrace.first(5).join("\n")}") |
| 62 | flash.now[:alert] = "An unexpected error occurred. Please try again." |
| 63 | render :new, status: :internal_server_error |
| 64 | end |
| 65 | |
| 66 | private |
| 67 | |
| 68 | def redirect_if_signed_in |
| 69 | redirect_to root_path, notice: "You are already signed in." if signed_in? |
| 70 | end |
| 71 | end |