Class: SpreeCmCommissioner::UserTelegramWebAppAuthenticator

Inherits:
BaseInteractor
  • Object
show all
Defined in:
app/interactors/spree_cm_commissioner/user_telegram_web_app_authenticator.rb

Instance Method Summary collapse

Instance Method Details

#callObject



5
6
7
8
9
10
11
# File 'app/interactors/spree_cm_commissioner/user_telegram_web_app_authenticator.rb', line 5

def call
  return context.fail!(message: 'telegram_bot_username_is_not_valid_or_not_exist_in_db') if telegram_bot.blank?
  return context.fail!(message: 'invalid_init_data') unless checker_context.success?

  context.telegram_user = ActiveSupport::JSON.decode(checker_context.decoded_telegram_init_data['user'])
  context.user = find_or_create_telegram_user
end

#checker_contextObject



36
37
38
# File 'app/interactors/spree_cm_commissioner/user_telegram_web_app_authenticator.rb', line 36

def checker_context
  context.checker_context ||= TelegramWebAppInitDataValidator.call(telegram_init_data: telegram_init_data, bot_token: telegram_bot.token)
end

#find_or_create_telegram_userObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/interactors/spree_cm_commissioner/user_telegram_web_app_authenticator.rb', line 13

def find_or_create_telegram_user
  identity = SpreeCmCommissioner::UserIdentityProvider.telegram.find_or_initialize_by(sub: context.telegram_user['id'])

  provider_telegram_bot = identity.user_identity_provider_telegram_bots.where(telegram_bot_id: telegram_bot.id).first_or_initialize
  provider_telegram_bot. = Time.zone.now

  if identity.new_record?
    user = Spree::User.new do |u|
      identity.name = context.telegram_user['username']
      u.first_name = context.telegram_user['first_name']
      u.last_name = context.telegram_user['last_name']
      u.password = SecureRandom.base64(16)
      u.user_identity_providers = [identity]
    end

    user.save!
    user
  else
    provider_telegram_bot.save!
    identity.user
  end
end

#telegram_botObject



40
41
42
# File 'app/interactors/spree_cm_commissioner/user_telegram_web_app_authenticator.rb', line 40

def telegram_bot
  context.telegram_bot ||= TelegramBot.find_by(username: telegram_bot_username)
end