Skip to content

Instantly share code, notes, and snippets.

@abelorian
Created December 21, 2023 18:00
Show Gist options
  • Save abelorian/85a01010fcb9f9593f4fe9020b93a8d9 to your computer and use it in GitHub Desktop.
Save abelorian/85a01010fcb9f9593f4fe9020b93a8d9 to your computer and use it in GitHub Desktop.
Login con Google. Obtener el usuario con OAuth2
# Instalar gem 'google-apis-core'
require 'google/api_client/client_secrets'
class GoogleAuth
# url definida en console.google
REDIRECT_TO = "http://localhost:4002"
def client
# en otros ejemplos se leen estos datos directamente desde un json
data = {
"web": {
"client_id": 'XXXX.apps.googleusercontent.com',
"project_id": "abcd",
"client_secret": 'GXXXXXX',
"redirect_uris": [REDIRECT_TO]
}
}
client_secrets = Google::APIClient::ClientSecrets.new(data)
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => ['https://www.googleapis.com/auth/userinfo.email'],
:redirect_uri => (REDIRECT_TO),
:additional_parameters => {
"access_type" => "online"
}
)
auth_client
end
# obtener la url de login
def get_auth_url
client.authorization_uri.to_s
end
# luego del login, se retorna el codigo que se usa para conseguir el access_token
# code se puede usar solo 1 vez
def get_access_token(code)
p code
begin
auth_client = client
auth_client.code = code
p auth_client.fetch_access_token!
JSON.parse(auth_client.to_json)
rescue Exception => error
{ error: JSON.parse(error.response.body)["error"]} rescue { error: "invalid_code"}
end
end
# se obtiene la informacion del user usando el access_token
def get_user_info access_token
url = "https://oauth2.googleapis.com/tokeninfo?access_token=#{access_token}"
response = HTTP.get(url)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment