Class: Mangadex::Auth

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

Class Method Summary collapse

Class Method Details

.check_tokenObject



43
44
45
46
47
48
49
50
# File 'lib/mangadex/auth.rb', line 43

def self.check_token
  JSON.parse(
    Mangadex::Internal::Request.get(
      '/auth/check',
      raw: true,
    )
  )
end

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



7
8
9
10
11
12
13
14
15
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
# File 'lib/mangadex/auth.rb', line 7

def self.(username: nil, email: nil, password: nil)
  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 = 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,
  )
  return if user.session_expired?

  Mangadex.context.user = user

  user.persist
  user
rescue Errors::UnauthorizedError => error
  raise Errors::AuthenticationError.new(error.response)
end

.logoutObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/mangadex/auth.rb', line 53

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



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

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