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



60
61
62
# File 'lib/mangadex/auth.rb', line 60

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
# 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 },
    }),
  )

  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

.logoutObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/mangadex/auth.rb', line 65

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



81
82
83
# File 'lib/mangadex/auth.rb', line 81

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