class Mangadex::Auth

Public Class Methods

check_token() click to toggle source
# File lib/mangadex/auth.rb, line 60
def self.check_token
  JSON.parse(
    Mangadex::Internal::Request.get(
      '/auth/check',
      raw: true,
    )
  )
end
login(username: nil, email: nil, password: nil) { |user| ... } click to toggle source
# File lib/mangadex/auth.rb, line 16
def self.login(username: nil, email: nil, password: nil, &block)
  args = { password: password }
  args.merge!(email: email) if email
  args.merge!(username: username) if username

  response = Mangadex::Internal::Request.post(
    '/auth/login',
    payload: Mangadex::Internal::Definition.validate(args, {
      username: { accepts: String },
      email: { accepts: String },
      password: { accepts: String, required: true },
    }),
  )

  session_valid_until = Time.now + (15 * 60)

  session = response.dig('token', 'session')
  refresh = response.dig('token', 'refresh')

  mangadex_user = Mangadex::Internal::Request.get('/user/me', headers: { Authorization: session })

  user = Mangadex::Api::User.new(
    mangadex_user_id: mangadex_user.data.id,
    session: session,
    refresh: refresh,
    data: mangadex_user.data,
    session_valid_until: session_valid_until,
  )

  user.persist
  user

  Mangadex.context.user = user

  if block_given?
    return yield(user)        
  end

  user
rescue Errors::UnauthorizedError => error
  raise Errors::AuthenticationError.new(error.response)
end
logout() click to toggle source
# File lib/mangadex/auth.rb, line 70
def self.logout
  return true if Mangadex.context.user.nil?

  response = Mangadex::Internal::Request.post(
    '/auth/logout',
  )
  return reponse if response.is_a?(Mangadex::Api::Response) && response.errored?

  clear_user
  true
rescue Mangadex::Errors::UnauthorizedError
  clear_user
  true
end
refresh_token() click to toggle source
# File lib/mangadex/auth.rb, line 86
def self.refresh_token
  !(Mangadex.context.user&.refresh_session!).nil?
end

Private Class Methods

clear_user() click to toggle source
# File lib/mangadex/auth.rb, line 93
def self.clear_user
  return if Mangadex.context.user.nil?

  if Mangadex.context.user.respond_to?(:session=)
    Mangadex.context.user.session = nil
  end
  if Mangadex.context.user.respond_to?(:refresh=)
    Mangadex.context.user.refresh = nil
  end
  Mangadex.storage.clear(Mangadex.context.user.mangadex_user_id)
  Mangadex.context.user = nil
end