Class: GLogin::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/glogin/auth.rb

Overview

GitHub auth mechanism

Instance Method Summary collapse

Constructor Details

#initialize(id, secret, redirect) ⇒ Auth

Returns a new instance of Auth.



38
39
40
41
42
43
44
45
46
# File 'lib/glogin/auth.rb', line 38

def initialize(id, secret, redirect)
  raise "GitHub client ID can't be nil" if id.nil?
  @id = id
  raise "GitHub client secret can't be nil" if secret.nil?
  @secret = secret
  raise "Redirect URL can't be nil" if redirect.nil?
  raise "Redirect URL can't be empty" if redirect.empty?
  @redirect = redirect
end

Instance Method Details

#login_uriObject



48
49
50
# File 'lib/glogin/auth.rb', line 48

def 
  "https://github.com/login/oauth/authorize?client_id=#{CGI.escape(@id)}&redirect_uri=#{CGI.escape(@redirect)}"
end

#user(code) ⇒ Object

Returns a hash with information about Github user, who just logged in with the authentication code.

API: docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-the-authenticated-user



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/glogin/auth.rb', line 56

def user(code)
  if @secret.empty?
    return {
      'id' => 526_301,
      'login' => 'yegor256',
      'avatar_url' => 'https://github.com/yegor256.png'
    }
  end
  raise 'Code can\'t be nil' if code.nil?
  raise 'Code can\'t be empty' if code.empty?
  uri = URI.parse('https://api.github.com/user')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  req = Net::HTTP::Get.new(uri.request_uri)
  req['Accept-Header'] = 'application/json'
  token = access_token(code)
  req['Authorization'] = "token #{token}"
  res = http.request(req)
  raise "HTTP error ##{res.code} with token #{escape(token)}: #{res.body}" unless res.code == '200'
  JSON.parse(res.body)
end