Class: Mangadex::Auth

Inherits:
Object show all
Extended by:
T::Sig
Defined in:
lib/mangadex/auth.rb

Class Method Summary collapse

Class Method Details

.check_tokenObject



68
69
70
# File 'lib/mangadex/auth.rb', line 68

def self.check_token
  Mangadex::Internal::Request.get('/auth/check')
end

.login(username: nil, email: nil, password: nil, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/mangadex/auth.rb', line 16

def self.(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 },
    }),
  )

  if response.is_a?(Mangadex::Api::Response) && response.result == "error"
    if block_given?
      return yield(response)
    else
      return response
    end
  end

  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: "Bearer #{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

.logoutObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/mangadex/auth.rb', line 73

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_tokenObject



89
90
91
# File 'lib/mangadex/auth.rb', line 89

def self.refresh_token
  !(Mangadex.context.user&.refresh_session!).nil?
end