<commit_before>require 'cgi'
require 'jwt'
require 'securerandom'
require 'uri'

class ZendeskSSOURL
  attr_reader :user, :return_to, :settings

  def initialize(user, return_to, settings)
    @user = user
    @return_to = return_to
    @settings = settings
  end

  def to_s
    URI::HTTPS.build(
      host: host,
      path: path,
      query: query_hash.to_query,
    ).to_s
  end

  private

  def host
    "#{settings.subdomain}.zendesk.com"
  end

  def path
    '/access/jwt'
  end

  # From https://github.com/zendesk/zendesk_jwt_sso_examples/blob/master/ruby_on_rails_jwt.rb
  def payload
    iat = Time.now.to_i
    jti = "#{iat}/#{SecureRandom.hex(18)}"

    JWT.encode({
      iat: iat,
      jti: jti,
      name: user.first_name,
      email: user.email,
    }, settings.shared_secret)
  end

  def query_hash
    q = { jwt: payload }
    q[:return_to] = CGI.escape(return_to) if return_to.present?<commit_msg>Fix logins to zendesk when user signups with a single name<commit_after>require 'cgi'
require 'jwt'
require 'securerandom'
require 'uri'

class ZendeskSSOURL
  attr_reader :user, :return_to, :settings

  def initialize(user, return_to, settings)
    @user = user
    @return_to = return_to
    @settings = settings
  end

  def to_s
    URI::HTTPS.build(
      host: host,
      path: path,
      query: query_hash.to_query,
    ).to_s
  end

  private

  def host
    "#{settings.subdomain}.zendesk.com"
  end

  def path
    '/access/jwt'
  end

  # From https://github.com/zendesk/zendesk_jwt_sso_examples/blob/master/ruby_on_rails_jwt.rb
  def payload
    iat = Time.now.to_i
    jti = "#{iat}/#{SecureRandom.hex(18)}"

    JWT.encode({
      iat: iat,
      jti: jti,
      name: [user.first_name, user.last_name].join(' '),
      email: user.email,
    }, settings.shared_secret)
  end

  def query_hash
    q = { jwt: payload }
    q[:return_to] = CGI.escape(return_to) if return_to.present?
{'fraction_non_alphanumeric': 0.11700468018720749, 'fraction_numerical': 0.0020800832033281333, 'mean_word_length': 2.8712273641851107, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '647310', 'n_tokens_mistral': 752, 'n_tokens_neox': 721, 'n_words': 156}