Why isn't Oauth setting email in tests? - ruby-on-rails

# spec/support/omniauth_helper.rb
module OmniauthMacros
def mock_auth_hash
OmniAuth.config.mock_auth[:github] = {
'provider' => 'github',
'uid' => '11',
'info' => {
'email' => 'gituser#github',
'name' => 'gituser',
'image' => 'mock_user_thumbnail_url'
},
'credentials' => {
'token' => 'mock_token',
'secret' => 'mock_secret'
}
}
end
end
This returns
ActiveRecord::RecordInvalid: Validation failed: Email can't be blank.
If I move this into Test environment config it starts working. Why is this happening?

Related

More readable, DRY class with jira issue creation

In my rails app I've got a base class - creator - which creates an issue in Jira board using jira-ruby gem. I want to use it in 15 different scenarios but the only thing that will be different are required fields such as summary, description, and issuetype. To avoid duplicates I use inheritance where in each case I've got a class with only one method - required_fields.
creator
module Jira
class Creator
def initialize(webhook)
#webhook = webhook
end
def call
issue = client.Issue.build
issue.save(ticket_class.new(webhook).required_fields)
end
private
def client
#client ||= Jira::JiraConnection.new.call
end
def ticket_class
#ticket_class ||= "Issues::#{webhook.action_type_class}".constantize"
end
def required_fields; end
end
end
Sample of class inheriting from Creator:
class NewRepo < Creator
def required_fields
{
'fields' => {
'summary' => 'Create new repo <github_repo> for <Github user>',
'description' => 'This is an automatic confirmation of creating new PRIVATE repo
- <github_repo> for <Github user>',
'project' => { 'key' => 'TEST' },
'issuetype' => { 'id' => '12580' },
'customfield_15100' => 'None'
}
}
end
end
This is required_fields is not so readable, how to create such an class where hash in required_fields will be look like:
{
'fields' => {
'summary' => new_repo,
'project' => testing_project,
'issuetype' => autoresolved,
'customfield_15100' => 'None'
}
}
How to put new_repo, testing_project etc (which will be a method probably?) inside of this hash? should I merge this somehow? Or maybe there is a better way to make this hash more readable?
Here are different scenarios for required fields which I want to use depends on webhook information:
class AddMember < Creator
def required_fields
{
'fields' => {
'summary' => 'Add <Github user> collaborator to <github_repo>',
'description' => 'This is an automatic ticket confirmation of user added',
'project' => { 'key' => 'New Board' },
'issuetype' => { 'id' => '12581' },
'customfield_15100' => 'None'
}
}
end
end
class DeleteRepo < Creator
def required_fields
{
'fields' => {
'summary' => 'Recheck <Github user> deleted <github_repo>',
'description' => 'This is an automatic ticket confirmation of delete repo <github_repo>',
'project' => { 'key' => 'Second Board' },
'issuetype' => { 'id' => '1234' },
'customfield_15100' => 'None'
}
}
end
end

How to use aws_account_utils to create an AWS account ? Getting error : cannot load such file -- aws_account_utils

I want to use AWSAccountUtils in my project to create AWS account. I have installed gem aws_account_utils too. What more do I need to do or what is that I am missing ? In my controller I have defined following function and code is :
def create_aws_account
require 'aws_account_utils'
#account_details = []
#account_values = {}
aws_utils = AwsAccountUtils::AwsAccountUtils.new()
details = { 'fullName' => 'Devanshu Kumar',
'company' => 'ABC',
'addressLine1' => 'CP, Bund Garden Road',
'city' => 'Pune',
'state' => 'Maharastra',
'postalCode' => '411007',
'phoneNumber' => '1234567890',
'guess' => 'Test Account Dev' }
resp = aws_utils.create_account(account_name: 'My Test Account Devanshu Kumar',
account_email: 'devanshu.kumar#abc.com',
account_password: 'password',
account_details: details)
#account_values = {:account_number => data_disk.resp}
#account_details.push #account_values
render :json => { created_aws_account: account_details }
end
AWS Account Details Error Image

How to resolve "Insufficient Permission" error in Google Calendar API for Ruby?

I'm trying to use Google Calendar API for Ruby and this is code that I took from the google console site. But when I tried to run this code, I got this error.
......rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/google-api-client-0.8.6/lib/google/api_client.rb:662:in `block (2 levels) in execute!': Insufficient Permission (Google::APIClient::ClientError)
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'fileutils'
APPLICATION_NAME = 'Calendar API Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"calendar-api-quickstart.json")
#SCOPE = 'https://www.googleapis.com/auth/calendar.readonly'
SCOPE = 'https://www.googleapis.com/auth/calendar'
def authorize
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)
storage = Google::APIClient::Storage.new(file_store)
auth = storage.authorize
if auth.nil? || (auth.expired? && auth.refresh_token.nil?)
app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)
flow = Google::APIClient::InstalledAppFlow.new({
:client_id => app_info.client_id,
# :redirect_uri => 'http://localhost:3000/auth/google_oauth2/callback',
:client_secret => app_info.client_secret,
:scope => SCOPE})
auth = flow.authorize(storage)
puts "Credentials saved to #{CREDENTIALS_PATH}" unless auth.nil?
end
auth
end
# Initialize the API
client = Google::APIClient.new(:application_name => APPLICATION_NAME)
calendar_api = client.discovered_api('calendar', 'v3')
client.authorization = authorize
=begin
# Fetch the next 10 events for the user
results = client.execute!(
:api_method => calendar_api.events.list,
:parameters => {
:calendarId => 'primary',
:maxResults => 10,
:singleEvents => true,
:orderBy => 'startTime',
:timeMin => Time.now.iso8601 })
puts "Upcoming events:"
puts "No upcoming events found" if results.data.items.empty?
results.data.items.each do |event|
start = event.start.date || event.start.date_time
puts "- #{event.summary} (#{start})"
puts "- #{event.updated} (#{start})"
# puts "- #{event.accessRole} (#{start})"
##여기에 뭔가 생기는군
end
=end
event = {
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => {
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
},
'end' => {
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
},
'recurrence' => [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees' => [
{'email' => 'lpage#example.com'},
{'email' => 'sbrin#example.com'},
],
'reminders' => {
'useDefault' => false,
'overrides' => [
{'method' => 'email', 'minutes' => 24 * 60},
{'method' => 'sms', 'minutes' => 10},
],
},
}
results = client.execute!(
:api_method => calendar_api.events.insert,
:parameters => {
:calendarId => 'primary'},
:body_object => event)
event = results.data
puts "Event created: #{event.htmlLink}"
I copied the functioning part from the console site here. How can I allow the permission to use Calendar application?
For the basic read-only app, I was able to run the application because I have Calendar application enabled in the console setting but don't know how to proceed the next step. Please let me know how to solve this issue :)
I was in trouble same to you. You should change two points below:
Your application name is aimed to draw quick sample data by API. It is suitable to set your own application name. The name is one you registered in Google developer console.
You should change credentials path to your own. The path you wrote is only for quick start sample.
{File.join(Dir.home, '.credentials',"calendar-api-quickstart.json"")} >>>
{File.join(Dir.home, '.credentials',"client_secret.json")}

New calendar event, created using Google service account isn't sending invitaion email to the attendees

I am creating a new event in Google Calendar by using Google's service account, and I have also set sendNotifications to true, but after creating an event, invitation emails are not sending to the attendees ??
# new event to be created
event = {
'summary'=> summary,
'description'=> description,
'start'=> {'dateTime' => datetime },
'end' => {'dateTime' => datetime },
'sendNotifications' => true,
'sequence' => sequence,
'reminders' => {
'useDefault' => false,
'overrides' => [
{'minutes' => 60, 'method' => 'email'}
]
},
'attendees'=> [
{
'email'=> email
}
]
}
# build client
client = Google::APIClient.new application_name: "Test", application_version: "0.0.1"
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/calendar',
:issuer => ENV['SERVICE_ACCOUNT_EMAIL'],
:grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
:access_type => 'offline',
:signing_key => key
)
# fetch access token
client.authorization.fetch_access_token!
# create new event
service = client.discovered_api('calendar', 'v3')
client.execute(:api_method => service.acl.insert,
:parameters => {'calendarId' => 'primary'},
:body => JSON.dump(event),
:headers => {'Content-Type' => 'application/json'})
sendNotifications is a property of the request, not of an event. See the documentation of an insert here: https://developers.google.com/google-apps/calendar/v3/reference/events/insert You can also try the explorer to see how exactly requests should look like: https://developers.google.com/apis-explorer/#p/calendar/v3/ (don't forget to authenticate in the top right corner).

Testing OAuth with Capybara/Rspec for Facebook

I'm writing a test for Facebook integration. When I run rspec, I get the following error
Failure/Error: before { click_link "Sign in with Facebook" }
NoMethodError:
undefined method `provider' for #<Hash:0x007fbe98511798>
# ./app/models/user.rb:55:in `from_omniauth'
My OAuth mock contains
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = {
'uid' => "999999",
'provider' => "facebook",
'extra' => {
'user_hash' => {
'email' => 'test#gmail.com',
'first_name' => 'First',
'last_name' => 'Last',
'gender' => 'Male'
}
},
'credentials' => {
'token' => "token1234qwert"
}
}
The exact place it apparently breaks is
def self.from_omniauth(auth)
where("fb_provider = ? and fb_uid = ?", auth.provider, auth.uid.to_s).first_or_initialize.tap do |user|
But when I do a puts auth.to_yaml as the first line in from_omniauth(auth) it shows provider: facebook along with everything else I included in my mock auth. I'm lost at this point. Any suggestions or help would be appreciated. Thanks.
Your code should be this:
where("fb_provider = ? and fb_uid = ?", auth['provider'], auth['uid'].to_s ...
This is because auth in this instance is a Hash object and Hash objects do not respond to methods by the same name as their keys. Instead, you should just use the Hash#[] method -- as I've demonstrated -- to access the value for those keys.

Resources