//  [ruby]
  def sso_login
    raise Discourse::NotFound unless SiteSetting.enable_discourse_connect
    raise Discourse::ReadOnly if @readonly_mode && !staff_writes_only_mode?

    params.require(:sso)
    params.require(:sig)

    begin
      sso = DiscourseConnect.parse(request.query_string, secure_session: secure_session)
    rescue DiscourseConnect::ParseError => e
      connect_verbose_warn { "Verbose SSO log: Signature parse error\n\n#{e.message}\n\n#{sso&.diagnostics}" }

      # Do NOT pass the error text to the client, it would give them the correct signature
      return render_sso_error(text: I18n.t("discourse_connect.login_error"), status: 422)
    end

    if !sso.nonce_valid?
      connect_verbose_warn { "Verbose SSO log: #{sso.nonce_error}\n\n#{sso.diagnostics}" }
      return render_sso_error(text: I18n.t("discourse_connect.timeout_expired"), status: 419)
    end

    if ScreenedIpAddress.should_block?(request.remote_ip)
      connect_verbose_warn { "Verbose SSO log: IP address is blocked #{request.remote_ip}\n\n#{sso.diagnostics}" }
      return render_sso_error(text: I18n.t("discourse_connect.unknown_error"), status: 500)
    end

    return_path = sso.return_path
    sso.expire_nonce!

    begin
      invite = validate_invitiation!(sso)

      if user = sso.lookup_or_create_user(request.remote_ip)
        raise Discourse::ReadOnly if staff_writes_only_mode? && !user&.staff?

        if user.suspended?
          render_sso_error(text: failed_to_login(user)[:error], status: 403)
          return
        end

        # users logging in via SSO using an invite do not need to be approved,
        # they are already pre-approved because they have been invited
        if SiteSetting.must_approve_users? && !user.approved? && invite.blank?
          if SiteSetting.discourse_connect_not_approved_url.present?
            redirect_to SiteSetting.discourse_connect_not_approved_url, allow_other_host: true
          else
            render_sso_error(text: I18n.t("discourse_connect.account_not_approved"), status: 403)
          end
          return

        # we only want to redeem the invite if
        # the user has not already redeemed an invite
        # (covers the same SSO user visiting an invite link)
        elsif invite.present? && user.invited_user.blank?
          redeem_invitation(invite, sso)

          # we directly call user.activate here instead of going
          # through the UserActivator path because we assume the account
          # is valid from the SSO provider's POV and do not need to
          # send an activation email to the user
          user.activate
          login_sso_user(sso, user)

          topic = invite.topics.first
          return_path = topic.present? ? path(topic.relative_url) : path("/")
        elsif !user.active?
          activation = UserActivator.new(user, request, session, cookies)
          activation.finish
          session["user_created_message"] = activation.message
          return redirect_to(users_account_created_path)
        else
          login_sso_user(sso, user)
        end

        # If it's not a relative URL check the host
        if return_path !~ /^\/[^\/]/
          begin
            uri = URI(return_path)
            if (uri.hostname == Discourse.current_hostname)
              return_path = uri.to_s
            elsif !SiteSetting.discourse_connect_allows_all_return_paths
              return_path = path("/")
            end
          rescue
            return_path = path("/")
          end
        end

        # this can be done more surgically with a regex
        # but it the edge case of never supporting redirects back to
        # any url with `/session/sso` in it anywhere is reasonable
        if return_path.include?(path("/session/sso"))
          return_path = path("/")
        end

        redirect_to return_path, allow_other_host: true
      else
        render_sso_error(text: I18n.t("discourse_connect.not_found"), status: 500)
      end
    rescue ActiveRecord::RecordInvalid => e

      connect_verbose_warn { <<~TEXT }
        Verbose SSO log: Record was invalid: #{e.record.class.name} #{e.record.id}
        #{e.record.errors.to_h}

        Attributes:
        #{e.record.attributes.slice(*DiscourseConnectBase::ACCESSORS.map(&:to_s))}

        SSO Diagnostics:
        #{sso.diagnostics}
      TEXT

      text = nil

      # If there's a problem with the email we can explain that
      if (e.record.is_a?(User) && e.record.errors[:primary_email].present?)
        if e.record.email.blank?
          text = I18n.t("discourse_connect.no_email")
        else
          text = I18n.t("discourse_connect.email_error", email: ERB::Util.html_escape(e.record.email))
        end
      end

      render_sso_error(text: text || I18n.t("discourse_connect.unknown_error"), status: 500)
    rescue DiscourseConnect::BlankExternalId
      render_sso_error(text: I18n.t("discourse_connect.blank_id_error"), status: 500)
    rescue Invite::ValidationFailed => e
      render_sso_error(text: e.message, status: 400)
    rescue Invite::RedemptionFailed => e
      render_sso_error(text: I18n.t("discourse_connect.invite_redeem_failed"), status: 412)
    rescue Invite::UserExists => e
      render_sso_error(text: e.message, status: 412)
    rescue => e
      message = +"Failed to create or lookup user: #{e}."
      message << "  "
      message << "  #{sso.diagnostics}"
      message << "  "
      message << "  #{e.backtrace.join("\n")}"

      Rails.logger.error(message)

      render_sso_error(text: I18n.t("discourse_connect.unknown_error"), status: 500)
    end
  end