repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
ack43/rocket_cms
|
lib/rocket_cms/patch.rb
|
module RocketCMS
class PatchDSL
def self.call(&blk)
instance = new
instance.instance_eval(&blk)
instance.instance_variables.inject({}) { |result_hash, instance_variable|
result_hash[instance_variable[1..-1].to_sym] = instance.instance_variable_get(instance_variable)
result_hash
}
end
def initialize
@model = Proc.new {}
@admin = Proc.new {}
@list = Proc.new {}
@show = Proc.new {}
@edit = Proc.new {}
@export = Proc.new {}
end
def model(&blk); @model = blk; end
def admin(&blk); @admin = blk; end
def list(&blk); @list = blk; end
def show(&blk); @show = blk; end
def edit(&blk); @edit = blk; end
def export(&blk); @export = blk; end
end
@@patches = {}
def self.only_patches(s, sections)
s.instance_eval do
sections.each do |section|
send section do
RocketCMS.apply_patches self
end
end
end
end
def self.apply_patches(s)
if s.class.name.index('RailsAdmin::Config::Sections::').nil?
if s.class.name == 'RailsAdmin::Config::Model'
s.instance_eval(&@@patches[s.abstract_model.model_name][:admin]) unless @@patches[s.abstract_model.model_name].nil?
else
s.instance_eval(&@@patches[s.name][:model]) unless @@patches[s.name].nil?
end
else
model = s.abstract_model.model_name
action = s.class.name.split('::')[-1].downcase.to_sym
s.instance_eval(&@@patches[model][action]) unless @@patches[model].nil?
end
end
def self.patch(model, &blk)
@@patches[model] = PatchDSL.call(&blk)
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/mongoid/menu.rb
|
<reponame>ack43/rocket_cms
module RocketCMS
module Models
module Mongoid
module Menu
extend ActiveSupport::Concern
included do
field :name, type: String, default: ""
end
end
end
end
end
|
ack43/rocket_cms
|
app/models/gallery_image.rb
|
if RocketCMS.mongoid?
class GalleryImage
include RocketCMS::Models::GalleryImage
RocketCMS.apply_patches self
rails_admin &RocketCMS.image_config
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/active_record/menu.rb
|
module RocketCMS
module Models
module ActiveRecord
module Menu
extend ActiveSupport::Concern
included do
has_paper_trail
validates_lengths_from_database
if RocketCMS.config.localize
translates :name
end
end
end
end
end
end
|
ack43/rocket_cms
|
app/models/concerns/geocodeable.rb
|
module Geocodeable
extend ActiveSupport::Concern
include Mappable
end
|
ack43/rocket_cms
|
lib/rocket_cms/controllers/search.rb
|
module RocketCMS
module Controllers
module Search
extend ActiveSupport::Concern
# def index
# if params[:query].blank?
# @results = []
# else
# @results = Mongoid::Elasticsearch.search({
# body: {
# query: {
# query_string: {
# query: Mongoid::Elasticsearch::Utils.clean(params[:query])
# }
# },
# highlight: {
# fields: {
# name: {},
# content: {}
# }
# }
# }},
# page: params[:page],
# per_page: RocketCMS.configuration.search_per_page,
# )
# end
# end
def index
if params[:q].blank?
@results = []
else
query = params[:q].to_s.gsub(/\P{Word}+/, ' ').gsub(/ +/, ' ').strip
@results = Page.search(query,
per_page: 10,
highlight: true,
suggest: true,
page: params[:page],
per_page: RocketCMS.configuration.search_per_page
)
# @results = Mongoid::Elasticsearch.search({
# body: {
# query: {
# query_string: {
# query: Mongoid::Elasticsearch::Utils.clean(params[:query])
# }
# },
# highlight: {
# fields: {
# name: {},
# content: {}
# }
# }
# }},
# page: params[:page],
# per_page: RocketCMS.config.search_per_page,
# )
end
end
end
end
end
|
ack43/rocket_cms
|
app/models/concerns/enableable.rb
|
module Enableable
extend ActiveSupport::Concern
include BooleanField
included do
boolean_field(:enabled)
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/mongoid/news.rb
|
module RocketCMS
module Models
module Mongoid
module News
extend ActiveSupport::Concern
unless RocketCMS.config.news_image_styles.nil?
include ::Mongoid::Paperclip
end
included do
field :time, type: Time
index({enabled: 1, time: 1})
unless RocketCMS.config.news_image_styles.nil?
has_mongoid_attached_file :image, styles: RocketCMS.config.news_image_styles
def image_file_name=(val)
return self[:image_file_name] = "" if val == ""
return self[:image_file_name] = nil if val == nil
val = val.to_s
extension = File.extname(val)[1..-1]
file_name = val[0..val.size-extension.size-1]
self[:image_file_name] = "#{file_name.filename_to_slug}.#{extension.filename_to_slug}"
end
end
field :excerpt, type: String, localize: RocketCMS.configuration.localize, default: ""
field :content, type: String, localize: RocketCMS.configuration.localize, default: ""
scope :after_now, -> { where(:time.lt => Time.now) }
scope :by_date, -> { desc(:time) }
end
end
end
end
end
|
ack43/rocket_cms
|
mongoid/rocket_cms_mongoid.gemspec
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
lib = File.expand_path('../../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rocket_cms/version'
Gem::Specification.new do |spec|
spec.name = 'ack_rocket_cms_mongoid'
spec.version = RocketCMS::VERSION
spec.authors = ['<NAME>', 'glebtv']
spec.email = ["<EMAIL>", '<EMAIL>']
spec.description = %q{AckRocketCMS - RocketCMS fork - Mongoid metapackage}
spec.summary = %q{}
spec.homepage = 'https://github.com/ack43/rocket_cms'
spec.license = 'MIT'
spec.files = %w(lib/ack_rocket_cms_mongoid.rb lib/rocket_cms_mongoid.rb)
spec.executables = []
spec.test_files = []
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_dependency 'mongoid', ['>= 4.0.0', '< 6.0']
spec.add_dependency 'ack_rocket_cms', RocketCMS::VERSION
spec.add_dependency 'glebtv-mongoid_nested_set'
spec.add_dependency 'glebtv-mongoid-paperclip'
spec.add_dependency 'mongoid-audit', '~> 1.1.0'
spec.add_dependency 'mongoid_slug'
spec.add_dependency 'mongo_session_store-rails4'
spec.add_dependency 'rails_admin_settings', '~> 0.9.0'
end
|
ack43/rocket_cms
|
activerecord/lib/rocket_cms_activerecord.rb
|
<filename>activerecord/lib/rocket_cms_activerecord.rb
require 'awesome_nested_set'
require 'paperclip'
require 'paper_trail'
require 'friendly_id'
require 'validates_lengths_from_database'
require 'pg_search'
module RocketCMS
def self.orm
:active_record
end
end
require 'rocket_cms'
|
ack43/rocket_cms
|
app/models/news.rb
|
if RocketCMS.active_record?
class News < ActiveRecord::Base
end
end
class News
include RocketCMS::Models::News
RocketCMS.apply_patches self
rails_admin &RocketCMS.news_config
end
|
ack43/rocket_cms
|
template.rb
|
rails_spec = (Gem.loaded_specs["railties"] || Gem.loaded_specs["rails"])
version = rails_spec.version.to_s
mongoid = options[:skip_active_record]
if Gem::Version.new(version) < Gem::Version.new('4.2.4')
puts "You are using an old version of Rails (#{version})"
puts "Please update"
puts "Stopping"
exit 1
end
remove_file 'Gemfile'
create_file 'Gemfile' do <<-TEXT
source 'https://rubygems.org'
gem 'rails', '4.2.4'
#{if mongoid then "gem 'mongoid', '~> 4.0.0'" else "gem 'pg'" end}
# gem 'sass'
gem 'compass'
#{if mongoid then "gem 'ack_rocket_cms_mongoid'" else "gem 'ack_rocket_cms_activerecord'" end}, '~> 0.8.0'
gem 'devise'
gem 'sass-rails', '~> 5.0'
gem 'compass-rails', '~> 2.0.4'
gem 'slim-rails'
gem 'rs_russian'
gem 'cancancan'
gem 'cloner'
gem 'unicorn'
gem 'x-real-ip'
gem 'sentry-raven'
group :development do
gem 'better_errors'
gem 'binding_of_caller'
gem 'pry-rails'
gem 'spring'
gem 'capistrano', '~> 3.4.0', require: false
gem 'rvm1-capistrano3', require: false
gem 'glebtv-capistrano-unicorn', require: false
gem 'capistrano-bundler', require: false
gem 'capistrano-rails', require: false
gem 'hipchat'
# gem 'coffee-rails-source-maps'
# gem 'compass-rails-source-maps'
gem 'favicon_maker', '0.3'
gem 'favicon_maker_rails'
gem 'rails_email_preview', '~> 0.2.29'
end
group :test do
gem 'rspec-rails'
gem 'database_cleaner'
gem 'email_spec'
#{if mongoid then "gem 'mongoid-rspec'" else "" end}
gem 'ffaker'
gem 'factory_girl_rails'
end
#{if mongoid then "gem 'mongo_session_store-rails4'" else "" end}
gem 'slim'
gem 'sprockets'
gem 'sitemap_generator'
gem 'rails_admin_sitemap'
gem 'uglifier'
group :production do
gem "god"
end
TEXT
end
remove_file '.gitignore'
create_file '.gitignore' do <<-TEXT
# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
# git config --global core.excludesfile '~/.gitignore_global'
.idea
.idea/*
/.bundle
/log/*.log
/tmp/*
/public/assets
/public/ckeditor_assets
TEXT
end
create_file 'extra/.gitkeep', ''
if mongoid
remove_file 'config/initializers/embedded_findable.rb'
create_file 'config/initializers/embedded_findable.rb' do <<-TEXT
module Mongoid
# Helps to override find method in an embedded document.
# Usage :
# - add to your model "include Mongoid::EmbeddedFindable"
# - override find method with:
# def self.find(id)
# find_through(Book, 'chapter', id)
# end
module EmbeddedFindable
extend ActiveSupport::Concern
included do
# Search an embedded document by id.
#
# Document is stored within embedding_class collection, and can be accessed through provided relation.
# Also supports chained relationships (if the searched document is nested in several embedded documents)
#
# Example, with a chapter embedded in a book, the book being embedded in a library.
# use find_through(Library, "books", book_id) in Book class
# and find_through(Library, "books.chapters", chapter_id) in Chapter class
def self.find_through(embedding_class, relation, id = nil)
return nil if id.nil? || id.blank?
id = BSON::ObjectId.from_string(id) if id.is_a?(String)
relation = relation.to_s unless relation.is_a?(String)
relation_parts = relation.split('.')
parent = embedding_class.send(:all)
while relation_parts.length > 0
item = if parent.is_a?(Mongoid::Criteria) || parent.is_a?(Array)
parent.where("\#{relation_parts.join('.')}._id" => id).first
else
parent
end
return nil if item.nil?
parent = item.send(relation_parts.shift)
end
if parent.is_a?(Mongoid::Criteria) || parent.is_a?(Array)
parent.where('_id' => id).first
else
parent
end
end
end
end
end
TEXT
end
end
if mongoid
remove_file 'config/initializers/cookies_serializer.rb'
create_file 'config/initializers/cookies_serializer.rb' do <<-TEXT
# Be sure to restart your server when you modify this file.
# json serializer breaks Devise + Mongoid. DO NOT ENABLE
# See https://github.com/plataformatec/devise/pull/2882
# Rails.application.config.action_dispatch.cookies_serializer = :json
Rails.application.config.action_dispatch.cookies_serializer = :marshal
TEXT
end
end
if mongoid
remove_file 'config/initializers/session_store.rb'
create_file 'config/initializers/session_store.rb' do <<-TEXT
# Be sure to restart your server when you modify this file.
#Rails.application.config.session_store :cookie_store, key: '_#{app_name.tableize.singularize}_session'
Rails.application.config.session_store :mongoid_store
TEXT
end
end
remove_file 'app/controllers/application_controller.rb'
create_file 'app/controllers/application_controller.rb' do <<-TEXT
class ApplicationController < ActionController::Base
include RocketCMS::Controller
end
TEXT
end
create_file 'config/navigation.rb' do <<-TEXT
# empty file to please simple_navigation, we are not using it
# See https://github.com/ack43/rocket_cms/blob/master/app/controllers/concerns/rs_menu.rb
TEXT
end
create_file 'README.md', "## #{app_name}\nProject generated by RocketCMS\nORM: #{if mongoid then 'Mongoid' else 'ActiveRecord' end}\n\n"
create_file '.ruby-version', "2.2.3\n"
create_file '.ruby-gemset', "#{app_name}\n"
run 'bundle install --without production'
# generate 'rails_email_preview:install'
remove_file 'app/mailer_previews/contact_mailer_preview.rb'
create_file 'app/mailer_previews/contact_mailer_preview.rb' do <<-TEXT
class ContactMailerPreview
def new_message_email
ContactMailer.new_message_email(ContactMessage.all.to_a.sample)
end
end
TEXT
end
if mongoid
create_file 'config/mongoid.yml' do <<-TEXT
development:
sessions:
default:
database: #{app_name.downcase}
hosts:
- localhost:27017
production:
sessions:
default:
database: #{app_name.downcase}
hosts:
- localhost:27017
test:
sessions:
default:
database: #{app_name.downcase}_test
hosts:
- localhost:27017
TEXT
end
else
remove_file 'config/database.yml'
create_file 'config/database.yml' do <<-TEXT
development:
adapter: postgresql
encoding: unicode
database: #{app_name.downcase}_development
pool: 5
username: #{app_name.downcase}
password: #{<PASSWORD>}
template: template0
TEXT
end
say "Please create a PostgreSQL user #{app_name.downcase} with password #{app_name.downcase} and a database #{app_name.downcase}_development owned by him for development NOW.", :red
ask("Press <enter> when done.", true)
end
unless mongoid
generate 'simple_captcha'
end
generate "devise:install"
generate "devise", "User"
remove_file "config/locales/devise.en.yml"
remove_file "config/locales/en.yml"
gsub_file 'app/models/user.rb', '# :confirmable, :lockable, :timeoutable and :omniauthable', '# :confirmable, :registerable, :timeoutable and :omniauthable'
gsub_file 'app/models/user.rb', ':registerable,', ' :lockable,'
if mongoid
gsub_file 'app/models/user.rb', '# field :failed_attempts', 'field :failed_attempts'
gsub_file 'app/models/user.rb', '# field :unlock_token', 'field :unlock_token'
gsub_file 'app/models/user.rb', '# field :locked_at', 'field :locked_at'
inject_into_file 'app/models/user.rb', before: /^end/ do <<-TEXT
field :name, type: String
field :login, type: String
field :roles, type: Array, default: []
before_save do
self.roles ||= []
self.roles.reject! { |r| r.blank? }
end
AVAILABLE_ROLES = ["admin", "manager", "client"]
AVAILABLE_ROLES.each do |r|
class_eval <<-EVAL
def \#{r}?
self.roles and self.roles.include?("\#{r}")
end
scope :\#{r.pluralize}, -> { any_in(roles: "\#{r}") }
EVAL
end
rails_admin do
list do
field :email
field :name
field :login
field :roles do
pretty_value do
bindings[:view].content_tag(:p, bindings[:object].roles.join(", "))
end
end
end
edit do
field :email, :string do
visible do
bindings[:controller].current_user.admin? or (bindings[:controller].current_user.manager? bindings[:controller].current_user == bindings[:object])
end
end
field :name, :string
field :login, :string do
visible do
bindings[:controller].current_user.admin?
end
end
field :roles, :enum do
enum do
AVAILABLE_ROLES
end
multiple do
true
end
visible do
bindings[:controller].current_user.admin?
end
end
field :password do
visible do
bindings[:controller].current_user.admin? or bindings[:controller].current_user == bindings[:object]
end
end
field :password_confirmation do
visible do
bindings[:controller].current_user.admin? or bindings[:controller].current_user == bindings[:object]
end
end
end
end
TEXT
end
end
if mongoid
generate "ckeditor:install", "--orm=mongoid", "--backend=paperclip"
else
generate "ckeditor:install", "--orm=active_record", "--backend=paperclip"
end
unless mongoid
generate "rocket_cms:migration"
generate "rails_admin_settings:migration"
end
generate "rocket_cms:admin"
generate "rocket_cms:ability"
generate "rocket_cms:layout"
unless mongoid
rake "db:migrate"
end
generate "simple_form:install"
generate "rspec:install"
remove_file 'config/routes.rb'
create_file 'config/routes.rb' do <<-TEXT
Rails.application.routes.draw do
devise_for :users
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
mount Ckeditor::Engine => '/ckeditor'
get 'contacts' => 'contacts#new', as: :contacts
post 'contacts' => 'contacts#create', as: :create_contacts
get 'contacts/sent' => 'contacts#sent', as: :contacts_sent
get 'search' => 'search#index', as: :search
resources :news, only: [:index, :show]
root to: 'home#index'
get '*slug' => 'pages#show'
resources :pages, only: [:show]
end
TEXT
end
create_file 'config/locales/ru.yml' do <<-TEXT
ru:
attributes:
is_default: По умолчанию
mongoid:
models:
item: Товар
attributes:
item:
price: Цена
TEXT
end
remove_file 'db/seeds.rb'
require 'securerandom'
admin_pw = SecureRandom.urlsafe_base64(6)
create_file 'db/seeds.rb' do <<-TEXT
admin_pw = "#{admin_pw}"
User.destroy_all
User.create!(email: '<EMAIL>', password: <PASSWORD>, password_confirmation: <PASSWORD>, roles: ["admin"])
TEXT
end
create_file 'config/initializers/rack.rb' do <<-TEXT
if Rails.env.development?
module Rack
class CommonLogger
alias_method :log_without_assets, :log
#{'ASSETS_PREFIX = "/#{Rails.application.config.assets.prefix[/\A\/?(.*?)\/?\z/, 1]}/"'}
def log(env, status, header, began_at)
unless env['REQUEST_PATH'].start_with?(ASSETS_PREFIX) || env['REQUEST_PATH'].start_with?('/uploads') || env['REQUEST_PATH'].start_with?('/system')
log_without_assets(env, status, header, began_at)
end
end
end
end
end
Rack::Utils.multipart_part_limit = 0
TEXT
end
create_file 'app/assets/stylesheets/rails_admin/custom/theming.sass' do <<-TEXT
.navbar-brand
margin-left: 0 !important
.input-small
width: 150px
.container-fluid
input[type=text]
width: 380px !important
input.ra-filtering-select-input[type=text]
width: 180px !important
input.hasDatepicker
width: 180px !important
.sidebar-nav
a
padding: 6px 10px !important
.dropdown-header
padding: 10px 0px 3px 9px
.label-important
background-color: #d9534f
.alert-notice
color: #5bc0de
.page-header
display: none
.breadcrumb
margin-top: 20px
.control-group
clear: both
.container-fluid
padding-left: 0
> .row
margin: 0
.last.links
a
display: inline-block
padding: 3px
font-size: 20px
.remove_nested_fields
opacity: 1 !important
body.rails_admin .modal
margin: 0 auto !important
.modal-dialog
width: 990px !important
input[type=checkbox]
width: 30px !important
body.rails_admin
.root_links
> li
display: inline-block
.dropdown-header
border-top: 2px solid #777777
text-align: right
&:first-child
border-top: none
.bank_row .logo_field, #edit_bank img
background: #ccc !important
.ui-menu-item
border: 1px solid transparent
.content > .alert
margin-top: 20px
.badge-important
background: red
.badge-success
background: green
.sidebar-nav i
margin-right: 5px
body.rails_admin .table td.paperclip_type, body.rails_admin .table td.carrierwave_type, body.rails_admin .table td.jcrop_type
img
max-width: 150px
max-height: 100px
TEXT
end
remove_file 'public/robots.txt'
create_file 'public/robots.txt' do <<-TEXT
User-Agent: *
Allow: /
Disallow: /admin
Sitemap: /sitemap.xml.gz
TEXT
end
remove_file 'app/views/layouts/application.html.erb'
gsub_file 'app/views/layouts/application.html.slim', "= favicon_link_tag '/favicon.ico'", "= render partial: 'blocks/favicon' #= favicon_link_tag '/favicon.ico'"
remove_file 'config/application.rb'
create_file 'config/application.rb' do <<-TEXT
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_model/railtie"
#{'#' if mongoid}require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module #{app_name.camelize}
class Application < Rails::Application
config.generators do |g|
g.test_framework :rspec
g.view_specs false
g.helper_specs false
g.feature_specs false
g.template_engine :slim
g.stylesheets false
g.javascripts false
g.helper false
g.fixture_replacement :factory_girl, :dir => 'spec/factories'
end
config.i18n.locale = :ru
config.i18n.default_locale = :ru
config.i18n.available_locales = [:ru, :en]
config.i18n.enforce_available_locales = true
#{'config.active_record.schema_format = :sql' unless mongoid}
#{'config.autoload_paths += %W(#{config.root}/extra)'}
#{'config.eager_load_paths += %W(#{config.root}/extra)'}
config.time_zone = 'Europe/Moscow'
config.assets.paths << Rails.root.join("app", "assets", "fonts")
end
end
TEXT
end
remove_file 'app/assets/stylesheets/application.css'
remove_file 'app/assets/stylesheets/application.css.sass'
create_file 'app/assets/stylesheets/application.sass' do <<-TEXT
@import 'compass'
@import 'rocket_cms'
#wrapper
width: 960px
margin: 0 auto
#sidebar
float: left
width: 200px
#content
float: right
width: 750px
@import "compass/layout/sticky-footer"
+sticky-footer(50px)
TEXT
end
remove_file 'app/assets/javascripts/application.js'
remove_file 'app/assets/javascripts/application.js.coffee'
create_file 'app/assets/javascripts/application.coffee' do <<-TEXT
#= require rocket_cms
TEXT
end
#god+unicorn
remove_file 'config/unicorn.rb'
create_file 'config/unicorn.rb' do <<-TEXT
worker_processes 2
working_directory "/home/ack/www/#{app_name.downcase}"
# This loads the application in the master process before forking
# worker processes
# Read more about it here:
# http://unicorn.bogomips.org/Unicorn/Configurator.html
preload_app true
timeout 30
# This is where we specify the socket.
# We will point the upstream Nginx module to this socket later on
listen "/home/ack/www/#{app_name.downcase}/tmp/sockets/unicorn.sock", :backlog => 64
pid "/home/ack/www/qiwi_middleware/tmp/pids/unicorn.pid"
# Set the path of the log files inside the log folder of the testapp
stderr_path "/home/ack/www/#{app_name.downcase}/log/unicorn.stderr.log"
stdout_path "/home/ack/www/#{app_name.downcase}/log/unicorn.stdout.log"
before_fork do |server, worker|
server.logger.info("worker=#{worker.nr} spawning in #{Dir.pwd}")
# graceful shutdown.
old_pid_file = "/home/ack/www/#{app_name.downcase}/tmp/pids/unicorn.pid.oldbin"
if File.exists?(old_pid_file) && server.pid != old_pid_file
begin
old_pid = File.read(old_pid_file).to_i
server.logger.info("sending QUIT to #{old_pid}")
# we're killing old unicorn master right there
Process.kill("QUIT", old_pid)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
## no need for noSQL
# before_fork do |server, worker|
# # This option works in together with preload_app true setting
# # What is does is prevent the master process from holding
# # the database connection
# defined?(ActiveRecord::Base) and
# ActiveRecord::Base.connection.disconnect!
# end
#
# after_fork do |server, worker|
# # Here we are establishing the connection after forking worker
# # processes
# defined?(ActiveRecord::Base) and
# ActiveRecord::Base.establish_connection
# end
TEXT
end
remove_file 'config/unicorn.god'
create_file 'config/unicorn.god' do <<-TEXT
# http://unicorn.bogomips.org/SIGNALS.html
rails_env = ENV['RAILS_ENV'] || 'production'
rails_root = ENV['RAILS_ROOT'] || File.dirname(File.dirname(__FILE__))
God.watch do |w|
w.name = "unicorn_qiwi_middleware"
w.interval = 30.seconds # default
# unicorn needs to be run from the rails root
w.start = "cd #{rails_root} && unicorn -c #{rails_root}/config/unicorn.rb -E #{rails_env} -D"
# QUIT gracefully shuts down workers
w.stop = "kill -KILL `cat #{rails_root}/tmp/pids/unicorn.pid`"
# USR2 causes the master to re-create itself and spawn a new worker pool
w.restart = "kill -USR2 `cat #{rails_root}/tmp/pids/unicorn.pid`"# && cd #{rails_root} && unicorn -c #{rails_root}/config/unicorn.rb -E #{rails_env} -D"
w.start_grace = 10.seconds
w.restart_grace = 10.seconds
w.pid_file = "#{rails_root}/tmp/pids/unicorn.pid"
w.uid = 'ack'
w.gid = 'ack'
w.behavior(:clean_pid_file)
w.start_if do |start|
start.condition(:process_running) do |c|
c.interval = 5.seconds
c.running = false
end
end
w.restart_if do |restart|
restart.condition(:memory_usage) do |c|
c.above = 150.megabytes
c.times = [3, 5] # 3 out of 5 intervals
end
restart.condition(:cpu_usage) do |c|
c.above = 40.percent
c.times = 5
end
end
# lifecycle
w.lifecycle do |on|
on.condition(:flapping) do |c|
c.to_state = [:start, :restart]
c.times = 5
c.within = 5.minute
c.transition = :unmonitored
c.retry_in = 10.minutes
c.retry_times = 5
c.retry_within = 2.hours
end
end
end
TEXT
end
#scripts
remove_file 'scripts/assets_precompile.sh'
create_file 'scripts/assets_precompile.sh' do <<-TEXT
#!/bin/sh
RAILS_ENV=production rake assets:precompile
TEXT
end
remove_file 'scripts/bundle_production.sh'
create_file 'scripts/bundle_production.sh' do <<-TEXT
#!/bin/sh
rm Gemfile.lock
bundle install --without development test
TEXT
end
remove_file 'scripts/full_assets_precompile.sh'
create_file 'scripts/full_assets_precompile.sh' do <<-TEXT
#!/bin/sh
RAILS_ENV=production rake assets:precompile
TEXT
end
remove_file 'scripts/restart_thru_kill.sh'
create_file 'scripts/restart_thru_kill.sh' do <<-TEXT
#!/bin/sh
kill $(cat ./tmp/pids/unicorn.pid)
TEXT
end
remove_file 'scripts/send_usr2.sh'
create_file 'scripts/send_usr2.sh' do <<-TEXT
#!/bin/sh
kill -USR2 $(cat ./tmp/pids/unicorn.pid)
TEXT
end
remove_file 'scripts/send_hup.sh'
create_file 'scripts/send_hup.sh' do <<-TEXT
#!/bin/sh
kill -HUP $(cat ./tmp/pids/unicorn.pid)
TEXT
end
inject_into_file 'config/initializers/assets.rb', before: /\z/ do <<-TEXT
Rails.application.config.assets.precompile += %w( ckeditor/* )
TEXT
end
if mongoid
FileUtils.cp(Pathname.new(destination_root).join('config', 'mongoid.yml').to_s, Pathname.new(destination_root).join('config', 'mongoid.yml.example').to_s)
else
FileUtils.cp(Pathname.new(destination_root).join('config', 'database.yml').to_s, Pathname.new(destination_root).join('config', 'database.yml.example').to_s)
end
FileUtils.cp(Pathname.new(destination_root).join('config', 'secrets.yml').to_s, Pathname.new(destination_root).join('config', 'secrets.yml.example').to_s)
unless mongoid
generate "paper_trail:install"
generate "friendly_id"
rake "db:migrate"
end
git :init
git add: "."
git commit: %Q{ -m 'Initial commit' }
|
ack43/rocket_cms
|
app/models/contact_message.rb
|
if RocketCMS.active_record?
class ContactMessage < ActiveRecord::Base
end
end
class ContactMessage
include RocketCMS::Models::ContactMessage
RocketCMS.apply_patches self
rails_admin &RocketCMS.contact_message_config
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/mongoid/page.rb
|
module RocketCMS
module Models
module Mongoid
module Page
extend ActiveSupport::Concern
included do
field :regexp, type: String, default: ""
field :redirect, type: String, default: ""
field :excerpt, type: String, localize: RocketCMS.config.localize, default: ""
field :content, type: String, localize: RocketCMS.config.localize, default: ""
field :fullpath, type: String, default: ""
has_and_belongs_to_many :menus, inverse_of: :pages
acts_as_nested_set
manual_slug :name
scope :sorted, -> { order_by([:lft, :asc]) }
scope :menu, ->(menu_id) { enabled.sorted.where(menu_ids: menu_id) }
def page_h1
_ret = h1
_ret = name if _ret.blank?
_ret = title if _ret.blank?
_ret
end
end
end
end
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/migration.rb
|
<gh_stars>0
module RocketCMS
module Migration
extend self
def seo_fields(t)
if RocketCMS.config.localize
t.column :h1_translations, 'hstore', default: {}
t.column :title_translations, 'hstore', default: {}
t.column :keywords_translations, 'hstore', default: {}
t.column :description_translations, 'hstore', default: {}
t.column :og_title_translations, 'hstore', default: {}
else
t.string :h1
t.string :title
t.text :keywords
t.text :description
t.string :og_title
end
t.string :robots
t.attachment :og_image
end
def map_fields(t)
t.text :address
t.text :map_address
t.text :map_hint
t.float :latitude
t.float :longitude
t.float :lat
t.float :lon
end
end
end
|
ack43/rocket_cms
|
app/models/seo.rb
|
if RocketCMS.active_record?
class Seo < ActiveRecord::Base
end
end
class Seo
include RocketCMS::Models::Seo
RocketCMS.apply_patches self
rails_admin &RocketCMS.seo_config
belongs_to :seoable, polymorphic: true
def self.separate_table?
(RocketCMS.mongoid? && RocketCMS.config.separate_seo_table) || (RocketCMS.active_record? && Seo.table_exists?)
end
end
|
ack43/rocket_cms
|
app/controllers/news_controller.rb
|
<gh_stars>10-100
class NewsController < ApplicationController
include RocketCMS::Controllers::News
end
|
ack43/rocket_cms
|
app/models/page.rb
|
if RocketCMS.active_record?
class Page < ActiveRecord::Base
end
end
class Page
include RocketCMS::Models::Page
RocketCMS.apply_patches self
rails_admin &RocketCMS.page_config
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/embedded_gallery_image.rb
|
<gh_stars>0
module RocketCMS
module Models
module EmbeddedGalleryImage
extend ActiveSupport::Concern
include RocketCMS::Model
include Enableable
include Sortable
include RocketCMS.orm_specific('EmbeddedGalleryImage')
included do
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/, if: :image?
end
end
end
end
|
ack43/rocket_cms
|
app/mailers/contact_mailer.rb
|
<reponame>ack43/rocket_cms<gh_stars>0
class ContactMailer < ActionMailer::Base
def new_message_email(message)
@message = message
#if message.attachment?
# attachments[message.attachment.identifier] = File.read(message.attachment.current_path)
#end
mail(
from: Settings.default_email_from(default: '<EMAIL>'),
to: Settings.form_email(default: '<EMAIL>'),
subject: "[#{Settings.email_topic(default: 'с сайта')}] #{message.name} #{message.email}"
)
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/admin.rb
|
module RocketCMS
class << self
def map_config(is_active = true)
Proc.new {
active is_active
label I18n.t('rs.map')
field :address, :string
field :map_address, :string
field :map_hint, :string
field :coordinates, :string do
read_only true
formatted_value{ bindings[:object].coordinates.to_json }
end
field :lat
field :lon
if block_given?
yield
end
}
end
def seo_config(is_active = true)
Proc.new {
if respond_to?(:active)
active is_active
label "SEO"
else
visible false
end
RocketCMS.seo_fields(self)
}
end
def seo_fields(s)
s.instance_eval do
field :h1, :string
field :title, :string
field :keywords, :text
field :description, :text
field :robots, :string
field :og_title, :string
field :og_image, :jcrop do
jcrop_options :og_image_jcrop_options
end
if block_given?
yield
end
end
end
def page_config(fields = {})
Proc.new {
RocketCMS.apply_patches self
navigation_label I18n.t('rs.cms')
list do
scopes [:sorted, :enabled, nil]
field :enabled, :toggle
field :menus, :menu
field :name
field :fullpath do
pretty_value do
bindings[:view].content_tag(:a, bindings[:object].fullpath, href: bindings[:object].fullpath)
end
end
field :redirect
field :slug
RocketCMS.apply_patches self
end
edit do
field :name
field :excerpt, :ck_editor
field :content, :ck_editor
RocketCMS.apply_patches self
group :menu do
label I18n.t('rs.menu')
field :menus
field :fullpath, :string do
help I18n.t('rs.with_final_slash')
end
field :regexp, :string do
help I18n.t('rs.page_url_regex')
end
field :redirect, :string do
help I18n.t('rs.final_in_menu')
end
field :text_slug
end
fields.each_pair do |name, type|
if type.nil?
field name
else
if type.is_a?(Array)
field name, type[0], &type[1]
else
field name, type
end
end
end
if Seo.separate_table?
group :seo do
active true
field :seo do
active true
end
end
else
group :seo, &RocketCMS.seo_config(true)
end
group :sitemap_data, &RocketCMS.sitemap_data_config
end
RocketCMS.only_patches self, [:show, :export]
nested_set({
max_depth: RocketCMS.config.menu_max_depth,
scopes: []
})
if block_given?
yield
end
}
end
def menu_config
Proc.new {
navigation_label 'CMS'
field :enabled, :toggle
field :text_slug
field :name
RocketCMS.apply_patches self
RocketCMS.only_patches self, [:show, :list, :edit, :export]
if block_given?
yield
end
}
end
def contact_message_config
Proc.new {
navigation_label I18n.t('rs.settings')
field :c_at do
read_only true
end
field :name
field :content, :text
field :email
field :phone
RocketCMS.config.contacts_fields.each_pair do |fn, ft|
next if ft.nil?
if ft.is_a?(Array)
field fn, ft[1].to_sym
else
field fn
end
end
if block_given?
yield
end
RocketCMS.apply_patches self
RocketCMS.only_patches self, [:show, :list, :edit, :export]
}
end
def news_config(fields = {})
Proc.new {
navigation_label I18n.t('rs.cms')
list do
scopes [:by_date, :enabled, nil]
end
field :enabled, :toggle
field :time do
sort_reverse true
end
field :name
unless RocketCMS.config.news_image_styles.nil?
field :image, :jcrop do
jcrop_options :image_jcrop_options
end
end
field :excerpt, :ck_editor
field :slugs, :enum do
enum_method do
:slugs
end
visible do
bindings[:view].current_user.admin?
end
multiple do
true
end
end
field :text_slug
RocketCMS.apply_patches self
list do
RocketCMS.apply_patches self
sort_by :time
end
edit do
field :content, :ck_editor
fields.each_pair do |name, type|
if type.nil?
field name
else
if type.is_a?(Array)
field name, type[0], &type[1]
else
field name, type
end
end
end
RocketCMS.apply_patches self
group :seo, &RocketCMS.seo_config
group :sitemap_data, &RocketCMS.sitemap_data_config
end
RocketCMS.only_patches self, [:show, :list, :export]
if block_given?
yield(self)
end
}
end
def sitemap_data_config(is_active = false)
Proc.new {
active is_active
label I18n.t('rs.sitemap_data')
field :sitemap_show
field :sitemap_lastmod
field :sitemap_changefreq, :enum do
enum do
SitemapData::SITEMAP_CHANGEFREQ_ARRAY
end
end
field :sitemap_priority
if block_given?
yield
end
}
end
def embedded_element_config(navigation_label = I18n.t('rs.cms'), fields = {})
Proc.new {
navigation_label(navigation_label) unless navigation_label.nil?
field :enabled, :toggle
field :name, :string
fields.each_pair do |name, type|
if type.nil?
field name
else
if type.is_a?(Array)
field name, type[0], &type[1]
else
field name, type
end
end
end
if block_given?
yield
end
}
end
def embedded_image_config(fields = {})
jcrop_proc = Proc.new do
jcrop_options :image_jcrop_options
end
if block_given?
RocketCMS.embedded_element_config(
nil,
{image: [:jcrop, jcrop_proc]}.merge(fields),
yield
)
else
RocketCMS.embedded_element_config(
nil,
{image: [:jcrop, jcrop_proc]}.merge(fields)
)
end
end
def gallery_config
Proc.new {
navigation_label I18n.t('rs.gallery')
field :enabled, :toggle
field :name, :string
field :slugs, :enum do
enum_method do
:slugs
end
visible do
bindings[:view].current_user.admin?
end
multiple do
true
end
end
field :text_slug
field :image, :jcrop do
jcrop_options :image_jcrop_options
end
if block_given?
yield
end
}
end
def image_config(without_gallery = false, fields = {})
Proc.new {
navigation_label I18n.t('rs.gallery')
field :enabled, :toggle
unless without_gallery
field :gallery
end
field :name, :string
field :image, :jcrop do
jcrop_options :image_jcrop_options
end
fields.each_pair do |name, type|
if type.nil?
field name
else
field name, type
end
end
if block_given?
yield
end
}
end
end
end
|
ack43/rocket_cms
|
lib/generators/rocket_cms/templates/migration_news.rb
|
<reponame>ack43/rocket_cms<filename>lib/generators/rocket_cms/templates/migration_news.rb
class RocketCmsCreateNews < ActiveRecord::Migration
def change
create_table :news do |t|
t.boolean :enabled, default: true, null: false
t.timestamp :time, null: false
if RocketCMS.config.localize
t.column :name_translations, 'hstore', default: {}
t.column :excerpt_translations, 'hstore', default: {}
t.column :content_translations, 'hstore', default: {}
else
t.string :name, null: false
t.text :excerpt
t.text :content
end
t.string :slug, null: false
t.attachment :image
t.timestamps
end
add_index :news, :slug, unique: true
add_index :news, [:enabled, :time]
end
end
|
ack43/rocket_cms
|
app/controllers/contacts_controller.rb
|
class ContactsController < ApplicationController
include RocketCMS::Controllers::Contacts
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/page.rb
|
module RocketCMS
module Models
module Page
extend ActiveSupport::Concern
include RocketCMS::Model
include Enableable
include Seoable
include ManualSlug
include SitemapData
include RocketCMS.orm_specific('Page')
if RocketCMS.config.search_enabled
include RocketCMS::ElasticSearch
end
included do
has_and_belongs_to_many :menus, inverse_of: :pages
validates_uniqueness_of :fullpath
validates_presence_of :name
manual_slug :name
before_validation do
self.fullpath = "/pages/#{slug}" if self.fullpath.blank?
end
end
def get_fullpath
redirect.blank? ? fullpath : redirect
end
def has_content?
@content_used.nil? && !content.blank?
end
def page_content
if @content_used.nil?
@content_used = true
if content.nil?
''
else
content.gsub(/\{\{(.*?)\}\}/) do
Settings ? Settings.get($1).val : "" #temp
end
end
else
''
end
end
def is_current?(url)
if fullpath == '/'
url == '/'
else
url.match(clean_regexp)
end
end
def regexp_prefix
""
end
def clean_regexp
if regexp.blank?
/^#{regexp_prefix}#{Regexp.escape(fullpath)}$/
else
begin
/#{regexp}/
rescue
# not a valid regexp - treat as literal search string
/#{Regexp.escape(regexp)}/
end
end
end
def nav_options
{highlights_on: clean_regexp}
end
end
end
end
|
ack43/rocket_cms
|
app/models/concerns/sitemap_data.rb
|
<reponame>ack43/rocket_cms
module SitemapData
extend ActiveSupport::Concern
SITEMAP_CHANGEFREQ_ARRAY = %w(always hourly daily weekly monthly yearly never)
included do
if RocketCMS.mongoid?
field :sitemap_show, type: Boolean, default: true
field :sitemap_lastmod, type: DateTime
field :sitemap_changefreq, type: String, default: 'daily'
field :sitemap_priority, type: Float
scope :sitemap_show, -> { where(sitemap_show: true) }
scope :for_sitemap, -> { sitemap_show }
scope :show_in_sitemap, -> { sitemap_show }
elsif RocketCMS.active_record?
end
end
def self.admin
RocketCMS.sitemap_data_config
end
end
|
ack43/rocket_cms
|
app/models/concerns/seoable.rb
|
module Seoable
extend ActiveSupport::Concern
LOCALIZED_FIELDS = [:h1, :title, :keywords, :description, :og_title]
FIELDS = LOCALIZED_FIELDS + [:og_image, :robots]
if Seo.separate_table?
included do
has_one :seo, as: :seoable, autosave: true
accepts_nested_attributes_for :seo
delegate *FIELDS, to: :seo
delegate *(FIELDS.map {|f| "#{f}=".to_sym }), to: :seo
alias seo_without_build seo
def seo
seo_without_build || build_seo
end
if RocketCMS.config.localize
delegate *(LOCALIZED_FIELDS.map {|f| "#{f}_translations".to_sym }), to: :seo
delegate *(LOCALIZED_FIELDS.map {|f| "#{f}_translations=".to_sym }), to: :seo
end
end
include RocketCMS::SeoHelpers
else
include RocketCMS::Models::Seo
end
def self.admin
RocketCMS.seo_config
end
def og_image_jcrop_options
{aspectRation: 800.0/600.0}
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/controllers/pages.rb
|
<filename>lib/rocket_cms/controllers/pages.rb
module RocketCMS
module Controllers
module Pages
extend ActiveSupport::Concern
def show
if @seo_page.nil? || !@seo_page.persisted?
if !params[:id].blank? or !params[:slug].blank?
@seo_page = Page.enabled.find(params[:id] || params[:slug])
end
end
if @seo_page.nil?
render_404
return true
end
end
end
end
end
|
ack43/rocket_cms
|
lib/generators/rocket_cms/templates/migration_pages.rb
|
<filename>lib/generators/rocket_cms/templates/migration_pages.rb
class RocketCmsCreatePages < ActiveRecord::Migration
def change
create_table :menus do |t|
if RocketCMS.config.localize
t.column :name_translations, 'hstore'
else
t.string :name, null: false
end
t.string :slug, null: false
t.timestamps
end
add_index :menus, :slug, unique: true
create_table :pages do |t|
t.boolean :enabled, default: true, null: false
t.integer :parent_id
t.integer :lft
t.integer :rgt
t.integer :depth
if RocketCMS.config.localize
t.column :name_translations, 'hstore', default: {}
t.column :content_translations, 'hstore', default: {}
else
t.string :name, null: false
t.text :content
end
t.string :slug, null: false
t.string :regexp
t.string :redirect
t.string :fullpath, null: false
t.timestamps
end
add_index :pages, :slug, unique: true
add_index :pages, [:enabled, :lft]
create_join_table :menus, :pages
add_foreign_key(:menus_pages, :menus, dependent: :delete)
add_foreign_key(:menus_pages, :pages, dependent: :delete)
end
end
|
ack43/rocket_cms
|
rocket_cms.gemspec
|
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rocket_cms/version'
Gem::Specification.new do |spec|
spec.name = 'ack_rocket_cms'
spec.version = RocketCMS::VERSION
spec.authors = ['<NAME>', 'glebtv']
spec.email = ["<EMAIL>", '<EMAIL>']
spec.description = %q{RocketCMS fork}
spec.summary = %q{Please DO NOT use this gem directly, use ack_rocket_cms_mongoid or ack_rocket_cms_activerecord instead!}
spec.homepage = 'https://github.com/ack43/rocket_cms'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/).reject {|f| f.start_with?('mongoid') || f.start_with?('activerecord') }
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_dependency 'rails', '>= 4.1.0', '< 5.0'
spec.add_dependency 'jquery-rails'
spec.add_dependency 'simple_form'
spec.add_dependency 'glebtv-simple_captcha'
spec.add_dependency 'coffee-rails'
spec.add_dependency 'devise'
spec.add_dependency 'turbolinks'
spec.add_dependency 'validates_email_format_of'
spec.add_dependency 'rails_admin'
spec.add_dependency 'rails_admin_nested_set'
spec.add_dependency 'rails_admin_toggleable'
spec.add_dependency 'ckeditor'
spec.add_dependency 'rails_admin_settings'
spec.add_dependency 'geocoder'
spec.add_dependency 'simple-navigation'
spec.add_dependency 'sitemap_generator'
spec.add_dependency 'kaminari'
spec.add_dependency 'addressable'
# spec.add_dependency ''
spec.add_dependency 'x-real-ip'
spec.add_dependency "rails_admin_mongoid_localize_field", "~> 0.1.2"
spec.add_dependency "ack_rails_admin_jcrop"
spec.add_dependency 'stringex'
spec.add_dependency 'thor'
spec.add_dependency 'smart_excerpt'
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/embedded_element.rb
|
<filename>lib/rocket_cms/models/embedded_element.rb
module RocketCMS
module Models
module EmbeddedElement
extend ActiveSupport::Concern
include RocketCMS::Model
include Enableable
include Sortable
include RocketCMS.orm_specific('EmbeddedElement')
end
end
end
|
ack43/rocket_cms
|
lib/rocket_cms/models/seo.rb
|
<reponame>ack43/rocket_cms
module RocketCMS
module Models
module Seo
extend ActiveSupport::Concern
include RocketCMS::Model
include Enableable
include RocketCMS.orm_specific('Seo')
include RocketCMS::SeoHelpers
included do
RocketCMS.apply_patches self
validates_attachment_content_type :og_image, content_type: /\Aimage\/.*\Z/, if: :og_image?
end
end
end
end
|
ack43/rocket_cms
|
app/models/concerns/sortable.rb
|
<filename>app/models/concerns/sortable.rb
module Sortable
extend ActiveSupport::Concern
include SortField
included do
sort_field
end
end
|
vifreefly/sequel-db_tasks
|
test/sequel/db_tasks_test.rb
|
<filename>test/sequel/db_tasks_test.rb
require "test_helper"
class Sequel::DbTasksTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::Sequel::DbTasks::VERSION
end
def test_it_does_something_useful
assert false
end
end
|
vifreefly/sequel-db_tasks
|
lib/sequel/db_tasks/tasks.rake
|
<gh_stars>1-10
# All possible rails db tasks https://jacopretorius.net/2014/02/all-rails-db-rake-tasks-and-what-they-do.html
namespace :db do
task :preload, [:skip_adapter_validation] do |t, args|
require 'uri'
@url = Sequel::DbTasks.configuration.database_url
uri = URI.parse(@url)
unless args[:skip_adapter_validation]
raise "DB adapter is not postgres" if uri.scheme != "postgres"
end
end
###
# https://www.postgresql.org/docs/current/app-createdb.html
desc "Create database"
task create: :preload do
env = { "DATABASE_URL" => @url }
exec env, "postgressor", "createdb"
end
# https://www.postgresql.org/docs/current/app-dropdb.html
desc "Drop database"
task drop: :preload do
env = { "DATABASE_URL" => @url }
exec env, "postgressor", "dropdb"
end
###
# https://www.postgresql.org/docs/current/app-pgdump.html
desc "Dump (backup) database"
task dump: :preload do
env = { "DATABASE_URL" => @url }
exec env, "postgressor", "dumpdb"
end
# https://www.postgresql.org/docs/current/app-pgrestore.html
desc "Restore database from backup"
task :restore, [:restore_dump_file_path] do |t, args|
raise "Restore dump file path is not provided" unless args.restore_dump_file_path
Rake::Task["db:preload"].execute
env = { "DATABASE_URL" => @url }
command = ["postgressor", "restoredb", args.restore_dump_file_path]
command << "--switch_to_superuser" if ENV["AS_SUPERUSER"] == "true"
exec env, *command
end
###
# https://www.postgresql.org/docs/current/app-createuser.html
desc "Create database user" # superuser is optional
task create_user: :preload do
env = { "DATABASE_URL" => @url }
exec env, "postgressor", "createuser"
end
# https://www.postgresql.org/docs/current/app-dropuser.html
desc "Drop database user"
task drop_user: :preload do
env = { "DATABASE_URL" => @url }
exec env, "postgressor", "dropuser"
end
###
# https://github.com/jeremyevans/sequel/blob/master/doc/migration.rdoc#a-basic-migration
desc "Generate migration file"
task :gm, [:name] do |t, args|
migrations_path = Sequel::DbTasks.configuration.migrations_path
mkdir_p migrations_path
time = Time.now.utc.strftime("%Y%m%d%H%M%S")
filename = File.join(migrations_path, "#{time}_#{args.name}.rb")
File.write(filename,
<<~RUBY
# #{filename}
Sequel.migration do
change do
end
end
RUBY
)
puts "Created migration '#{filename}'"
end
# https://github.com/jeremyevans/sequel/blob/master/doc/migration.rdoc#running-migrations-from-a-rake-task
desc "Run migrations"
task :migrate, [:version] do |t, args|
Rake::Task["db:preload"].execute(skip_adapter_validation: true)
require 'sequel/core'
require 'logger'
Sequel.extension :migration
version = args[:version].to_i if args[:version]
Sequel.connect(@url, logger: Logger.new(STDOUT)) do |db|
Sequel::Migrator.run(db, Sequel::DbTasks.configuration.migrations_path, target: version)
end
end
# https://github.com/jeremyevans/sequel/blob/master/doc/migration.rdoc#dumping-the-current-schema-as-a-migration
desc "Print current database schema"
task :'schema:print' do
Rake::Task["db:preload"].execute(skip_adapter_validation: true)
exec "bundle", "exec", "sequel", "-d", @url
end
end
|
vifreefly/sequel-db_tasks
|
lib/sequel/db_tasks.rb
|
<filename>lib/sequel/db_tasks.rb
require 'ostruct'
module Sequel
module DbTasks
def self.configuration
@configuration ||= OpenStruct.new(
database_url: ENV["DATABASE_URL"],
migrations_path: "db/migrate"
)
end
def self.configure
yield(configuration)
end
def self.load!
Rake.application.add_import "#{__dir__}/db_tasks/tasks.rake"
end
end
end
|
JubalThang/twitter_many_to_many
|
lib/twitter_many_to_many/like.rb
|
class Like
@@all = []
def self.all
@@all
end
def initialize(attributes = {})
@tweet = attributes[:tweet]
@user = attributes[:user]
@@all << self
end
end
|
JubalThang/twitter_many_to_many
|
spec/01_examples_spec.rb
|
<reponame>JubalThang/twitter_many_to_many
# We can build more complicated relationships using one to many more than once.
RSpec.describe "Aquarium domain" do
let(:aquarium) { Aquarium.new(name: "Aquarium of the Pacific")}
let(:coral_reefs_exhibit) { Exhibit.new(name: "Coral Reefs: Nature's Underwater Cities", aquarium: aquarium)}
let(:shark_lagoon_exhibit) { Exhibit.new(name: "Shark Lagoon", aquarium: aquarium)}
let(:glowing_reef) { Fish.new(name: "Deep Reef", exhibit: coral_reefs_exhibit)}
let(:deep_reef) { Fish.new(name: "Deep Reef", exhibit: coral_reefs_exhibit)}
let(:clownfish) { Fish.new(name: "Clownfish", exhibit: coral_reefs_exhibit)}
let(:zebra_shark) { Fish.new(name: "Zebra Shark", exhibit: shark_lagoon_exhibit)}
let(:grey_reef_shark) {Fish.new(name: "Grey Reef Shark",exhibit: shark_lagoon_exhibit)}
let(:epaulette_shark){ Fish.new(name: "Epaulette Shark", exhibit: shark_lagoon_exhibit)}
describe "Basics" do
describe "Aquarium" do
describe ".all" do
it "returns an array of all aquariums" do
expect(Aquarium.all).to eq(Aquarium.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "accepts a hash of attributes as an argument, including a name, and saves the aquarium to @@all" do
expect { aquarium }.not_to raise_error
expect(aquarium.instance_variable_get("@name")).to eq("Aquarium of the Pacific")
expect(Aquarium.class_variable_get("@@all")).to include(aquarium)
end
end
end
describe "Exhibit" do
describe ".all" do
it ".all returns an array of @@all the Exhibits we've created so far" do
expect(Exhibit.all).to eq(Exhibit.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "accepts a hash of attributes as an argument, including a name and an aquarium, and saves the exhibit to @@all" do
expect { coral_reefs_exhibit }.not_to raise_error
expect(coral_reefs_exhibit.instance_variable_get("@name")).to eq("Coral Reefs: Nature's Underwater Cities")
expect(coral_reefs_exhibit.instance_variable_get("@aquarium")).to eq(aquarium)
expect(Exhibit.class_variable_get("@@all")).to include(coral_reefs_exhibit)
end
end
end
describe "Fish" do
describe ".all" do
it ".all returns an array of @@all the Fish we've created so far" do
expect(Fish.all).to eq(Fish.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "accepts a hash of attributes as an argument, including a name and an exhibit, and saves the fish to @@all" do
expect { grey_reef_shark }.not_to raise_error
expect(grey_reef_shark.instance_variable_get("@name")).to eq("Grey Reef Shark")
expect(grey_reef_shark.instance_variable_get("@exhibit")).to eq(shark_lagoon_exhibit)
expect(Fish.class_variable_get("@@all")).to include(grey_reef_shark)
end
end
end
end
describe "Associations" do
describe "Exhibit" do
describe "#fish" do
it "(has many fish) returns an array of all the fish in this exhibit" do
[shark_lagoon_exhibit, zebra_shark, grey_reef_shark, epaulette_shark]
expect(shark_lagoon_exhibit.fish).to include(zebra_shark, grey_reef_shark, epaulette_shark)
end
end
end
describe "Aquarium" do
describe "#exhibits" do
it "(has many exhibits) returns an array of Exhibit objects" do
[aquarium, coral_reefs_exhibit, shark_lagoon_exhibit]
expect(aquarium.exhibits).to include(coral_reefs_exhibit)
expect(aquarium.exhibits).to include(shark_lagoon_exhibit)
end
end
describe "#fish" do
it "(has many fish through exhibits) returns an array of Fish objects associated with" do
[aquarium, shark_lagoon_exhibit, grey_reef_shark, epaulette_shark]
expect(aquarium.fish).to include(grey_reef_shark)
expect(aquarium.fish).to include(epaulette_shark)
end
end
end
end
end
RSpec.describe "Doctor domain" do
let(:drew) { Doctor.new(name: "Dr. Drew") }
let(:amy) { Patient.new(name: "<NAME>") }
let(:appointment) { Appointment.new(time: "2PM", doctor: drew, patient: amy)}
describe "Basics" do
describe "Doctor" do
describe ".all" do
it "returns an array of all the doctors we have created." do
expect(Doctor.all).to eq(Doctor.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "accepts a hash of attributes as an argument, including a name, and stores the doctor in @@all" do
expect{ drew }.not_to raise_error
expect(Doctor.class_variable_get("@@all")).to include(drew)
end
end
end
describe "Patient" do
describe ".all" do
it "returns an array of all the patients we have created." do
expect(Patient.all).to eq(Patient.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "accepts a hash of attributes as an argument, including a name, and stores the patient in @@all" do
expect { amy }.not_to raise_error
expect(Patient.class_variable_get("@@all")).to include(amy)
end
end
end
describe "Appointment" do
describe ".all" do
it "returns an array of all appointments created" do
expect(Appointment.all).to eq(Appointment.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "takes a hash of attributes as an argument, including a time, doctor and patient, and stores the appointment in @@all" do
expect { appointment }.not_to raise_error
expect(Appointment.class_variable_get("@@all")).to include(appointment)
end
end
end
end
describe "Associations" do
describe "Appointment" do
describe "#doctor (belongs to)" do
it "returns the doctor this appointment belongs to" do
expect(appointment.doctor).to eq(drew)
end
end
describe "#patient (belongs to)" do
it "returns the patient this appointment belongs to" do
expect(appointment.patient).to eq(amy)
end
end
end
describe "Doctor" do
describe "#appointments (has_many)" do
it "returns an array of appointments that belong to this doctor" do
appointment
expect(drew.appointments).to include(appointment)
end
end
describe "#patients (has_many, through)" do
it "returns an array of patients that this doctor has appointments with" do
appointment
expect(drew.patients).to include(amy)
end
end
end
describe "Patient" do
describe "#appointments (has_many)" do
it "returns an array of appointments that belong to this patient" do
appointment
expect(amy.appointments).to include(appointment)
end
end
describe "#doctors (has_many, through)" do
it "returns an array of doctors that this patient has appointments with" do
appointment
expect(amy.doctors).to include(drew)
end
end
end
end
end
|
JubalThang/twitter_many_to_many
|
spec/02_exercise_spec.rb
|
<gh_stars>0
RSpec.describe "Exercise - Many to Many - User <=> Tweet through likes" do
let(:user1) { User.new(username: "Dakota") }
let(:user2) { User.new(username: "Sandra") }
let(:tweet1) { Tweet.new(message: "I can show you the world", user: user1)}
let(:tweet2) { Tweet.new(message: "Shining, shimmering, splendid!", user: user2) }
let(:tweet3) { Tweet.new(message: "I look down at my phone for 1 minute and American Idol's winner is spoiled #frustrated", user: user2)}
let(:like1) { Like.new(tweet: tweet1, user: user2) }
let(:like2) { Like.new(tweet: tweet2, user: user1) }
describe "Basics" do
describe "User" do
before(:each) do
User.class_variable_set("@@all", [])
end
describe ".all" do
it "returns an array containing all User objects" do
[user1, user2]
expect(User.all).to include(user1, user2)
expect(User.all).to eq(User.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "takes a hash of attributes as an argument, including a username, and adds the user to @@all" do
expect { user1 }.not_to raise_error
expect(user1.instance_variable_get("@username")).to eq("Dakota")
expect(User.all).to include(user1)
end
end
end
describe "Tweet" do
before(:each) do
Tweet.class_variable_set("@@all", [])
end
describe ".all" do
it "returns an array containing all Tweet objects" do
[tweet1, tweet2, tweet3]
expect(Tweet.all).to include(tweet1, tweet2, tweet3)
expect(Tweet.all).to eq(Tweet.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "takes a hash of attributes as an argument, including a message and a user, and adds the tweet to @@all" do
expect { tweet1 }.not_to raise_error
expect(tweet1.instance_variable_get("@message")).to eq("I can show you the world")
expect(tweet1.instance_variable_get("@user")).to eq(user1)
expect(Tweet.all).to include(tweet1)
end
end
end
describe "Like" do
before(:each) do
Like.class_variable_set("@@all", [])
end
describe ".all" do
it "returns an array containing all Like objects" do
[like1, like2]
expect(Like.all).to include(like1, like2)
expect(Like.all).to eq(Like.class_variable_get("@@all"))
end
end
describe "#initialize" do
it "takes a hash of attributes as an argumet, including a tweet and a user, and adds the like to @@all" do
expect { like1 }.not_to raise_error
expect(like1.instance_variable_get("@tweet")).to eq(tweet1)
expect(like1.instance_variable_get("@user")).to eq(user2)
expect(Like.all).to include(like1)
end
end
end
end
describe "Associations" do
before(:each) do
User.class_variable_set("@@all", [])
Tweet.class_variable_set("@@all", [])
Like.class_variable_set("@@all", [])
end
describe "Like" do
describe "#tweet (belongs_to)" do
it "returns the tweet this like belongs to" do
expect(like1.tweet).to eq(tweet1)
end
end
describe "#user (belongs_to)" do
it "returns the user this like belongs to" do
expect(like1.user).to eq(user2)
end
end
end
describe "User" do
describe "#likes (has_many)" do
it "returns an array of likes that belong to this user" do
like1
expect(user2.likes).to include(like1)
end
end
describe "#liked_tweets (has_many, through)" do
it "returns an array of tweets that this user has liked" do
like1
expect(user2.liked_tweets).to include(tweet1)
end
end
end
describe "Tweet" do
describe "#likes (has_many)" do
it "returns an array of likes that belong to this tweet" do
like1
expect(tweet1.likes).to include(like1)
end
end
describe "#likers (has_many, through)" do
it "returns an array of users that have liked this tweet" do
like1
expect(tweet1.likers).to include(user2)
end
end
end
end
end
|
JubalThang/twitter_many_to_many
|
lib/twitter_many_to_many.rb
|
require "pry"
require "twitter_many_to_many/version"
require "twitter_many_to_many/examples"
require "twitter_many_to_many/like"
require "twitter_many_to_many/user"
require "twitter_many_to_many/tweet"
module TwitterManyToMany
class Error < StandardError; end
# Your code goes here...
end
|
JubalThang/twitter_many_to_many
|
lib/twitter_many_to_many/tweet.rb
|
class Tweet
@@all = []
def self.all
@@all
end
attr_reader :message, :user
def initialize(attributes = {})
@message = attributes[:message]
@user = attributes[:user]
@@all << self
end
def username
user.username
end
def delete
Tweet.all.delete(self)
end
end
|
zachalbert/wbc
|
extras/rails/config/initializers/blendid.rb
|
<reponame>zachalbert/wbc
ASSET_PATH_CONFIG = JSON.parse(File.read('config/path-config.json'))
REV_MANIFEST_PATH = File.join(ASSET_PATH_CONFIG['dest'].gsub("..", "."), 'rev-manifest.json')
if File.exist?(REV_MANIFEST_PATH)
REV_MANIFEST = JSON.parse(File.read(REV_MANIFEST_PATH))
elsif !Rails.env.development? && !Rails.env.test?
raise "rev-manifest.json can not be found at path: #{REV_MANIFEST_PATH} and is required in non-development environments"
end
|
heroku/identity
|
lib/identity/heroku_cookie.rb
|
<gh_stars>10-100
module Identity
# This extension helps with set/unset logic for the infamous Heroku cookie
# used by Identity and other Heroku properties. The purpose of the Heroku
# cookie is to set a general cookie available on the `.heroku.com` domain
# that helps signal to other properties that the current user is logged in.
#
# A tiny bit of historical info: this started out as just `heroku_session`
# which is just a simple boolean. It was eventually expanded to
# `heroku_session_nonce` where a unique nonce value for the current user is
# stored; other properties can observe the nonce value for changes to quickly
# determine whether or not the logged in user has changed since the last time
# the browser visited.
module HerokuCookie
def self.registered(app)
app.instance_eval do
include Helpers::Log
include Methods
end
app.after do
if @cookie && @cookie.session_id
set_heroku_cookie(headers, "heroku_session", "1")
set_heroku_cookie(headers, "heroku_session_nonce", @cookie.session_id)
set_heroku_cookie(headers, "heroku_user_session", encrypted_user_info)
log :write_heroku_cookie,
nonce: @cookie.session_id,
oauth_dance_id: request.cookies["oauth_dance_id"]
else
delete_heroku_cookie(headers, "heroku_session")
delete_heroku_cookie(headers, "heroku_session_nonce")
delete_heroku_cookie(headers, "heroku_user_session")
log :delete_heroku_cookie,
oauth_dance_id: request.cookies["oauth_dance_id"]
end
end
end
private
module Methods
def delete_heroku_cookie(headers, key)
Rack::Utils.delete_cookie_header!(headers, key,
domain: Config.heroku_cookie_domain,
path: "/",
)
end
def set_heroku_cookie(headers, key, value)
Rack::Utils.set_cookie_header!(headers, key,
domain: Config.heroku_cookie_domain,
expires: Time.now + Config.cookie_expire_after,
path: "/",
value: value
)
end
private
def user_info
{
user: {
id: @cookie.user_id,
email: @cookie.user_email,
full_name: @cookie.user_full_name
}
}
end
def encrypted_user_info
cookie_coder.encode(user_info)
end
def cookie_coder
@cookie_coder ||= CookieCoder.new(
Config.heroku_root_domain_cookie_encryption_key,
Config.old_heroku_root_domain_cookie_encryption_key
)
end
end
end
end
|
heroku/identity
|
test/service_stubs/heroku_api_stub.rb
|
require "multi_json"
require "sinatra/base"
require "sinatra/namespace"
class HerokuAPIStub < Sinatra::Base
AUTHORIZATION = {
client: {
redirect_uri: "https://dashboard.heroku.com/oauth/callback/heroku"
},
grant: { code: "454118bc-902d-4a2c-9d5b-e2a2abb91f6e" }
}
register Sinatra::Namespace
configure do
set :raise_errors, true
set :show_exceptions, false
end
helpers do
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
def auth_credentials
auth.provided? && auth.basic? ? auth.credentials : nil
end
def authorized!
halt(401, "Unauthorized") unless auth_credentials
end
def two_factor?
user = auth_credentials.first
!env['HTTP_HEROKU_TWO_FACTOR_CODE'] && user.start_with?('two')
end
end
before do
@body = MultiJson.decode(request.body.read) rescue {}
end
post "/password-resets" do
MultiJson.encode(
created_at: Time.now.utc,
user: {
email: "<EMAIL>",
id: "06dcaabe-f7cd-473a-aa10-df54045ff69c"
}
)
201
end
post "/password-resets/:token/actions/finalize" do
MultiJson.encode(
created_at: Time.now.utc,
user: {
email: "<EMAIL>",
id: "06dcaabe-f7cd-473a-aa10-df54045ff69c"
}
)
end
patch "/users/~" do
authorized!
200
end
get "/oauth/authorizations" do
status(200)
MultiJson.encode([])
end
post "/oauth/authorizations" do
authorized!
if two_factor?
status(403)
response.headers['Heroku-Two-Factor-Required'] = 'true'
return MultiJson.encode(
message: 'A second factor is required.',
id: 'two_factor'
)
end
status(201)
authorization = {
id: "6<PASSWORD>",
scope: ["global"],
created_at: Time.now,
updated_at: Time.now,
access_token: nil,
client: {
id: 123,
ignores_delinquent: false,
name: "dashboard",
redirect_uri: AUTHORIZATION[:client][:redirect_uri],
},
grant: {
code: AUTHORIZATION[:grant][:code],
expires_in: 300,
},
refresh_token: nil,
user: {
id: "<PASSWORD>",
email: "<EMAIL>",
full_name: "<NAME>"
},
}
if @body["create_session"]
authorization.merge!(
session: { id: "8bb579ed-e3a4-41ed-9c1c-719e96618f71" })
end
if @body["create_tokens"]
authorization.merge!(
access_token: {
id: "<EMAIL>",
token: "<KEY>",
expires_in: 7200,
},
refresh_token: {
id: "<EMAIL>",
token: "faa180e4-5844-42f2-ad66-0c574a1dbed2",
expires_in: 2592000
})
end
MultiJson.encode(authorization)
end
get "/oauth/clients/:id" do |id|
status(200)
MultiJson.encode({
id: id,
name: "An OAuth Client",
description: "This is a sample OAuth client rendered by the API stub.",
ignores_delinquent: false,
redirect_uri: "https://example.com/oauth/callback/heroku",
trusted: id != Identity::Config.parse_oauth_client_id,
})
end
delete "/oauth/sessions/:id" do |id|
status(200)
MultiJson.encode({
id: id,
description: "Session @ 127.0.0.1",
expires_in: 2592000,
})
end
post "/oauth/tokens" do
status(201)
MultiJson.encode({
authorization: {
id: "<PASSWORD>",
},
access_token: {
id: "<EMAIL>",
token: "<KEY>",
expires_in: 7200,
},
refresh_token: {
id: "<EMAIL>",
token: "<PASSWORD>",
expires_in: 2592000,
},
session: {
id: "8bb579ed-e3a4-41ed-9c1c-719e96618f71",
},
user: {
session_nonce: "0a80ac35-b9d8-4fab-9261-883bea77ad3a",
}
})
end
patch "/invitations/:token" do
MultiJson.encode({
created_at: Time.now.utc,
user: {
email: "<EMAIL>",
id: "06dcaabe-f7cd-473a-aa10-df54045ff69c"
}
})
end
get "/users/~/sms-number" do
authorized!
MultiJson.encode({
sms_number: two_factor? ? '+1 *** 1234' : nil,
})
end
post "/users/~/sms-number/actions/recover" do
status(201)
end
end
if __FILE__ == $0
$stdout.sync = $stderr.sync = true
HerokuAPIStub.run! port: ENV["PORT"]
end
|
heroku/identity
|
test/robots_test.rb
|
<filename>test/robots_test.rb
require_relative "test_helper"
describe Identity::Robots do
include Rack::Test::Methods
def app
Identity::Robots
end
describe "GET /robots.txt" do
it "responds with a robots file" do
get "/robots.txt"
assert_match /text\/plain/, last_response.headers["Content-Type"]
assert_match /User-agent:/, last_response.body
assert_match /Disallow:/, last_response.body
end
end
end
|
heroku/identity
|
test/error_handling_test.rb
|
<gh_stars>10-100
require_relative "test_helper"
describe Identity::ErrorHandling do
include Rack::Test::Methods
def app
Sinatra.new do
register Identity::ErrorHandling
set :views, "#{Identity::Config.root}/views"
get "/401" do
raise Excon::Errors::Unauthorized.new("go away")
end
get "/404" do
raise Excon::Errors::NotFound.new("not found")
end
get "/429" do
raise Excon::Errors::TooManyRequests.new("too many")
end
get "/503" do
raise Excon::Errors::Timeout.new("timeout")
end
end
end
describe "401" do
it "renders the 401 error page" do
get "/401"
assert_equal 401, last_response.status
assert_match /Your credentials are invalid/, last_response.body
end
end
describe "404" do
it "renders the 404 error page" do
get "/404"
assert_equal 404, last_response.status
assert_match /but we couldn't find that page/, last_response.body
end
end
describe "429" do
it "renders the 429 error page" do
get "/429"
assert_equal 429, last_response.status
assert_match /Too Many Requests/, last_response.body
end
end
describe "unavailable errors" do
it "renders the 503 error page" do
get "/503"
assert_equal 503, last_response.status
assert_match /Unavailable/, last_response.body
end
end
end
|
heroku/identity
|
test/login_external_test.rb
|
require_relative "test_helper"
describe Identity::Account do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Rack::Session::Cookie, domain: "example.org", secret: "my-secret"
run Identity::LoginExternal
end
end
def request_session
last_request.env["rack.session"]
end
before do
rack_mock_session.clear_cookies
end
describe "shared key is not configured" do
before do
stub(Identity::Config).login_external_secret { nil }
end
it "returns 404" do
get "/login/extenal?token=123"
assert_equal 404, last_response.status
end
end
describe "shared key is configured" do
let(:shared_key){ "hello world secret token" }
before do
stub(Identity::Config).login_external_secret { shared_key }
end
it "returns 401 if token is incorrect" do
get "/login/external?token=123"
assert_equal 401, last_response.status
end
describe "token is correct" do
let(:jwt_data) { { "foo" => "bar" } }
let(:token) { JWT.encode(jwt_data, shared_key, "HS256") }
describe "there is no active oauth authorization request" do
it "writes cookies and redirects to dashboard" do
any_instance_of(Identity::LoginExternal) do |finalize|
mock(finalize).write_authentication_to_cookie(jwt_data)
end
get "/login/external?token=#{token}"
assert_equal 302, last_response.status
assert_equal Identity::Config.dashboard_url,
last_response.headers["Location"]
end
end
describe "the user has an active oauth authorization request" do
before do
stub_heroku_api
end
let(:jwt_data) do
{ access_token: { token: "abcd", expires_in: 9000 },
session: { id: "456" },
user: { id: "123" },
sso_entity: "initech" }
end
let(:session_data) do
{ "authorize_params" => MultiJson.encode("client_id" => "dashboard") }
end
it "finishes the authorization" do
get "/login/external",
{ token: token },
"rack.session" => session_data
assert_response_redirects_with_oauth_callback
end
end
describe "existing sessions" do
let(:session_id) { "1234" }
let(:rack_env) do
{
"rack.session" => {
"oauth_session_id" => session_id, "access_token" => "<PASSWORD>"
}
}
end
it "clears an existing session" do
session_deleted = false
stub_heroku_api do
delete "/oauth/sessions/:id" do
session_deleted = true
status 200
end
end
any_instance_of(Identity::LoginExternal) do |finalize|
mock(finalize).write_authentication_to_cookie(jwt_data)
end
get "/login/external?token=#{token}", {}, rack_env
assert_equal 302, last_response.status
assert session_deleted, "old session must be deleted"
assert_match /^heroku_user_session=(.+)$/, response_cookie,
"it should contain a new session"
refute_match /^heroku_user_session=#{session_id}$/, response_cookie,
"it should not contain the old session"
end
end
end
end
private
def response_cookie
last_response.headers["Set-Cookie"]
end
end
|
heroku/identity
|
lib/identity/heroku_api.rb
|
<reponame>heroku/identity<filename>lib/identity/heroku_api.rb
require "base64"
module Identity
class HerokuAPI < Excon::Connection
def initialize(ip:, version:, authorization: nil, headers: {}, pass: nil,
request_ids: [], user: nil)
headers = {
"Accept" => "application/vnd.heroku+json; version=#{version}",
# explicitly specify this or bodies will be interpreted as JSON
"Request-ID" => request_ids,
"X-Forwarded-For" => ip,
}.merge!(headers)
if version == 2
headers.merge!("Content-Type" => "application/x-www-form-urlencoded")
else
headers.merge!("Content-Type" => "application/json")
end
if user || pass
authorization = ["#{user || ''}:#{pass || ''}"].pack('m').delete("\r\n")
headers["Authorization"] = "Basic #{authorization}"
elsif authorization
headers["Authorization"] = authorization
end
uri = URI.parse(Config.heroku_api_url)
super(
host: uri.host,
path: uri.path,
port: uri.port,
scheme: uri.scheme,
headers: headers,
instrumentor: ExconInstrumentor.new(request_id: request_ids))
end
%i(delete get patch post put).each do |verb|
define_method(verb) do |*args|
convert_errors do
super(*args)
end
end
end
private
# Maps V3 error identifiers to custom error classes.
#
# This is a relatively new concept where before we just had multiple
# conditionals inside of a single rescue of an Excon status-class error. We
# should try to aim to increasingly move toward this model for better
# clarity.
ERROR_MAP = {
password_expired: Identity::Errors::PasswordExpired,
suspended: Identity::Errors::SuspendedAccount,
}
def convert_errors
yield
rescue Excon::Errors::HTTPStatusError => e
error_id, error_message = begin
data = MultiJson.decode(e.response.body)
# we may be dealing with a non-V3 error here, so deal with that case
if data.is_a?(Hash) && data.key?("id") && data.key?("message")
[data["id"].try(:to_sym), data["message"]]
else
[nil, nil]
end
rescue MultiJson::ParseError
[nil, nil]
end
if klass = ERROR_MAP[error_id]
raise klass.new(error_message)
else
raise
end
end
end
end
|
heroku/identity
|
lib/identity/config.rb
|
module Identity
module Config
extend self
def cookie_encryption_key
ENV.fetch("COOKIE_ENCRYPTION_KEY")
end
def old_cookie_encryption_key
ENV["OLD_COOKIE_ENCRYPTION_KEY"]
end
def heroku_root_domain_cookie_encryption_key
ENV.fetch("HEROKU_ROOT_DOMAIN_COOKIE_ENCRYPTION_KEY")
end
def old_heroku_root_domain_cookie_encryption_key
ENV["OLD_HEROKU_ROOT_DOMAIN_COOKIE_ENCRYPTION_KEY"]
end
def cookie_expire_after
ENV.fetch("COOKIE_EXPIRE_AFTER", 2592000).to_i
end
def dashboard_url
ENV.fetch("DASHBOARD_URL")
end
def sso_base_url
ENV["SSO_BASE_URL"]
end
def heroku_api_url
ENV.fetch("HEROKU_API_URL")
end
def heroku_oauth_id
ENV.fetch("HEROKU_OAUTH_ID")
end
def heroku_oauth_secret
ENV.fetch("HEROKU_OAUTH_SECRET")
end
def heroku_cookie_domain
ENV.fetch("HEROKU_COOKIE_DOMAIN", ".heroku.com")
end
def mixpanel_token
ENV["MIXPANEL_TOKEN"]
end
def google_tag_manager_account
ENV["GOOGLE_TAG_MANAGER_ACCOUNT"]
end
def login_external_secret
ENV["LOGIN_EXTERNAL_SECRET"]
end
def rollbar_access_token
ENV["ROLLBAR_ACCESS_TOKEN"]
end
def rack_env
ENV.fetch("RACK_ENV", "development")
end
def development?
rack_env == "development"
end
def production?
rack_env == "production"
end
def redirect_all_signups
!ENV["REDIRECT_ALL_SIGNUPS"].nil?
end
def release
@release ||= ENV.fetch("RELEASE", "1")
end
def root
@root ||= File.expand_path("../../../", __FILE__)
end
def signup_url
ENV.fetch("SIGNUP_URL")
end
# useful for staging environments with less-than-valid certs
# e.g. api.staging.herokudev.com
def ssl_verify_peer?
ENV["SSL_VERIFY_PEER"] != "false"
end
def parse_oauth_client_id
"17ae0773-297f-4437-a640-e70f464ff9f4"
end
end
end
|
heroku/identity
|
lib/identity.rb
|
require_relative "identity/config"
require_relative "identity/csrf"
require_relative "identity/cookie"
require_relative "identity/design"
require_relative "identity/error_handling"
require_relative "identity/errors"
require_relative "identity/excon_instrumentor"
require_relative "identity/fernet_cookie_coder"
require_relative "identity/cookie_coder"
require_relative "identity/heroku_api"
require_relative "identity/heroku_cookie"
require_relative "identity/rescue_errors"
require_relative "identity/helpers/log"
require_relative "identity/helpers/api"
require_relative "identity/helpers/auth"
# modules
require_relative "identity/account"
require_relative "identity/assets"
require_relative "identity/auth"
require_relative "identity/default"
require_relative "identity/login_external"
require_relative "identity/robots"
require_relative "identity/main"
module Identity
# make sure we get an app=identity in every line that we log
def self.log(action, data={}, &block)
data.merge!(app: "identity")
Slides.log(action, data, &block)
end
end
|
heroku/identity
|
test/auth_test.rb
|
<filename>test/auth_test.rb
require_relative "test_helper"
describe Identity::Auth do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Rack::Session::Cookie, domain: "example.org", secret: "my-secret"
use Rack::Flash
run Identity::Auth
end
end
before do
stub_heroku_api
rack_mock_session.clear_cookies
end
describe "POST /oauth/authorize" do
it "responds to GET as well" do
get "/oauth/authorize"
assert_equal 302, last_response.status
end
it "can be called by a user who is logged in" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_equal "https://dashboard.heroku.com",
last_response.headers["Location"]
follow_redirect!
post "/oauth/authorize", client_id: "dashboard"
assert_response_redirects_with_oauth_callback
end
it "stores and replays an authorization attempt when not logged in" do
post "/oauth/authorize", client_id: "dashboard"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
follow_redirect!
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_response_redirects_with_oauth_callback
end
it "passes state" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard", state: "my-state"
assert_response_redirects_with_oauth_callback state: "my-state"
end
it "redirects to login when a user is suspended" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
stub_heroku_api do
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "suspended",
message: "you are suspended"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::UnprocessableEntity.new(
"UnprocessableEntity", nil, response)
}
end
post "/oauth/authorize", client_id: "dashboard"
assert_equal 302, last_response.status
follow_redirect!
assert_equal 200, last_response.status
assert_match /you are suspended/, last_response.body
end
it "redirects to login when prompt=login is provided" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard", state: "my-state", prompt: "login"
assert_equal 302, last_response.status
assert_equal "http://example.org/login", last_response.headers["Location"]
end
it "redirects to password reset when a user's password has expired" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
stub_heroku_api do
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "password_expired",
message: "password expired"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::UnprocessableEntity.new(
"UnprocessableEntity", nil, response)
}
end
post "/oauth/authorize", client_id: "dashboard"
assert_equal 302, last_response.status
assert_match %r{/account/password/reset\z}, last_response.headers["Location"]
end
describe "when I have previously logged in via SSO" do
let(:rack_env) do
{ "rack.session" => { "sso_entity" => "initech" } }
end
it "redirects to the sso entity" do
post "/oauth/authorize", { client_id: "dashboard" }, rack_env
assert_equal 302, last_response.status
assert_equal "https://sso.heroku.com/initech",
last_response.headers["Location"]
end
describe "with a valid token" do
let(:rack_env) do
{
"rack.session" => {
"sso_entity" => "initech",
"access_token" => "<PASSWORD>",
"access_token_expires_at" => (Time.now.getlocal + 3600).to_s
}
}
end
it "authorizes when i have a valid access token" do
stub_heroku_api do
get("/account") { status(200) }
end
post "/oauth/authorize", { client_id: "dashboard" }, rack_env
assert_response_redirects_with_oauth_callback
end
end
describe "with an invalid token" do
let(:rack_env) do
{
"rack.session" => {
"sso_entity" => "initech",
"access_token" => "<PASSWORD>",
"access_token_expires_at" => (Time.now.getlocal + 3600).to_s
}
}
end
it "redirects to the sso entity" do
stub_heroku_api do
get("/account") { status(401) }
end
post "/oauth/authorize", { client_id: "dashboard" }, rack_env
assert_equal 302, last_response.status
assert_equal "https://sso.heroku.com/initech",
last_response.headers["Location"]
end
end
end
describe "for a delinquent account" do
it "redirects to `Location` for a client that does not `ignore_deliquent`" do
stub_heroku_api do
get("/oauth/clients/:id") {
headers["Heroku-Delinquent"] = "true"
headers["Location"] = "https://example.com"
MultiJson.encode({
ignores_delinquent: false
})
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
assert_equal 302, last_response.status
assert_equal "https://example.com", last_response.headers["Location"]
end
it "redirects normally for a client that does `ignore_delinquent" do
stub_heroku_api do
get("/oauth/clients/:id") {
headers["Heroku-Delinquent"] = "true"
headers["Location"] = "https://example.com"
MultiJson.encode({
ignores_delinquent: true,
redirect_uri: "https://dashboard.heroku.com",
trusted: true,
})
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
assert_response_redirects_with_oauth_callback
end
end
describe "for an untrusted client" do
before do
stub_heroku_api do
get("/oauth/clients/:id") {
MultiJson.encode({
trusted: false,
redirect_uri: HerokuAPIStub::AUTHORIZATION[:client][:redirect_uri]
})
}
end
end
it "confirms with the user before authorizing" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "untrusted"
assert_equal 200, last_response.status
assert_match /\bAllow\b/, last_response.body
end
it "creates an authorization after a user confirms" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
# post once to get parameters stored to session
post "/oauth/authorize", client_id: "untrusted"
# then again to confirm
post "/oauth/authorize", authorize: "Allow"
assert_response_redirects_with_oauth_callback
end
it "contains a button that denies access" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
# post once to get parameters stored to session
post "/oauth/authorize", client_id: "untrusted"
#check that the deny link points to the right place
uri = HerokuAPIStub::AUTHORIZATION[:client][:redirect_uri]
assert last_response.body.include?("#{uri}?error=access_denied")
end
it "does not create an authorization if a user confirms via GET" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
# post once to get parameters stored to session
post "/oauth/authorize", client_id: "untrusted"
# then try again, but with the wrong request method (should be POST)
get "/oauth/authorize", authorize: "Allow"
assert_equal 200, last_response.status
assert_match /\bAllow\b/, last_response.body
end
it "requires an actual client id" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: ""
assert_equal 400, last_response.status
end
end
end
describe "POST /oauth/token" do
it "renders access and refresh tokens" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
post "/oauth/token"
assert_equal 200, last_response.status
tokens = MultiJson.decode(last_response.body)
assert_equal "e51e8a64-29f1-4bbf-997e-391d84aa12a9", tokens["access_token"]
assert_equal "<PASSWORD>", tokens["refresh_token"]
assert_equal 7200, tokens["expires_in"]
end
describe "authorization_code" do
before do
stub_heroku_api do
post("/oauth/tokens") {
raise("missing_param=grant:code") unless @body["grant"]["code"]
raise("missing_param=grant:type") unless @body["grant"]["type"]
raise("missing_param=client:secret") \
unless @body["client"]["secret"]
raise("invalid_param=client:secret") \
unless @body["client"]["secret"] == "<KEY>"
raise("extra_param=refresh_token:token") \
if @body["refresh_token"]["token"]
status(201)
MultiJson.encode({
authorization: {
id: "68e3146b-be7e-4520-<PASSWORD>",
},
access_token: {
id: "<PASSWORD>",
token: "<PASSWORD>",
expires_in: 7200,
},
refresh_token: {
id: "<PASSWORD>",
token: "<PASSWORD>",
expires_in: 2592000,
},
session: {
id: "8bb579ed-e3a4-41ed-9c1c-719e96618f71",
},
user: {
session_nonce: "0a80ac35-b9d8-4fab-9261-883bea77ad3a",
}
})
}
end
end
it "accepts secret in body and returns 201" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
post "/oauth/token",
grant_type: "authorization_code",
code: "secret-auth-grant-code",
client_secret: "<KEY>"
assert_equal 200, last_response.status
end
it "accepts secret in auth header and returns 201" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
basic_authorize "<EMAIL>", "<PASSWORD>-e39a-<PASSWORD>"
post "/oauth/token",
grant_type: "authorization_code",
code: "secret-auth-grant-code"
assert_equal 200, last_response.status
end
end
it "accepts a refresh token" do
stub_heroku_api do
post("/oauth/tokens") {
raise("missing_param=grant:type") unless @body["grant"]["type"]
raise("missing_param=refresh_token:token") \
unless @body["refresh_token"]["token"]
raise("extra_param=grant:code") if @body["grant"]["code"]
status(201)
MultiJson.encode({
authorization: {
id: "<PASSWORD>",
},
access_token: {
id: "<PASSWORD>",
token: "e<PASSWORD>-<PASSWORD>-4bbf-9<PASSWORD>-391d84aa<PASSWORD>",
expires_in: 7200,
},
refresh_token: {
id: "<PASSWORD>",
token: "faa1<PASSWORD>4-5844-42f2-ad66-0c574a1dbed2",
expires_in: 2592000,
},
session: {
id: "8bb579ed-e3a4-41ed-9c1c-719e96618f71",
},
user: {
session_nonce: "0a80ac35-b9d8-4fab-9261-883bea77ad3a",
}
})
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
post "/oauth/authorize", client_id: "dashboard"
post "/oauth/token",
grant_type: "refresh_token",
refresh_token: "<PASSWORD>"
assert_equal 200, last_response.status
end
it "forwards a 401" do
stub_heroku_api do
post("/oauth/tokens") {
raise Excon::Errors::Unauthorized.new("Unauthorized", nil,
Excon::Response.new(body: "Unauthorized", status: 401))
}
end
post "/oauth/token"
assert_equal 401, last_response.status
end
it "forwards a 422" do
stub_heroku_api do
post("/oauth/tokens") {
raise Excon::Errors::UnprocessableEntity.new("missing param", nil,
Excon::Response.new(body: "missing param", status: 422))
}
end
post "/oauth/token"
assert_equal 422, last_response.status
end
it "forwards a 403" do
stub_heroku_api do
post("/oauth/tokens") do
body = MultiJson.encode(id: "suspended", message: "ruh roh")
raise Excon::Errors::Forbidden.new(
"suspended",
nil,
Excon::Response.new(body: body, status: 403))
end
end
post "/oauth/token"
assert_equal 403, last_response.status
assert_equal "ruh roh", last_response.body
end
end
describe "GET /login" do
it "shows a login page" do
get "/login"
assert_equal 200, last_response.status
end
describe "when coming from a pending authorization" do
before do
@authorize_params = { client_id: SecureRandom.uuid }
end
let(:rack_env) do
{
"x-rack.flash" => { link_account: true },
"rack.session" => { "authorize_params" => MultiJson.encode(@authorize_params) }
}
end
# use Capybara's for matchers like has_content? and has_elector?
let(:page) { Capybara::Node::Simple.new(last_response.body) }
it "renders the regular login page for trusted clients" do
get "/login", {}, rack_env
assert_equal 200, last_response.status
assert page.has_selector?("h3", text: "Log in to your account")
end
describe "for untrusted clients" do
before do
# parse's client id is hardcoded for now:
@authorize_params[:client_id] = Identity::Config.parse_oauth_client_id
end
it "renders a slightly different login screen for untrusted" do
get "/login", {}, rack_env
assert_equal 200, last_response.status
assert page.has_selector?("h3", text: "Log in to link accounts")
end
it "uses a custom sign-up campaign for Parse" do
get "/login", {}, rack_env
assert_equal 200, last_response.status
assert page.has_link?("sign up", href: "/signup/parse")
end
end
end
end
describe "POST /login" do
it "logs a user in and redirects to dashboard" do
post "/login", { email: "<EMAIL>", password: "<PASSWORD>" },
{ "HTTP_X_FORWARDED_FOR" => "8.7.6.5" }
assert_equal 302, last_response.status
assert_equal Identity::Config.dashboard_url,
last_response.headers["Location"]
end
it "redirects to login on a failed login" do
stub_heroku_api do
#post("/oauth/authorizations") { 401 }
# webmock doesn't handle Excon's :expects, so raise error directly
# until it does
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "unauthorized",
message: "you are not authorized"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::Unauthorized.new(
"Unauthorized", nil, response)
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "sets a heroku-wide session nonce in the cookie" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_includes response_cookie, "heroku_session=1;"
assert_includes response_cookie,
"heroku_session_nonce=8bb579ed-e3a4-41ed-9c1c-719e96618f71;"
assert response_cookie =~ /^heroku_user_session=(.+)$/,
"it should contain heroku_user_session"
# current version of `fernet` barks about URL encoded string
cipher = $1.split(";")[0]
coder = Identity::CookieCoder.new(
Identity::Config.heroku_root_domain_cookie_encryption_key)
payload = coder.decode(cipher)
assert_equal "06dcaabe-f7cd-473a-aa10-df54045ff69c", payload["user"]["id"]
assert_equal "<EMAIL>", payload["user"]["email"]
assert_equal "Full Name", payload["user"]["full_name"]
end
it "redirects to login on rate limited" do
stub_heroku_api do
#post("/oauth/authorizations") { 401 }
# webmock doesn't handle Excon's :expects, so raise error directly
# until it does
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "unauthorized",
message: "you are not authorized"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::TooManyRequests.new(
"TooManyRequests", nil, response)
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "redirects to login when a user is suspended" do
stub_heroku_api do
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "suspended",
message: "you are suspended"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::UnprocessableEntity.new(
"UnprocessableEntity", nil, response)
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
follow_redirect!
assert_equal 200, last_response.status
assert_match /you are suspended/, last_response.body
end
it "redirects to password reset when a user's password has expired" do
stub_heroku_api do
post("/oauth/authorizations") {
err = MultiJson.encode({
id: "password_expired",
message: "password expired"
})
response = OpenStruct.new(body: err)
raise Excon::Errors::UnprocessableEntity.new(
"UnprocessableEntity", nil, response)
}
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/account/password/reset\z}, last_response.headers["Location"]
end
it "redirects to login on forbidden responses that are not 2fa related" do
stub_heroku_api do
post("/oauth/authorizations") do
err = MultiJson.encode(
id: "forbidden",
message: "Vorboten"
)
response = OpenStruct.new(body: err, headers: {})
raise Excon::Errors::Forbidden.new("Forbidden", nil, response)
end
end
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
follow_redirect!
assert_equal 200, last_response.status
assert_match /Vorboten/, last_response.body
end
describe "exising sessions" do
let(:session_id) { "1234" }
let(:rack_env) do
{
"rack.session" => {
"oauth_session_id" => session_id, "access_token" => "5<PASSWORD>"
}
}
end
it "clears an existing session" do
session_deleted = false
stub_heroku_api do
delete "/oauth/sessions/:id" do
session_deleted = true
status 200
end
end
post "/login",
{ email: "<EMAIL>", password: "<PASSWORD>" }, rack_env
assert session_deleted, "old session must be deleted"
assert_match /^heroku_user_session=(.+)$/, response_cookie,
"it should contain a new session"
refute_match /^heroku_user_session=#{session_id}$/, response_cookie,
"it should not contain the old session"
end
it "ignores missing sessions" do
stub_heroku_api do
delete "/oauth/sessions/:id" do
status 404
end
end
post "/login",
{ email: "<EMAIL>", password: "<PASSWORD>" }, rack_env
assert_equal 302, last_response.status
assert_equal Identity::Config.dashboard_url,
last_response.headers["Location"]
end
it "ignores unauthorized sessions" do
stub_heroku_api do
delete "/oauth/sessions/:id" do
status 401
end
end
post "/login",
{ email: "<EMAIL>", password: "<PASSWORD>" }, rack_env
assert_equal 302, last_response.status
assert_equal Identity::Config.dashboard_url,
last_response.headers["Location"]
end
end
describe "for accounts with two-factor enabled" do
before do
stub_heroku_api do
post("/oauth/authorizations") {
# two-factor challenge!
pass if env["HTTP_HEROKU_TWO_FACTOR_CODE"] == "123456"
# raise a 401 with a header telling the client to ask for the code
response = OpenStruct.new(
headers: { "Heroku-Two-Factor-Required" => "true" })
raise Excon::Errors::Forbidden.new("Forbidden", nil, response)
}
end
end
it "redirects to /login if we have no email or password" do
get "/login/two-factor"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "redirects to /login/two-factor to prompt for the code" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/login/two-factor$}, last_response.headers["Location"]
end
it "redirects to /login/two-factor and hides sms recovery" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
follow_redirect!
assert_equal 200, last_response.status
refute_match /SMS/, last_response.body
end
it "and then posts the authorization again, using the two-factor code" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
follow_redirect!
post "/login", :code => "123456"
assert_equal 302, last_response.status
assert_equal Identity::Config.dashboard_url,
last_response.headers["Location"]
end
end
describe "for users that have previously used an SSO" do
it "removes the sso_entity cookie when successfully logging in" do
post "/login", { email: "<EMAIL>", password: "<PASSWORD>" },
"HTTP_X_FORWARDED_FOR" => "8.7.6.5",
"rack.session" => { "foo" => "bar", "sso_entity" => "initech" }
assert_equal last_request.env["rack.session"]["sso_entity"], nil
end
end
end
describe "for accounts with two-factor and sms recovery enabled" do
it "redirects to /login/two-factor and has sms recovery" do
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
assert_equal 302, last_response.status
follow_redirect!
assert_equal 200, last_response.status
assert_match /SMS/, last_response.body
end
end
describe "DELETE /logout" do
it "responds to GET as well" do
get "/logout"
assert_equal 302, last_response.status
end
it "clears session and redirects to login" do
delete "/logout"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "destroys heroku_* cookies" do
# login to get the heroku cookies in our jar
post "/login", email: "<EMAIL>", password: "<PASSWORD>"
delete "/logout"
assert_includes response_cookie, "heroku_session=;"
assert_includes response_cookie, "heroku_session_nonce=;"
assert_includes response_cookie, "heroku_user_session=;"
end
it "redirects to a given url if it's safe" do
delete "/logout", url: "https://devcenter.heroku.com"
assert_equal 302, last_response.status
assert_match "https://devcenter.heroku.com",
last_response.headers["Location"]
end
it "doesn't redirect to a given url if it's not safe" do
delete "/logout", url: "https://example.com"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
end
private
def response_cookie
last_response.headers["Set-Cookie"]
end
end
|
heroku/identity
|
lib/identity/auth.rb
|
module Identity
class Auth < Sinatra::Base
register ErrorHandling
register HerokuCookie
register Sinatra::Namespace
include Helpers::API
include Helpers::Auth
include Helpers::Log
configure do
set :views, "#{Config.root}/views"
end
before do
@cookie = Cookie.new(env["rack.session"])
@oauth_dance_id = request.cookies["oauth_dance_id"]
end
namespace "/login" do
get do
@campaign = "login" # used to identify the user if they signup from here
@link_account = flash[:link_account] && @cookie.authorize_params
if @link_account
client_id = @cookie.authorize_params["client_id"]
@oauth_client = get_client_info(client_id)
@campaign = get_client_campaign(client_id)
if @oauth_client["trusted"]
@link_account = false
end
end
slim :login, layout: :"layouts/purple"
end
get "/two-factor" do
if @cookie.email && @cookie.password
@sms_number = fetch_sms_number
slim :"two-factor", layout: :"layouts/purple"
else
redirect to("/login")
end
end
# Creates a session for a user by receiving their username and password.
# If that user was trying to authorize an OAuth client before being
# forced to login, that authorization process is continued.
post do
begin
if code = params[:code]
user, pass = @cookie.email, @cookie.password
else
user, pass = params[:email], params[:password]
end
destroy_session
perform_oauth_dance(user, pass, code)
# in special cases, we may have a redirect URL to go to after login
if @cookie.redirect_url
redirect to(@cookie.redirect_url)
# if we know that we're in the middle of an authorization attempt,
# continue it; otherwise go to dashboard
elsif @cookie.authorize_params
authorize(@cookie.authorize_params)
else
redirect to(Config.dashboard_url)
end
# given client_id wasn't found (API throws a 400 status)
rescue Excon::Errors::BadRequest
flash[:error] = "Unknown OAuth client."
redirect to("/login")
# we couldn't track the user's session meaning that it's likely been
# destroyed or expired, redirect to login
rescue Excon::Errors::NotFound
# clear a bad set of parameters in the session
@cookie.authorize_params = nil
redirect to("/login")
# two-factor auth is required
rescue Excon::Errors::Forbidden => e
if e.response.headers.has_key?("Heroku-Two-Factor-Required")
@cookie.email = user
@cookie.password = <PASSWORD>
redirect to("/login/two-factor")
else
flash[:error] = decode_error(e.response.body)
redirect to("/login")
end
# oauth dance or post-dance authorization was unsuccessful
rescue Excon::Errors::Unauthorized
flash[:error] = "There was a problem with your login."
redirect to("/login")
rescue Excon::Errors::TooManyRequests
flash[:error] = "Account reached login rate limit, please wait a few minutes before trying again"
redirect to("/login")
rescue Identity::Errors::PasswordExpired => e
flash[:error] = e.message
redirect to("/account/password/reset")
rescue Identity::Errors::SuspendedAccount => e
flash[:error] = e.message
redirect to("/login")
# client not yet authorized; show the user a confirmation dialog
rescue Identity::Errors::UnauthorizedClient => e
@client = e.client
@scope = @cookie && @cookie.authorize_params["scope"] || nil
slim :"clients/authorize", layout: :"layouts/purple"
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
flash[:error] = decode_error(e.response.body)
redirect to("/login")
end
end
end
namespace "/logout" do
get do
# same as DELETE
call(env.merge("REQUEST_METHOD" => "DELETE"))
end
delete do
begin
destroy_session
ensure
logout
end
end
end
namespace "/oauth" do
# OAuth 2 spec stipulates that the authorize endpoint MUST support GET
# (but that also means be very wary of CSRF):
#
# http://tools.ietf.org/html/rfc6749#section-3.1
get "/authorize" do
redirect_or_authorize
end
if Identity::Config.development?
get "/authorize/dev" do
@client = {"name" => "Test Client"}
@scope = [
"create-apps",
"global",
"identity",
"read",
"read-protected",
"write",
"write-protected",
]
slim :"clients/authorize", layout: :"layouts/purple"
end
end
# Tries to authorize a user for a client by proxying the authorization
# request to API. If the user is not logged in, they are sent to the
# login screen, from where this authorization will be reattempted on a
# successful login. If Identity's access token has expired, it is
# refreshed.
post "/authorize" do
redirect_or_authorize
end
# Exchanges a code and client_secret for a token set by proxying the
# request to the API.
post "/token" do
begin
res = log :create_token, by_proxy: true,
session_id: @cookie.session_id do
Rack::Auth::Basic::Request.new(request.env)
# no credentials are required here because the code segment of the
# exchange is state that's linked to a user in the API
api = HerokuAPI.new(ip: request.ip, request_ids: request_ids,
version: 3)
api.post(path: "/oauth/tokens", expects: 201,
body: MultiJson.encode({
client: {
secret: client_secret
},
grant: {
code: params[:code],
type: params[:grant_type] || "authorization_code",
},
refresh_token: {
token: params[:refresh_token]
},
}))
end
token = MultiJson.decode(res.body)
content_type(:json)
status(200)
response = {
# core spec response
access_token: token["access_token"]["token"],
expires_in: token["access_token"]["expires_in"],
refresh_token: token["refresh_token"]["token"],
token_type: "Bearer",
# heroku extra response
user_id: token["user"]["id"],
session_nonce: token["session"].try(:[], "id")
}
# some basic sanity checks
raise "missing=access_token" unless response[:access_token]
raise "missing=expires_in" unless response[:expires_in]
raise "missing=refresh_token" unless response[:refresh_token]
# WARNING: some users appear to have nil nonces
#raise "missing=session_nonce" unless response[:session_nonce]
MultiJson.encode(response)
# Handle 4xx errors from API
rescue Identity::Errors::SuspendedAccount => e
content_type(:json)
[403, e.message]
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
# pass the whole API error through to the client
content_type(:json)
[e.response.status, e.response.body]
end
end
end
private
def redirect_or_authorize
if redirect_to_sso?
@cookie.authorize_params = get_authorize_params
redirect to("#{Config.sso_base_url}/#{@cookie.sso_entity}")
elsif !@cookie.access_token || params[:prompt] == "login"
# Have users login if they don't have a session, or the client
# has requested an explicit login
flash[:link_account] = true
@cookie.post_signup_url = request.url
@cookie.authorize_params = get_authorize_params
redirect to("/login")
else
# Otherwise, perform the authorization
call_authorize
end
end
def redirect_to_sso?
# If the user uses SSO and SSO is configured in Identity, continue on to
# check if their access token is valid.
return false unless @cookie.sso_entity && Config.sso_base_url
return true unless @cookie.access_token
# Check if their current access token is valid.
api = Identity::HerokuAPI.new(pass: @cookie.access_token,
ip: request.ip,
request_ids: request_ids,
version: 3)
api.get(path: "/account").status != 200
end
def flash
request.env["x-rack.flash"]
end
def client_secret
# per RFC 6749 section 2.3.1, token endpoint must accept basic auth
req = Rack::Auth::Basic::Request.new(request.env)
if req.provided? && req.basic?
# credentials contain the client ID (user) and the client secret (pass)
_, client_secret = req.credentials
client_secret
else
# if it's not is basic auth, hopefully it's in the request body
params[:client_secret]
end
end
def get_client_info(client_id)
api = HerokuAPI.new(ip: request.ip, version: 3)
res = api.get(
expects: 200,
path: "/oauth/clients/#{client_id}")
MultiJson.decode(res.body)
end
# hardcoded for now :{ we can potentially move this to API at some point,
# but will need some sort of service to issue salesforce campaign ids
def get_client_campaign(oauth_client_id)
{
Identity::Config.parse_oauth_client_id => "parse",
}[oauth_client_id] || "login"
end
def safe_redirect?(url)
uri = URI.parse(url)
# possibly move this to a config var if it starts ballooning out of
# control
[
"addons.heroku.com",
"addons-staging.heroku.com",
"api.heroku.com",
"api.staging.herokudev.com",
"devcenter.heroku.com",
"devcenter-staging.heroku.com",
"discussion.heroku.com",
].include?(uri.host)
rescue URI::InvalidURIError
false
end
end
end
|
heroku/identity
|
lib/identity/helpers/api.rb
|
<filename>lib/identity/helpers/api.rb<gh_stars>10-100
module Identity::Helpers
module API
def decode_error(body)
json = MultiJson.decode(body)
if json.is_a?(Hash)
# use the message field, otherwise munge the errors together
json["message"] || json.map { |e| e.join(" ") }.join("; ")
end
rescue MultiJson::DecodeError
# V2 logs some special cases, like 404s, as plain text
log :decode_error, body: body
body
end
def fetch_sms_number
return unless @cookie.email && @cookie.password
options = {
ip: request.ip,
request_ids: request_ids,
user: @cookie.email,
pass: <PASSWORD>,
version: "3",
}
api = Identity::HerokuAPI.new(options)
res = api.get(path: "/users/~/sms-number",
expects: 200)
MultiJson.decode(res.body)["sms_number"]
rescue
nil
end
end
end
|
heroku/identity
|
test/helpers/api_test.rb
|
require_relative "../test_helper"
describe Identity::Helpers::API do
include Identity::Helpers::API
describe :decode_error do
before do
stub(self).log
end
it "returns the message value for v3 error messages" do
error = {
id: "rate_limit",
message: "Please wait a few minutes before making new requests"
}
assert_equal error[:message], decode_error(MultiJson.encode(error))
end
it "merges any other hashes it gets back" do
error = {
id: "wat",
error: "something weird"
}
assert_equal "id wat; error something weird",
decode_error(MultiJson.encode(error))
end
it "falls through in the case of decoding errors" do
assert_equal "that's some error", decode_error("that's some error")
end
end
end
|
heroku/identity
|
test/service_stubs.rb
|
require_relative "service_stubs/heroku_api_stub"
def stub_service(uri, stub, &block)
uri = URI.parse(uri)
port = uri.port != uri.default_port ? ":#{uri.port}" : ""
stub = block ? Sinatra.new(stub, &block) : stub
stub_request(:any, /^#{uri.scheme}:\/\/(.*:.*@)?#{uri.host}#{port}\/.*$/).
to_rack(stub)
end
def stub_heroku_api(&block)
stub_service(Identity::Config.heroku_api_url, HerokuAPIStub, &block)
end
|
heroku/identity
|
test/account_test.rb
|
require_relative "test_helper"
describe Identity::Account do
include Rack::Test::Methods
def app
Rack::Builder.new do
use Rack::Session::Cookie, secret: "my-secret"
use Rack::Flash
run Identity::Account
end
end
before do
stub_heroku_api
rack_mock_session.clear_cookies
end
describe "GET /account/accept/:id/:token" do
it "redirects to the same path in the signup app" do
stub(Identity::Config).redirect_all_signups { true }
get "/account/accept/123/456abc"
assert_equal 302, last_response.status
assert_equal "#{Identity::Config.signup_url}/account/accept/123/456abc?from=id", last_response.headers["Location"]
end
end
describe "POST /account/accept/ok" do
it "redirects to the signup app on success" do
stub(Identity::Config).redirect_all_signups { true }
post "/account/accept/ok", token: "foo"
assert_equal 302, last_response.status
assert_equal "#{Identity::Config.signup_url}/account/accept/ok?from=id", last_response.headers["Location"]
end
it "redirects to login if the token is not found" do
stub_heroku_api do
patch "/invitations/:token" do
halt(404, "Not found")
end
end
post "/account/accept/ok", token: "foo"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "redirects to accept if the invitation data is wrong" do
stub_heroku_api do
patch "/invitations/:token" do
[422, MultiJson.encode(message: "Password too short.")]
end
end
post "/account/accept/ok", token: "foo", password: "<PASSWORD>", id: 123
assert_equal 302, last_response.status
assert_match(
%r{/account/accept/123/foo$}, last_response.headers["Location"])
end
end
describe "GET /account/accept/ok" do
it "redirects to the signup app" do
get "/account/accept/ok"
assert_equal 302, last_response.status
assert_equal "#{Identity::Config.signup_url}/account/accept/ok?from=id", last_response.headers["Location"]
end
end
describe "GET /account/email/confirm/:token" do
it "requires login" do
get "/account/email/confirm/c45685917ef644198a0fececa10d479a"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "redirects to dashboard on a successful confirmation" do
any_instance_of(Identity::Cookie) do |cookie|
stub(cookie).access_token { "abc<PASSWORD>" }
end
get "/account/email/confirm/c45685917ef644198a0fececa10d479a"
assert_equal 302, last_response.status
assert_match Identity::Config.dashboard_url,
last_response.headers["Location"]
end
it "shows a helpful page for a token that wasn't found" do
any_instance_of(Identity::Cookie) do |cookie|
stub(cookie).access_token { "abc<PASSWORD>" }
end
stub_heroku_api do
patch "/users/~" do
halt(404, "Not found")
end
end
get "/account/email/confirm/c45685917ef644198a0fececa10d479a"
assert_equal 404, last_response.status
assert_match(/couldn't find that e-mail/, last_response.body)
end
end
describe "GET /account/password/reset" do
it "shows a reset password form" do
get "/account/password/reset"
assert_equal 200, last_response.status
end
end
describe "POST /account/password/reset" do
it "requests a password reset" do
stub_heroku_api
post "/account/password/reset", email: "<EMAIL>"
assert_equal 200, last_response.status
refute last_request.env["x-rack.flash"]["notice"].nil?
end
it "redirects when the api responded with an error" do
stub_heroku_api do
post "/password-resets" do
[422, MultiJson.encode(message: "Fail")]
end
end
post "/account/password/reset", email: "<EMAIL>"
assert_equal 302, last_response.status
assert last_response.headers["Location"] =~ %r{/account/password/reset$}
end
end
describe "GET /account/password/reset/:token" do
it "renders a password reset form" do
get "/account/password/reset/<PASSWORD>"
assert_equal 200, last_response.status
end
end
describe "POST /account/password/reset/:token" do
it "changes a password and redirects to login" do
stub_heroku_api
post "/account/password/reset/<PASSWORD>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/login$}, last_response.headers["Location"]
end
it "renders a not found page when there's a 404 error from API" do
stub_heroku_api do
post "/password-resets/:token/actions/finalize" do
[404, MultiJson.encode(message: "Not Found")]
end
end
post "/account/password/reset/<PASSWORD>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>"
assert_equal 404, last_response.status
end
[ 403, 422 ].each do |error_code|
it "redirects back to reset page when there's a #{error_code} error" do
stub_heroku_api do
post "/password-resets/:token/actions/finalize" do
[error_code, MultiJson.encode(message: "a #{error_code} error")]
end
end
post "/account/password/reset/<PASSWORD>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>"
assert_equal 302, last_response.status
assert_match %r{/account/password/reset/<PASSWORD>$}, last_response.headers["Location"]
follow_redirect!
assert_match(/a #{error_code} error/, last_response.body)
end
end
end
describe "GET /signup" do
it "redirects to the root of the signup app" do
get "/signup"
assert_equal 301, last_response.status
assert_equal "#{Identity::Config.signup_url}?from=id", last_response.headers["Location"]
end
end
describe "GET /signup/:slug" do
it "redirects to the same slug in the signup app" do
get "/signup/foo"
assert_equal 301, last_response.status
assert_equal "#{Identity::Config.signup_url}/foo?from=id",
last_response.headers["Location"]
end
it "sets the redirect-url so the user is taken back when authorizing a client" do
url = "https://id.heroku.com/oauth/authorize/1234"
rack_env = {
# set a cookie
"rack.session" => { "post_signup_url" => url }
}
get "/signup/foo", {}, rack_env
expected_params = {
"from" => "id",
"redirect-url" => url
}
encoded_params = URI.encode_www_form(expected_params)
assert_equal 301, last_response.status
assert_equal "#{Identity::Config.signup_url}/foo?#{encoded_params}",
last_response.headers["Location"]
end
it "scrub cr character" do
get "/signup/%0dSet-Cookie:mycookie=myvalue"
assert_equal 301, last_response.status
assert_equal "#{Identity::Config.signup_url}/Set-Cookie:mycookie=myvalue?from=id",
last_response.headers["Location"]
end
it "scrub crlf characters" do
get "/signup/%0d%0aSet-Cookie:mycookie=myvalue"
assert_equal 301, last_response.status
assert_equal "#{Identity::Config.signup_url}/Set-Cookie:mycookie=myvalue?from=id",
last_response.headers["Location"]
end
end
describe "GET /account/two-factor/recovery" do
it "renders a recovery form" do
get "/account/two-factor/recovery"
assert_equal 200, last_response.status
refute_match /code via SMS/, last_response.body
end
it "renders a recovery form with SMS if present" do
get "/account/two-factor/recovery", {}, 'rack.session' => { :email => '<EMAIL>', :password => '' }
assert_equal 200, last_response.status
assert_match /code via SMS/, last_response.body
end
end
describe "GET /account/two-factor/recovery/sms" do
it "renders a sms recovery form" do
get "/account/two-factor/recovery/sms", {}, 'rack.session' => { :email => '<EMAIL>', :password => '' }
assert_equal 200, last_response.status
assert_match /\+1 \*\*\* 1234/, last_response.body
assert_match /Resend SMS/, last_response.body
end
end
describe "POST /account/two-factor/recovery/sms" do
it "redirects back to two-factor if number missing" do
stub_heroku_api do
post("/users/~/sms-number/actions/recover") {
[422, MultiJson.encode({ message: "Number missing." })]
}
end
post "/account/two-factor/recovery/sms"
assert_equal 302, last_response.status
assert_match %r{/login/two-factor$}, last_response.headers["Location"]
end
end
end
|
heroku/identity
|
lib/identity/fernet_cookie_coder.rb
|
require "base64"
require "rack/session/cookie"
module Identity
class FernetCookieCoder
def initialize(*keys)
@keys = keys.compact
end
def encode(raw)
# use Marshal instead of JSON to avoid trouble with string/symbol
# conversions
data = Base64.urlsafe_encode64(Marshal.dump(raw))
# for new session, we always encode with the latest `fernet`
Fernet.generate(@keys.first, data)
end
def decode(cipher)
return {} if cipher == nil
# There can be URL encoded characters
# from the cookies
cipher = CGI::unescape(cipher)
plain = nil
@keys.each do |key|
begin
plain = decode_with_key(cipher, key)
rescue OpenSSL::Cipher::CipherError
end
break if plain
end
raise "no valid encryption key for cipher" if !plain
plain
# fernet throws random exceptions :{ eat it for now
rescue Exception => e
Identity.log(:exception,
class: e.class.name,
message: e.message,
fernet: true,
backtrace: e.backtrace.inspect)
{}
end
private
def decode_with_key(cipher, key)
decode_with_latest_fernet(cipher, key) ||
decode_with_legacy_fernet(cipher, key)
end
def decode_with_legacy_fernet(cipher, key)
legacy_verifier = LegacyFernet.verifier(key, cipher)
legacy_verifier.enforce_ttl = false
legacy_verifier.verify_token(cipher)
if legacy_verifier.valid?
Identity.log(:legacy,
message: "Decoding with legacy fernet",
legacy_fernet: true)
return Marshal.load(
Base64.urlsafe_decode64(legacy_verifier.data["session"])
)
end
rescue
# mute any exception and let latest fernet to try again
# see `decode_with_latest_fernet`
end
def decode_with_latest_fernet(cipher, key)
verifier = Fernet.verifier(key, cipher)
verifier.enforce_ttl = false
return nil unless verifier.valid?
Marshal.load(Base64.urlsafe_decode64(verifier.message))
end
end
end
|
heroku/identity
|
lib/identity/rescue_errors.rb
|
<reponame>heroku/identity
module Identity
class RescueErrors
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
rescue Exception => e
Identity.log(:exception, class: e.class.name, message: e.message,
backtrace: e.backtrace.inspect)
[500, { 'Content-Type' => 'text/html', 'Content-Length' => '0' }, []]
end
end
end
|
heroku/identity
|
test/csrf_test.rb
|
<reponame>heroku/identity
require_relative "test_helper"
describe Identity::CSRF do
include Rack::Test::Methods
def app
Sinatra.new do
use Rack::Session::Cookie, domain: "example.org", secret: "my-secret"
use Identity::CSRF
get "/good" do
200
end
get "/bad" do
raise Rack::Csrf::InvalidCsrfToken
end
end
end
it "falls through normally" do
get "/good"
assert_equal 200, last_response.status
end
it "responds with a 403 on a bad CSRF request" do
get "/bad"
assert_equal 403, last_response.status
end
it "logs certain request information" do
mock(Identity).log(:invalid_csrf_token, anything)
get "/bad"
end
end
|
heroku/identity
|
lib/identity/account.rb
|
require "addressable/uri"
require 'cgi'
module Identity
class Account < Sinatra::Base
register ErrorHandling
register HerokuCookie
register Sinatra::Namespace
include Helpers::API
include Helpers::Auth
include Helpers::Log
configure do
set :views, "#{Config.root}/views"
end
before do
@cookie = Cookie.new(env["rack.session"])
@oauth_dance_id = request.cookies["oauth_dance_id"]
end
namespace "/account" do
get "/accept/:id/:token" do |id, token|
redirect_to_signup_app(request.path)
end
# This endpoint is unreachable except if a user manually hits it by
# manipulating their browser during the signup process.
get "/accept/ok" do
redirect_to_signup_app(request.path)
end
# This endpoint is NOT protected against CSRF, because the signup app needs it
# to verify and log the user in.
post "/accept/ok" do
begin
api = HerokuAPI.new(
ip: request.ip,
request_ids: request_ids,
version: 3)
res = api.patch(
path: "/invitations/#{params[:token]}",
expects: 200,
body: MultiJson.encode(
password: <PASSWORD>[:password],
password_confirmation: params[:<PASSWORD>],
receive_newsletter: params[:receive_newsletter]
))
json = MultiJson.decode(res.body)
# log the user in right away
perform_oauth_dance(json["user"]["email"], params[:password], nil)
@redirect_uri = if @cookie.authorize_params
# if we know that we're in the middle of an authorization attempt,
# continue it
authorize(@cookie.authorize_params)
# users who signed up from a particular source may have a specialized
# redirect location; otherwise go to Dashboard
else
redirect_to_signup_app(request.path)
end
# given client_id wasn't found (API throws a 400 status)
rescue Excon::Errors::BadRequest
flash[:error] = "Unknown OAuth client."
redirect to("/login")
# we couldn't track the user's session meaning that it's likely been
# destroyed or expired, redirect to login
rescue Excon::Errors::NotFound
redirect to("/login")
# refresh token dance was unsuccessful
rescue Excon::Errors::Unauthorized
redirect to("/login")
# client not yet authorized; show the user a confirmation dialog
rescue Identity::Errors::UnauthorizedClient => e
@client = e.client
@scope = @cookie && @cookie.authorize_params["scope"] || nil
slim :"clients/authorize", layout: :"layouts/purple"
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
flash[:error] = decode_error(e.response.body)
redirect to("/account/accept/#{params[:id]}/#{params[:token]}")
end
end
get "/email/confirm/:token" do |token|
begin
# confirming an e-mail change requires authentication
raise Identity::Errors::LoginRequired unless @cookie.access_token
api = HerokuAPI.new(
user: nil,
pass: <PASSWORD>,
ip: request.ip,
request_ids: request_ids,
version: 3)
api.patch(
path: "/users/~",
expects: 200,
body: MultiJson.encode(email_change_token: params[:token]))
redirect to(Config.dashboard_url)
# user tried to access the change e-mail request under the wrong
# account
rescue Excon::Errors::Forbidden
flash[:error] = "This link can't be used with your current login."
redirect to("/login")
rescue Excon::Errors::NotFound, Excon::Errors::UnprocessableEntity
status 404
slim :"account/email/not_found", layout: :"layouts/purple"
# it seems that the user's access token is no longer valid, refresh
rescue Excon::Errors::Unauthorized
begin
perform_oauth_refresh_dance
redirect to(request.path_info)
# refresh dance unsuccessful
rescue Excon::Errors::Unauthorized
redirect to("/logout")
end
rescue Identity::Errors::LoginRequired
@cookie.redirect_url = request.env["PATH_INFO"]
redirect to("/login")
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
flash[:error] = decode_error(e.response.body)
redirect to("/login")
end
end
get "/password/reset" do
slim :"account/password/reset", layout: :"layouts/purple"
end
post "/password/reset" do
begin
api = HerokuAPI.new(
ip: request.ip,
request_ids: request_ids,
version: 3)
api.post(
path: "/password-resets",
body: MultiJson.encode(email: params[:email]),
expects: 201)
flash.now[:notice] =
"Check your inbox for the next steps.\n"\
"If you don't receive an email, and it's not in your spam folder "\
"this could mean you signed up with a different address."
slim :"account/password/reset", layout: :"layouts/purple"
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
flash[:error] = decode_error(e.response.body)
redirect to("/account/password/reset")
end
end
get "/password/reset/:token" do |token|
slim :"account/password/finish_reset", layout: :"layouts/purple"
end
post "/password/reset/:token" do |token|
begin
api = HerokuAPI.new(
ip: request.ip,
request_ids: request_ids,
version: 3)
body = MultiJson.encode(
password: params[:password],
password_confirmation: params[:password_confirmation],
)
api.post(
path: "/password-resets/#{token}/actions/finalize",
expects: 200,
body: body)
flash[:success] = "Your password has been changed."
redirect to("/login")
rescue Excon::Errors::NotFound => e
status 404
slim :"account/password/not_found", layout: :"layouts/purple"
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
Identity.log(
password_reset_error: true,
error_body: e.response.body,
error_code: e.response.status)
@user = flash[:user]
flash[:error] = decode_error(e.response.body)
redirect to("/account/password/reset/#{token}")
end
end
get "/two-factor/recovery" do
@sms_number = fetch_sms_number
slim :"account/two-factor/recovery", layout: :"layouts/purple"
end
post "/two-factor/recovery/sms" do
options = {
ip: request.ip,
request_ids: request_ids,
user: @cookie.email,
pass: <PASSWORD>,
version: "3",
}
begin
api = HerokuAPI.new(options)
api.post(path: "/users/~/sms-number/actions/recover", expects: 201)
# catch-all for generic 4xx errors
rescue Excon::Errors::ClientError => e
flash[:error] = decode_error(e.response.body)
redirect to("/login/two-factor")
end
redirect to("/account/two-factor/recovery/sms")
end
get "/two-factor/recovery/sms" do
@sms_number = fetch_sms_number
slim :"account/two-factor/recovery_sms", layout: :"layouts/purple"
end
end
get "/signup" do
redirect_to_signup_app("", 301)
end
get "/signup/:slug" do |slug|
redirect_to_signup_app("/#{params[:slug]}", 301)
end
private
# Redirects to the signup app adding a special param
def redirect_to_signup_app(next_path, code = 302)
current_params = CGI.parse(URI.parse(request.fullpath).query.to_s)
append_params = { from: 'id' }
if redirect_url = @cookie.post_signup_url
append_params["redirect-url"] = redirect_url
end
next_params = URI.encode_www_form(current_params.merge(append_params))
next_path = next_path.gsub(/[\r\n]/, "")
redirect to("#{Config.signup_url}#{next_path}?#{next_params}"), code
end
end
end
|
heroku/identity
|
config.ru
|
<gh_stars>10-100
$stdout.sync = $stderr.sync = true
require "bundler/setup"
Bundler.require
require "./lib/identity"
#
# initialization/configuration
#
Rollbar.configure do |config|
config.disable_monkey_patch = true
config.access_token = Identity::Config.rollbar_access_token
config.enabled = !Identity::Config.rollbar_access_token.nil?
config.environment = ENV["RACK_ENV"]
config.root = Identity::Config.root
end
Excon.defaults[:ssl_verify_peer] = Identity::Config.ssl_verify_peer?
Slim::Engine.set_default_options pretty: !Identity::Config.production?
run Identity::Main
|
heroku/identity
|
lib/identity/robots.rb
|
module Identity
class Robots < Sinatra::Base
register ErrorHandling
get "/robots.txt" do
content_type :text
<<-eos
# Won't actually prevent these folders from appearing in a search engine's
# index, but isn't really harmful either.
User-agent: *
Disallow: /account/email/confirm/
Disallow: /account/password/reset/
eos
end
end
end
|
heroku/identity
|
test/identity_assertions.rb
|
<gh_stars>10-100
def assert_response_redirects_with_oauth_callback(state: nil)
assert_equal 302, last_response.status
base = HerokuAPIStub::AUTHORIZATION[:client][:redirect_uri]
code = HerokuAPIStub::AUTHORIZATION[:grant][:code]
state = !state.nil? ? "&state=#{state}" : ""
assert_equal "#{base}?code=#{code}#{state}", last_response.headers["Location"]
end
|
heroku/identity
|
lib/identity/default.rb
|
<reponame>heroku/identity<gh_stars>10-100
module Identity
class Default < Sinatra::Base
register ErrorHandling
register HerokuCookie
configure do
set :views, "#{Config.root}/views"
end
before do
@cookie = Cookie.new(env["rack.session"])
end
get "/" do
if @cookie.access_token
redirect to(Config.dashboard_url)
else
redirect to("/login")
end
end
not_found do
slim :"errors/404", layout: :"layouts/purple"
end
end
end
|
heroku/identity
|
lib/identity/login_external.rb
|
# This defines an endpoint for external services such as Fido (Federated
# Identity) and signup.heroku.com so that they can use their own method for
# authentication and set cookies in identity.
# The endpoint is protected by a shared secret.
module Identity
class LoginExternal < Default
register Sinatra::Namespace
include Helpers::Auth
namespace "/login/external" do
before do
halt 404 unless shared_key
end
get do
token = params[:token]
auth, _ = JWT.decode(token, shared_key)
destroy_session
write_authentication_to_cookie auth
# If the user has an active client oauth request, try to finish it.
# Otherwise, send the user to dashboard.
if auth_params = @cookie.authorize_params
call_authorize(auth_params)
else
redirect to(Config.dashboard_url)
end
end
error JWT::DecodeError do
handle_error 401
end
end
private
def shared_key
Config.login_external_secret
end
end
end
|
heroku/identity
|
lib/identity/errors.rb
|
<reponame>heroku/identity
module Identity::Errors
class LoginRequired < StandardError; end
class PasswordExpired < StandardError
attr_accessor :message
def initialize(_)
# Override this message so that the user doesn't see a URL that they're
# supposed to visit. Instead, just take them directly to the write place.
@message = <<-eos.strip
Your password has expired. Please reset it.
eos
end
end
class UnauthorizedClient < StandardError
attr_accessor :client
def initialize(client)
@client = client
end
end
class SuspendedAccount < StandardError
attr_accessor :message
def initialize(msg)
@message = msg
end
end
end
|
heroku/identity
|
lib/identity/design.rb
|
<filename>lib/identity/design.rb
# To test a new design layout called `foo`:
# - add a view in `views/layouts/foo.slim`
# - replicate the design links adding `?layout=foo`
module Identity
class Design < Sinatra::Base
register Sinatra::Namespace
configure do
set :views, "#{Config.root}/views"
end
before do
flash[:error] = nil
@layout = params[:layout] ? :"layouts/#{params[:layout]}" : :"layouts/purple"
end
namespace "/design" do
get "/login" do
if params[:client]
flash.now[:link_account] = true
@oauth_client = { "name" => params[:client] }
end
slim :"login", layout: @layout
end
get "/login-flash" do
flash[:error] = "There was a problem with your login."
slim :"login", layout: @layout
end
get "/two-factor" do
@sms_number = '+1 *** *** 1234'
slim :"two-factor", layout: @layout
end
get "/two-factor/recovery" do
@sms_number = '+1 *** *** 1234'
slim :"account/two-factor/recovery", layout: @layout
end
get "/two-factor/recovery/sms" do
@sms_number = '+1 *** *** 1234'
slim :"account/two-factor/recovery_sms", layout: @layout
end
get "/errors/:error" do # 404, 500, 503
slim :"errors/#{params['error']}", layout: @layout
end
get "/authorize" do
@client = { "name" => "An example app"}
slim :"clients/authorize", layout: @layout
end
namespace "/password" do
get "/finish-reset" do
@user = { "email" => "<EMAIL>"}
slim :"account/password/finish_reset", layout: @layout
end
get "/not-found" do
slim :"account/password/not_found", layout: @layout
end
get "/reset" do
slim :"account/password/reset", layout: @layout
end
end
get "*" do
slim :"design/index"
end
end
def client_deny_url
"https://id.heroku.com/#deny"
end
end
end
|
heroku/identity
|
lib/identity/main.rb
|
module Identity
Main = Rack::Builder.new do
use Identity::RescueErrors
use Rack::Instruments,
context: { app: "identity" },
response_request_id: true
use Rack::SSL if Config.production?
use Rack::Deflater
# General cookie storing information of the logged in user; don't set the
# domain so that it's allowed to default to the current app's domain scope.
use Rack::Session::Cookie,
coder: FernetCookieCoder.new(
Config.cookie_encryption_key,
Config.old_cookie_encryption_key),
http_only: true,
path: '/',
expire_after: Config.cookie_expire_after,
key: 'identity-session'
# CSRF + Flash should come before the unadorned heroku cookies that follow
use Identity::CSRF, skip: [
# skip CSRF for POST /oauth/token (the second step of a standard OAuth
# flow)
"POST:/oauth/token",
# skip CSRF for POST /account/accept/ok (where users confirm their account
# and set their password) so Dev Center can submit this form from a
# different app and provide a different on-boarding experience.
# It seems dangerous, but the form can only be used once and needs
# a unique user_id / token combination to work that is only shared with
# the user's email address after signing up.
"POST:/account/accept/ok"
]
use Rack::Flash
run Sinatra::Router.new {
mount Account
mount Assets
mount Auth
mount Design if Config.development?
mount LoginExternal
mount Robots
run Default # index + error handlers
}
end
end
|
heroku/identity
|
lib/identity/helpers/auth.rb
|
<reponame>heroku/identity
module Identity::Helpers
module Auth
include Log
include API
# Performs the authorization step of the OAuth dance against the Heroku
# API.
def authorize(params, confirm=false)
api = Identity::HerokuAPI.new(
pass: <PASSWORD>,
ip: request.ip,
request_ids: request_ids,
version: 3,
headers: {
# must ask for legacy IDs to get `legacy_id` field below
"X-Heroku-Legacy-Ids" => "true"
})
client_id = params["client_id"]
halt 400, "Need client_id" if client_id.nil? || client_id.empty?
res = log :get_client, client_id: client_id do
api.get(path: "/oauth/clients/#{client_id}", expects: 200)
end
client = MultiJson.decode(res.body)
# if the account is set to delinquent, and the client does not ignore
# delinquency, then redirect to the pay-balance page, which is given to
# us in the `Location` header
if res.headers["Heroku-Delinquent"] == "true" &&
!client["ignores_delinquent"]
redirect to(res.headers["Location"])
end
# if the client is not trusted, then see if the user has already
# authorized it
if !client["trusted"]
res = log :get_authorizations do
api.get(path: "/oauth/authorizations", expects: [200, 401],
headers: { "Range" => "id ..; max=1000" })
end
logout if res.status == 401
authorizations = MultiJson.decode(res.body)
authorization = authorizations.detect { |a|
a["client"] &&
a["client"]["id"] == client_id &&
a["scope"] == (params["scope"] || ["global"])
}
# fall back to legacy_id (for now)
if !authorization
authorization = authorizations.detect { |a|
a["client"] &&
a["client"]["legacy_id"] &&
a["client"]["legacy_id"] == client_id &&
a["scope"] == (params["scope"] || ["global"])
}
if authorization
log(:legacy_client_id, client_id: authorization["client"]["id"])
end
end
# if there is no authorization raise an error so that we can show a
# confirmation dialog to the user
#
# SECURITY NOTE: the confirm parameter is *only* respected if the
# request came in on a POST, otherwise a CSRF attack is possible
if !authorization && (!confirm || request.request_method != "POST")
raise Identity::Errors::UnauthorizedClient.new(client)
end
end
res = log :create_authorization, by_proxy: true,
client_id: params["client_id"], session_id: @cookie.session_id do
api.post(path: "/oauth/authorizations", expects: [201, 401],
body: MultiJson.encode({
client: { id: params["client_id"] },
scope: params["scope"],
response_type: params["response_type"],
session: { id: @cookie.session_id },
}))
end
logout if res.status == 401
# successful authorization, clear any params in session
@cookie.authorize_params = nil
authorization = MultiJson.decode(res.body)
redirect_params = { code: authorization["grant"]["code"] }
redirect_params.merge!(state: params["state"]) if params["state"]
uri = build_uri(authorization["client"]["redirect_uri"], redirect_params)
log :redirecting, uri: uri
redirect to(uri)
end
# merges extra params into a base URI
def build_uri(base, params)
uri = URI.parse(base)
uri_params = Rack::Utils.parse_query(uri.query).merge(params)
uri.query = Rack::Utils.build_query(uri_params)
uri.to_s
end
# Performs the complete OAuth dance against the Heroku API in order to
# provision an identity client token that can be used by Identity to manage
# the user's client identities.
def perform_oauth_dance(user, pass, otp_code)
log :oauth_dance do
options = {
headers: {},
ip: request.ip,
pass: <PASSWORD>,
request_ids: request_ids,
user: user,
version: 3,
}
if otp_code
options[:headers].merge!({ "Heroku-Two-Factor-Code" => otp_code })
end
api = Identity::HerokuAPI.new(options)
auth = nil
begin
res = log :create_authorization, user: user do
api.post(path: "/oauth/authorizations", expects: 201,
body: MultiJson.encode({
client: { id: Identity::Config.heroku_oauth_id },
create_session: true,
create_tokens: true,
response_type: "code",
}))
end
auth = MultiJson.decode(res.body)
end
write_authentication_to_cookie auth
log :oauth_dance_complete, session_id: @cookie.session_id, user: user
end
end
# Attempts to refresh a user's access token using a known refresh token.
def perform_oauth_refresh_dance
log :oauth_refresh_dance do
res = log :refresh_token do
api = Identity::HerokuAPI.new(ip: request.ip,
request_ids: request_ids, version: 3)
api.post(path: "/oauth/tokens", expects: 201,
body: MultiJson.encode({
client: { secret: Identity::Config.heroku_oauth_secret },
grant: { type: "refresh_token" },
refresh_token: { token: @cookie.refresh_token },
}))
end
# store appropriate tokens to session
token = MultiJson.decode(res.body)
@cookie.access_token = token["access_token"]["token"]
@cookie.access_token_expires_at =
Time.now.getlocal + token["access_token"]["expires_in"]
raise "missing=access_token" unless @cookie.access_token
raise "missing=expires_in" unless @cookie.access_token_expires_at
log :oauth_refresh_dance_complete, session_id: @cookie.session_id
end
end
# Attempt to resolve an oauth/authorize request
def call_authorize(authorize_params = get_authorize_params)
# clear anything that might be left over in the session
@cookie.authorize_params = nil
begin
# Try to perform an access token refresh if we know it's expired. At
# the time of this writing, refresh tokens last 30 days (much longer
# than the short-lived 2 hour access tokens).
if Time.now.getlocal > @cookie.access_token_expires_at
perform_oauth_refresh_dance
end
# redirects back to the oauth client on success
authorize(authorize_params, params[:authorize] == "Allow")
# given client_id wasn't found (API throws a 400 status)
rescue Excon::Errors::BadRequest
flash[:error] = "Unknown OAuth client."
redirect to("/login")
# we couldn't track the user's session meaning that it's likely been
# destroyed or expired, redirect to login
rescue Excon::Errors::NotFound
redirect to("/login")
# user needs to login.
rescue Identity::Errors::LoginRequired
flash[:link_account] = true
@cookie.post_signup_url = request.url
@cookie.authorize_params = authorize_params
redirect to("/login")
# refresh token dance was unsuccessful
rescue Excon::Errors::Unauthorized
@cookie.authorize_params = authorize_params
redirect to("/login")
rescue Identity::Errors::PasswordExpired => e
flash[:error] = e.message
redirect to("/account/password/reset")
rescue Identity::Errors::SuspendedAccount => e
flash[:error] = e.message
redirect to("/login")
# client not yet authorized; show the user a confirmation dialog
rescue Identity::Errors::UnauthorizedClient => e
@cookie.authorize_params = authorize_params
@client = e.client
@scope = @cookie && @cookie.authorize_params["scope"] || nil
slim :"clients/authorize", layout: :"layouts/purple"
# for example, "invalid scope"
rescue Excon::Errors::UnprocessableEntity => e
flash[:error] = decode_error(e.response.body)
redirect to("/login")
end
end
def filter_params(*safe_params)
safe_params.flatten!
params.dup.keep_if { |k, _| safe_params.include?(k) }
end
def get_authorize_params
# if the user is submitting a confirmation form, pull from session,
# otherwise get params from the request
if params[:authorize]
@cookie.authorize_params || {}
else
filter_params(%w{client_id response_type scope state prompt}).tap do |p|
p["scope"] = p["scope"].split(/[, ]+/).sort.uniq if p["scope"]
end
end
end
def client_deny_url
base = @client && @client["redirect_uri"] || "https://id.heroku.com"
build_uri(base, error: "access_denied")
end
def write_authentication_to_cookie(auth)
expires_at = Time.now.getlocal + auth["access_token"]["expires_in"]
@cookie.session_id = auth["session"]["id"]
@cookie.access_token = auth["access_token"]["token"]
@cookie.access_token_expires_at = expires_at
@cookie.refresh_token = auth["refresh_token"].try(:[], "token")
@cookie.user_id = auth["user"]["id"]
@cookie.user_email = auth["user"]["email"]
@cookie.user_full_name = auth["user"]["full_name"]
@cookie.sso_entity = if Identity::Config.sso_base_url
auth["sso_entity"]
end
# some basic sanity checks
raise "missing=access_token" unless @cookie.access_token
raise "missing=expires_in" unless @cookie.access_token_expires_at
end
def destroy_session
return if @cookie.session_id.nil?
api = Identity::HerokuAPI.new(
user: nil,
pass: @cookie.access_token,
ip: request.ip,
request_ids: request_ids,
version: 3
)
# tells API to destroy the session for Identity's current tokens, and
# all the tokens that were provisioned through this session
log :destroy_session, session_id: @cookie.session_id do
api.delete(
path: "/oauth/sessions/#{@cookie.session_id}",
expects: [200, 401, 404]
)
end
end
def logout
url = if params[:url] && safe_redirect?(params[:url])
params[:url]
else
"/login"
end
@cookie.clear
redirect to(url)
end
end
end
|
heroku/identity
|
test/heroku_cookie_test.rb
|
require_relative "test_helper"
describe Identity::HerokuCookie do
include Rack::Test::Methods
def app
@app
end
it "sets the Heroku cookie when appropriate" do
@app = new_app({ "oauth_session_id" => "1234" })
get "/"
assert_includes response_cookie, "heroku_session=1; domain=.heroku.com; path=/;"
assert_includes response_cookie, "heroku_session_nonce=1234; domain=.heroku.com; path=/;"
end
it "deletes the Heroku cookie when appropriate" do
@app = new_app({})
get "/"
assert_includes response_cookie, "heroku_session=; domain=.heroku.com; path=/;"
assert_includes response_cookie, "heroku_session_nonce=; domain=.heroku.com; path=/;"
end
private
def new_app(cookie)
Sinatra.new do
register Identity::HerokuCookie
get "/" do
@cookie = Identity::Cookie.new(cookie)
end
end
end
def response_cookie
last_response.headers["Set-Cookie"]
end
end
|
heroku/identity
|
lib/identity/helpers/log.rb
|
module Identity::Helpers
module Log
def log(action, data={}, &block)
data.merge! app: "identity", request_id: request_ids
# A UUID in a shared cookie allows correlating OAuth logs with other Heroku properties
data.merge! oauth_dance_id: @oauth_dance_id if @oauth_dance_id
Slides.log(action, data, &block)
end
def request_ids
request.env["REQUEST_IDS"]
end
end
end
|
heroku/identity
|
test/test_helper.rb
|
# seed the environment
ENV["COOKIE_ENCRYPTION_KEY"] = \
"<KEY>
ENV["HEROKU_ROOT_DOMAIN_COOKIE_ENCRYPTION_KEY"] = \
"<KEY>
ENV["DASHBOARD_URL"] = "https://dashboard.heroku.com"
ENV["SSO_BASE_URL"] = "https://sso.heroku.com"
ENV["HEROKU_API_URL"] = "https://api.heroku.com"
ENV["HEROKU_OAUTH_ID"] = "<KEY>"
ENV["HEROKU_OAUTH_SECRET"] = "<KEY>"
# set before using Bundler
ENV["RACK_ENV"] = "test"
ENV["SIGNUP_URL"] = "https://signup.heroku.com"
require "bundler/setup"
Bundler.require(:default, :test)
require "capybara"
require "minitest/autorun"
require "minitest/spec"
require "rack/test"
require "webmock/minitest"
require_relative "../lib/identity"
require_relative "service_stubs"
require_relative "identity_assertions"
WebMock.disable_net_connect!
# suppress logging
module Slides
def self.log(action, data={}, &block)
yield(block) if block
end
def self.log_array(action, data, &block)
yield(block) if block
end
end
class MiniTest::Spec
include RR::Adapters::TestUnit
end
|
heroku/identity
|
lib/identity/cookie.rb
|
module Identity
class Cookie
def initialize(session)
@session = session
self.created_at ||= Time.now
end
def access_token
@session["access_token"]
end
def access_token=(token)
@session["access_token"] = token
end
def access_token_expires_at
@session["access_token_expires_at"] ?
Time.parse(@session["access_token_expires_at"]) : nil
end
def access_token_expires_at=(expires_at)
@session["access_token_expires_at"] =
expires_at ? expires_at.iso8601 : nil
end
def authorize_params
@session["authorize_params"] ?
MultiJson.decode(@session["authorize_params"]) : nil
end
def authorize_params=(params)
@session["authorize_params"] = params ? MultiJson.encode(params) : nil
end
def post_signup_url
@session["post_signup_url"]
end
def post_signup_url=(url)
@session["post_signup_url"] = url
end
def sso_entity
@session["sso_entity"]
end
def sso_entity=(entity)
@session["sso_entity"] = entity
end
def clear
@session.clear
end
# not used yet, but will eventually be used to enforce a maximum duration
# on session lifetimes
def created_at
@session["created_at"] ? Time.parse(@session["created_at"]) : nil
end
def created_at=(created_at)
@session["created_at"] =
created_at ? created_at.iso8601 : nil
end
# used to store creds during two-factor auth
def email
@session["email"]
end
def email=(email)
@session["email"] = email
end
# used to store creds during two-factor auth
def password
@session["password"]
end
def password=(password)
@session["password"] = password
end
# URL to redirect to after login
def redirect_url
@session["redirect_url"]
end
def redirect_url=(redirect_url)
@session["redirect_url"] = redirect_url
end
def refresh_token
@session["refresh_token"]
end
def refresh_token=(token)
@session["refresh_token"] = token
end
def session_id
# session_id is a reserved key
@session["oauth_session_id"]
end
def session_id=(id)
# session_id is a reserved key
@session["oauth_session_id"] = id
end
def signup_source
@session["signup_source"]
end
def signup_source=(slug)
@session["signup_source"] = slug
end
def user_id
@session["user_id"]
end
def user_id=(id)
@session["user_id"] = id
end
def user_email
@session["user_email"]
end
def user_email=(email)
@session["user_email"] = email
end
def user_full_name
@session["user_full_name"]
end
def user_full_name=(id)
@session["user_full_name"] = id
end
end
end
|
heroku/identity
|
lib/identity/csrf.rb
|
module Identity
class CSRF < ::Rack::Csrf
def initialize(app, opts={})
opts.merge!(raise: true)
super(app, opts)
end
def call(env)
super(env)
rescue InvalidCsrfToken
req = Rack::Request.new(env)
Identity.log :invalid_csrf_token,
actual_token: req.params['_csrf'],
expected_token: env['rack.session']['csrf.token'],
id: env["REQUEST_IDS"],
referrer: env["HTTP_REFERER"]
[403, { 'Content-Type' => 'text/html', 'Content-Length' => '0' }, []]
end
end
end
|
heroku/identity
|
lib/identity/assets.rb
|
<filename>lib/identity/assets.rb
module Identity
class Assets < Sinatra::Base
register ErrorHandling
def initialize(*args)
super
path = "#{Config.root}/assets"
@assets = Sprockets::Environment.new do |env|
Identity.log :assets, path: path
env.append_path(path + "/fonts")
env.append_path(path + "/images")
env.append_path(path + "/javascripts")
env.append_path(path + "/stylesheets")
if Config.production?
env.js_compressor = YUI::JavaScriptCompressor.new
env.css_compressor = YUI::CssCompressor.new
end
end
end
get "/assets/:release/purple.js" do
respond_with_asset(@assets["purple.js"])
end
get "/assets/:release/modernizr.min.js" do
respond_with_asset(@assets["modernizr.min.js"])
end
get "/assets/:release/purple.css" do
respond_with_asset(@assets["purple.css"])
end
(%w{ico jpg png} + %w{eot svg ttf woff}).each do |format|
get "/assets/*.#{format}" do |image|
name = "#{image}.#{format}"
if @assets[name]
respond_with_asset(@assets[name])
else
404
end
end
end
private
def respond_with_asset(asset)
cache_control(:public, max_age: 2592000)
content_type(asset.content_type)
last_modified(asset.mtime.utc)
asset
end
end
end
|
heroku/identity
|
test/fernet_cookie_coder_test.rb
|
<gh_stars>10-100
require_relative "test_helper"
describe Identity::FernetCookieCoder do
secret = "<KEY>
another_secret = "<KEY>
it "encrypts a cookie, then decrypts a cookie" do
data = { access_token: "5<PASSWORD>" }
coder = Identity::FernetCookieCoder.new(secret)
cipher = coder.encode(data)
assert_equal data, coder.decode(cipher)
end
it "encrypts with the first given key" do
data = { access_token: "5<PASSWORD>" }
coder = Identity::FernetCookieCoder.new(secret)
coder.encode(data)
coder = Identity::FernetCookieCoder.new(another_secret, secret)
refute_equal data, coder.encode(data)
end
it "enables graceful encryption key rotation" do
data = { access_token: "5<PASSWORD>" }
coder = Identity::FernetCookieCoder.new(secret)
cipher = coder.encode(data)
coder = Identity::FernetCookieCoder.new(another_secret, secret)
assert_equal data, coder.decode(cipher)
end
it "decrypts with legacy fernet" do
data = { access_token: "5<PASSWORD>" }
legacy_cipher = generate_legacy_cipher(secret, data)
coder = Identity::FernetCookieCoder.new(secret)
assert_equal data, coder.decode(legacy_cipher)
end
def generate_legacy_cipher(key, raw)
data = Base64.urlsafe_encode64(Marshal.dump(raw))
LegacyFernet.generate(key) do |generator|
generator.data = { "session" => data }
end
end
end
|
heroku/identity
|
test/cookie_coder_test.rb
|
require_relative "test_helper"
describe Identity::CookieCoder do
secret = "<KEY>
another_secret = "<KEY>
it "encryptes a cookie, then descrypts a cookie" do
data = {
user: {
id: "1234",
email: "<EMAIL>",
full_name: "<NAME>"
}
}
coder = Identity::CookieCoder.new(secret)
cipher = coder.encode(data)
assert_equal JSON.parse(JSON.generate(data)), coder.decode(cipher)
end
it "encrypts with the first given key" do
data = {
user: {
id: "1234",
email: "<EMAIL>",
full_name: "<NAME>"
}
}
coder = Identity::CookieCoder.new(secret)
coder.encode(data)
coder = Identity::CookieCoder.new(another_secret, secret)
refute_equal data, coder.encode(data)
end
it "enables graceful encryption key rotation" do
data = {
user: {
id: "1234",
email: "<EMAIL>",
full_name: "<NAME>"
}
}
coder = Identity::CookieCoder.new(secret)
cipher = coder.encode(data)
coder = Identity::CookieCoder.new(another_secret, secret)
assert_equal JSON.parse(JSON.generate(data)), coder.decode(cipher)
end
end
|
heroku/identity
|
lib/identity/excon_instrumentor.rb
|
module Identity
class ExconInstrumentor
attr_accessor :events
def initialize(extra_data={})
@extra_data = extra_data
end
def instrument(name, params={}, &block)
data = {
app: "identity",
host: params[:host],
path: params[:path],
method: params[:method],
expects: params[:expects],
status: params[:status],
}
# dump everything on an error
data.merge!(params) if name == "excon.error"
data.merge!(@extra_data)
Slides.log(name, data) { block.call if block }
end
end
end
|
heroku/identity
|
lib/identity/error_handling.rb
|
<filename>lib/identity/error_handling.rb
module Identity
module ErrorHandling
UNAVAILABLE_ERRORS = [
Excon::Errors::ServerError,
# a NotAcceptable probably means that the ELB has lost its backends and
# doesn't know how to respond to our V3 "Accept"; display unavailable
Excon::Errors::NotAcceptable,
Excon::Errors::ServiceUnavailable,
Excon::Errors::GatewayTimeout,
Excon::Errors::SocketError,
Excon::Errors::Timeout
]
ERROR_TYPES = {
401 => :unauthorized,
404 => :not_found,
429 => :too_many_requests,
500 => :server_error,
503 => :unavailable
}
def self.registered(app)
app.helpers Helpers
app.error Excon::Errors::TooManyRequests do
handle_error 429
end
app.error *UNAVAILABLE_ERRORS do
handle_error 503
end
app.error Excon::Errors::Unauthorized do
handle_error 401
end
app.error Excon::Errors::NotFound do
handle_error 404
end
app.error do
Rollbar.error(env["sinatra.error"], context)
handle_error 500
end
end
module Helpers
def context
{
method: request.request_method,
module: self.class.name,
request_id: env["REQUEST_IDS"],
route_signature: env["HTTP_X_ROUTE_SIGNATURE"]
}
end
def handle_error(code)
status code
e = env["sinatra.error"]
Identity.log(:exception, {
type: ERROR_TYPES[code],
class: e.class.name,
message: e.message,
backtrace: e.backtrace.inspect
}.merge(context))
slim :"errors/#{code}", layout: :"layouts/purple"
end
end
def route(verb, path, *)
condition { env["HTTP_X_ROUTE_SIGNATURE"] = path.to_s }
super
end
end
end
|
heroku/identity
|
lib/identity/cookie_coder.rb
|
require "base64"
module Identity
# CookieCoder encodes and decodes payload before setting it to cookie
# Different from FernetCookieCoder, it doesn't use Ruby Marshal.
# The encrypted cookie is meant to consumed by other programming
# languages other than Ruby.
class CookieCoder
def initialize(*keys)
@keys = keys.compact
end
def encode(payload)
# make sure all keys are strings
payload = JSON.generate(payload)
Fernet.generate(@keys.first, payload)
end
def decode(cipher)
return {} if cipher == nil
# There can be URL encoded characters
# from the cookies
cipher = CGI::unescape(cipher)
plain = nil
@keys.each do |key|
begin
plain = decode_with_key(cipher, key)
rescue OpenSSL::Cipher::CipherError
end
break if plain
end
raise "no valid encryption key for cipher" unless plain
plain
rescue => e
Identity.log(:exception,
class: e.class.name,
message: e.message,
fernet: true,
backtrace: e.backtrace.inspect
)
{}
end
private
def decode_with_key(cipher, key)
verifier = Fernet.verifier(key, cipher)
verifier.enforce_ttl = false
return nil unless verifier.valid?
JSON.parse(verifier.message)
end
end
end
|
heroku/identity
|
test/cookie_test.rb
|
<filename>test/cookie_test.rb
require_relative "test_helper"
describe Identity::Cookie do
it "sets created_at on initialization" do
Timecop.freeze(Time.now) do
fake_session = {}
cookie = Identity::Cookie.new(fake_session)
assert_equal Time.now.to_i, cookie.created_at.to_i
assert_equal Time.now.iso8601, fake_session["created_at"]
end
end
end
|
martinstannard/ruby-processing
|
lib/ruby-processing/runner.rb
|
<filename>lib/ruby-processing/runner.rb
require 'ostruct'
require 'fileutils'
module Processing
# Utility class to handle the different commands that the 'rp5' command
# offers. Able to run, watch, live, create, app, applet, and unpack
class Runner
HELP_MESSAGE = <<-EOS
Ruby-Processing is a little shim between Processing and JRuby that helps
you create sketches of code art.
Usage:
rp5 [run | watch | live | create | app | applet | unpack] path/to/sketch
Examples:
rp5 unpack samples
rp5 run samples/jwishy.rb
rp5 create some_new_sketch 640 480
rp5 watch some_new_sketch.rb
rp5 applet some_new_sketch.rb
Further information:
http://wiki.github.com/jashkenas/ruby-processing
EOS
# Start running a ruby-processing sketch from the passed-in arguments
def self.execute
runner = new
runner.parse_options(ARGV)
runner.execute!
end
# Dispatch central.
def execute!
case @options.action
when 'run' : run(@options.path)
when 'watch' : watch(@options.path)
when 'create' : create(@options.path, @options.args)
when 'live' : live(@options.path)
when 'app' : app(@options.path)
when 'applet' : applet(@options.path)
when 'unpack' : unpack(@options.path)
when /-v/ : show_version
when /-h/ : show_help
else show_help
end
end
# Parse the command-line options. Keep it simple.
def parse_options(args)
@options = OpenStruct.new
@options.action = args[0] || nil
@options.path = args[1] || File.basename(Dir.pwd + '.rb')
@options.args = args[2..-1] || []
end
# Create a fresh Ruby-Processing sketch, with the necessary
# boilerplate filled out.
def create(sketch, args)
Processing::Creator.new.create!(sketch, args)
end
# Just simply run a ruby-processing sketch.
def run(sketch)
ensure_exists(sketch)
spin_up('run.rb', sketch)
end
# Run a sketch, keeping an eye on it's file, and reloading
# whenever it changes.
def watch(sketch)
ensure_exists(sketch)
spin_up('watch.rb', sketch)
end
# Run a sketch, opening its guts to IRB, letting you play with it.
def live(sketch)
ensure_exists(sketch)
spin_up('live.rb', sketch)
end
# Generate a cross-platform application of a given Ruby-Processing sketch.
def app(sketch)
Processing::ApplicationExporter.new.export!(sketch)
end
# Generate an applet and HTML page for a given sketch.
def applet(sketch)
Processing::AppletExporter.new.export!(sketch)
end
# Install the included samples to a given path, where you can run and
# alter them to your heart's content.
def unpack(dir)
require 'fileutils'
usage = "Usage: rp5 unpack [samples | library]"
puts usage and return unless dir.match(/\A(samples|library)\Z/)
FileUtils.cp_r("#{RP5_ROOT}/#{dir}", "#{Dir.pwd}/#{dir}")
end
# Display the current version of Ruby-Processing.
def show_version
puts "Ruby-Processing version #{Processing.version}"
end
# Show the standard help/usage message.
def show_help
puts HELP_MESSAGE
end
private
# Trade in this Ruby instance for a JRuby instance, loading in a
# starter script and passing it some arguments.
def spin_up(starter_script, args)
runner = "#{RP5_ROOT}/lib/ruby-processing/runners/#{starter_script}"
command = "java -cp #{jruby_complete} #{dock_icon} org.jruby.Main #{runner} #{args}"
exec(command)
# exec replaces the Ruby process with the JRuby one.
end
def ensure_exists(sketch)
puts "Couldn't find: #{sketch}" and exit unless File.exists?(sketch)
end
def jruby_complete
File.join(RP5_ROOT, 'lib/core/jruby-complete.jar')
end
# On the Mac, we can display a fat, shiny ruby in the Dock.
def dock_icon
mac = RUBY_PLATFORM.match(/darwin/i)
mac ? "-Xdock:name=Ruby-Processing -Xdock:icon=#{RP5_ROOT}/lib/templates/application/Contents/Resources/sketch.icns" : ""
end
end # class Runner
end # module Processing
|
martinstannard/ruby-processing
|
lib/ruby-processing/runners/run.rb
|
<gh_stars>1-10
# Windows apps start life in the wrong folder.
ARGV[1] = nil and Dir.chdir('lib') if ARGV[1] == '--windows-app'
require "#{File.dirname(__FILE__)}/base.rb"
require Processing::SKETCH_PATH
|
martinstannard/ruby-processing
|
samples/processing_app/3D/form/brick_tower.rb
|
<filename>samples/processing_app/3D/form/brick_tower.rb
require 'ruby-processing'
# Original by <NAME>
# 3D castle tower constructed out of individual bricks.
# Uses the PVecor and Cube classes.
class BrickTower < Processing::App
def setup
@bricks_per_layer = 16
@brick_layers = 18
@brick_width, @brick_height, @brick_depth = 60, 25, 25
@radius = 175.0
@angle = 0
render_mode P3D
@brick = Cubeish.new(@brick_width, @brick_height, @brick_depth)
end
def draw
background 0
@temp_x, @temp_y, @temp_z = 0, 0, 0
fill 182, 62, 29
no_stroke
lights
translate(width/2.0, height*1.2, -380) # move viewpoint into position
rotate_x(radians(-45)) # tip tower to see inside
rotate_y(frame_count * PI/600) # slowly rotate tower
@brick_layers.times {|i| draw_layer(i) }
end
def draw_layer(layer_num)
@layer_num = layer_num
@temp_y -= @brick_height # increment rows
@angle = 360.0 / @bricks_per_layer * @layer_num / 2.0 # alternate brick seams
@bricks_per_layer.times {|i| draw_bricks(i) }
end
def draw_bricks(brick_num)
@brick_num = brick_num
@temp_z = cos(radians(@angle)) * @radius
@temp_x = sin(radians(@angle)) * @radius
push_matrix
translate @temp_x, @temp_y, @temp_z
rotate_y(radians(@angle))
top_layer = @layer_num == @brick_layers - 1
even_brick = @brick_num % 2 == 0
@brick.create unless top_layer # main tower
@brick.create if top_layer && even_brick # add crenelation
pop_matrix
@angle += 360.0 / @bricks_per_layer
end
end
# The Cubeish class works a little different than the cube in the
# Processing example. SIDES tells you where the negative numbers go.
# We dynamically create each of the PVectors by passing in the
# appropriate signs.
class Cubeish
SIDES = {:front => ['-- ', ' - ', ' ', '- '],
:left => ['-- ', '---', '- -', '- '],
:right => [' - ', ' --', ' -', ' '],
:back => ['---', ' --', ' -', '- -'],
:top => ['-- ', '---', ' --', ' - '],
:bottom => ['- ', '- -', ' -', ' ']}
SIGNS = {'-' => -1,
' ' => 1}
def initialize(width, height, depth)
@vertices = {}
@w, @h, @d = width, height, depth
SIDES.each do |side, signs|
@vertices[side] = signs.map do |s|
s = s.split('').map {|el| SIGNS[el] }
Processing::PVector.new(s[0]*@w/2, s[1]*@h/2, s[2]*@d/2)
end
end
end
def create
@vertices.each do |name, vectors|
$app.begin_shape BrickTower::QUADS
vectors.each {|v| $app.vertex(v.x, v.y, v.z) }
$app.end_shape
end
end
end
BrickTower.new :title => "Brick Tower", :width => 640, :height => 360
|
martinstannard/ruby-processing
|
lib/ruby-processing/exporters/base_exporter.rb
|
<gh_stars>1-10
require 'fileutils'
require 'erb'
module Processing
# This base exporter implements some of the common
# code-munging needed to generate apps and applets.
class BaseExporter
include FileUtils
DEFAULT_TITLE = "Ruby-Processing Sketch"
DEFAULT_DIMENSIONS = {'width' => '500', 'height' => '500'}
DEFAULT_DESCRIPTION = ''
# Returns the filepath, basename, and directory name of the sketch.
def get_main_file(file)
return file, File.basename(file), File.dirname(file)
end
# Centralized method to read the source of the sketch and extract
# all the juicy details.
def extract_information
# Extract information from main file
@info = {}
@info[:source_code] = source = read_source_code
@info[:class_name] = extract_class_name(source)
@info[:title] = extract_title(source)
@info[:width] = extract_dimension(source, 'width')
@info[:height] = extract_dimension(source, 'height')
@info[:description] = extract_description(source)
@info[:libraries] = extract_libraries(source)
@info[:real_requires] = extract_real_requires(source)
hash_to_ivars @info
@info
end
# Searches the source for a class name.
def extract_class_name(source)
match = source.match(/(\w+)\s*<\s*Processing::App/)
match ? match[1] : nil
end
# Searches the source for a title.
def extract_title(source)
match = source.match(/#{@info[:class_name]}\.new.*?:title\s=>\s["'](.+)["']/m)
match ? match[1] : DEFAULT_TITLE
end
# Searches the source for the width and height of the sketch.
def extract_dimension(source, dimension)
match = source.match(/#{@info[:class_name]}\.new.*?:#{dimension}\s=>\s(\d+)/m)
match ? match[1] : DEFAULT_DIMENSIONS[dimension]
end
# Searches the source for a description of the sketch.
def extract_description(source)
match = source.match(/# Description:(.*?)\n[^#]/m)
match ? match[1].gsub!(/\n(\s*)?#/, "") : DEFAULT_DESCRIPTION
end
# Searches the source any libraries that have been loaded.
def extract_libraries(source)
libs = []
code = source.dup
loop do
matchdata = code.match(/load_\w+_library.+?["':](\S+?)["'\s]/)
break unless matchdata
match = matchdata[1]
@opengl = true if match.match(/opengl/i)
local_path = "#{local_dir}/library/#{match}"
rp5_path = "#{RP5_ROOT}/library/#{match}"
File.exists?(local_path) ? libs << local_path :
(libs << rp5_path if File.exists?(rp5_path))
code = matchdata.post_match
end
libs
end
# Looks for all of the codes require or load commands, checks
# to see if the file exists (that it's not a gem, or a standard lib)
# and hands you back all the real ones.
def extract_real_requires(source)
code = source.dup
requirements = []
partial_paths = []
loop do
matchdata = code.match(/^.*\b(require|load)\b.*$/)
break unless matchdata
line = matchdata[0].gsub('__FILE__', "'#{@main_file_path}'")
line = line.gsub(/\b(require|load)\b/, 'partial_paths << ')
eval(line)
requirements += Dir["{#{local_dir}/,}{#{partial_paths.join(',')}}.{rb,jar}"]
code = matchdata.post_match
end
return requirements
end
protected
def read_source_code
File.read(@main_file_path)
end
def local_dir
File.dirname(@main_file_path)
end
def hash_to_ivars(hash)
hash.each{|k,v| instance_variable_set("@" + k.to_s, v) }
end
def wipe_and_recreate_destination
remove_entry_secure @dest if File.exists?(@dest)
mkdir_p @dest
end
def render_erb_in_path_with_binding(path, some_binding, opts={})
erbs = Dir.glob(path + "/**/*.erb")
erbs.each do |erb|
string = File.open(erb) {|f| f.read }
rendered = render_erb_from_string_with_binding(string, some_binding)
File.open(erb.sub(".erb", ""), "w") {|f| f.print rendered }
rm erb if opts[:delete]
end
end
def render_erb_from_string_with_binding(erb, some_binding)
rendered = ERB.new(erb, nil, "<>", "rendered").result(some_binding)
end
end
end
|
martinstannard/ruby-processing
|
lib/ruby-processing.rb
|
# Ruby-Processing is for Code Art.
# Send suggestions, ideas, and hate-mail to jashkenas [at] gmail.com
# Also, send samples and libraries.
unless defined? RP5_ROOT
$LOAD_PATH << File.expand_path(File.dirname(__FILE__))
RP5_ROOT = File.expand_path(File.dirname(__FILE__) + "/../")
end
require 'ruby-processing/helpers/string'
# The top-level namespace, a home for all Ruby-Processing classes.
module Processing
VERSION = [1,0,1]
# Returns the current version of Ruby-Processing.
def self.version
VERSION.join('.')
end
autoload :App, 'ruby-processing/app'
autoload :Runner, 'ruby-processing/runner'
autoload :Creator, 'ruby-processing/exporters/creator'
autoload :BaseExporter, 'ruby-processing/exporters/base_exporter'
autoload :AppletExporter, 'ruby-processing/exporters/applet_exporter'
autoload :ApplicationExporter, 'ruby-processing/exporters/application_exporter'
end
|
zapt-tech/zapt-location-ios-sdk
|
ZaptLocation-iOS-SDK.podspec
|
<reponame>zapt-tech/zapt-location-ios-sdk
Pod::Spec.new do |s|
s.name = 'ZaptLocation-iOS-SDK'
s.version = '0.0.10-rc1'
s.summary = 'SDK for indoor positioning'
s.homepage = 'http://docs.zapt.tech/'
s.author = { "Zapt Tecnologia de Localizacao Ltda." => "<EMAIL>" }
s.license = 'Copyright'
s.documentation_url = "http://docs.zapt.tech"
s.platform = :ios
s.source = { :git => "https://github.com/zapt-tech/zapt-location-ios-sdk.git", :tag => "0.0.10-rc1" }
s.ios.deployment_target = '9.0'
s.ios.vendored_frameworks = 'ZaptLocation_iOS_SDK.framework'
s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
end
|
rendegosling/game_tictactoe
|
game_tictactoe.rb
|
class GameTicTacToe
def initialize
@board = Board.new
setup_players
assign_starting_player
end
def setup_players
@player_1 = Player.new("Player 1", :x, @board)
@player_2 = Player.new("Player 2", :o, @board)
end
def assign_starting_player
@current_player = @player_1
end
def play
loop do
@board.render
@current_player.get_coordinates
break if game_over?
switch_players
end
end
def game_over?
game_has_winner? || game_draw?
end
def game_has_winner?
if @board.winning_combination?(@current_player.piece)
puts "Game over...#{@current_player.name}, you win!"
true
else
false
end
end
def game_draw?
if @board.full?
puts "Game is a draw..."
true
else
false
end
end
def switch_players
if @current_player == @player_1
@current_player = @player_2
else
@current_player = @player_1
end
end
end
# player related functionality
class Player
attr_accessor :name, :piece
def initialize(name = "Mystery_Player", piece, board)
raise "Piece must be a Symbol!" unless piece.is_a?(Symbol)
@name = name
@piece = piece
@board = board
end
def get_coordinates
loop do
coordinates = ask_for_coordinates
break if validate_coordinates_format(coordinates) && @board.add_piece(coordinates, @piece)
end
end
def ask_for_coordinates
puts "#{@name}(#{@piece}), enter your coordinates in x,y:"
gets.strip.split(",").map(&:to_i)
end
def validate_coordinates_format(coordinates)
if coordinates.is_a?(Array) && coordinates.size == 2
true
else
puts "Your coordinates are not in the valid format!"
end
end
end
# responsible for the board state
class Board
def initialize
@board = Array.new(3){Array.new(3)}
end
def render
puts
@board.each do |row|
row.each do |cell|
cell.nil? ? print("-") : print(cell.to_s)
end
puts
end
puts
end
def add_piece(coordinates, piece)
if piece_location_valid?(coordinates)
@board[coordinates[0]][coordinates[1]] = piece
true
else
false
end
end
def piece_location_valid?(coordinates)
if within_valid_coordinates?(coordinates)
coordinates_available?(coordinates)
end
end
def within_valid_coordinates?(coordinates)
if (0..2).include?(coordinates[0]) && (0..2).include?(coordinates[1])
true
else
puts "Piece coordinates are out of bounds"
end
end
def coordinates_available?(coordinates)
if @board[coordinates[0]][coordinates[1]].nil?
true
else
puts "There is already a piece there!"
end
end
def winning_combination?(piece)
winning_diagonal?(piece) ||
winning_horizontal?(piece) ||
winning_vertical?(piece)
end
# check if there are 3 piece in a diagonal
def winning_diagonal?(piece)
diagonals.any? do |diag|
diag.all?{|cell| cell == piece }
end
end
# check if there are 3 piece in a vertical
def winning_vertical?(piece)
verticals.any? do |vert|
vert.all?{|cell| cell == piece }
end
end
# check if there are 3 piece in a horizontal
def winning_horizontal?(piece)
horizontals.any? do |horizontal|
horizontal.all?{|cell| cell == piece }
end
end
def diagonals
[[@board[0][0],@board[1][1],@board[2][2]],[@board[2][0],@board[1][1],@board[0][2]]]
end
def verticals
@board
end
def horizontals
horizontals = []
3.times do |i|
horizontals << [@board[0][i],@board[1][i],@board[2][i]]
end
horizontals
end
def full?
@board.all? do |row|
row.none?(&:nil?)
end
end
end
game = GameTicTacToe.new
game.play
|
rendegosling/game_tictactoe
|
merged_list.rb
|
lists = [[1,4,5],[1,3,4],[2,6]]
merged_list = []
lists.each do |list|
merged_list += list
end
puts merged_list.sort
|
voc/eventkalender
|
spec/lib/eventkalender/event/conference_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Conference do
before(:each) do
@event = Eventkalender::Conference.new(name: 'my todes event',
location: 'todes location',
start_date: '24.04.1999',
end_date: '24.04.2000',
description: 'http://example.com',
short_name: 'h5n1',
wiki_path: '/wiki/h5n1',
buildup: '23.04.1999',
teardown: '25.04.2000',
planing_status: '')
end
after(:each) do
@event = nil
end
describe '#new' do
it 'should accept options hash' do
expect(@event.name).to eq 'my todes event'
expect(@event.location).to eq 'todes location'
expect(@event.start_date).to eq Date.parse('24.04.1999')
expect(@event.end_date).to eq Date.parse('24.04.2000')
expect(@event.description).to eq 'http://example.com'
expect(@event.short_name).to eq 'h5n1'
expect(@event.wiki_path).to eq '/wiki/h5n1'
expect(@event.buildup).to eq '23.04.1999'
expect(@event.teardown).to eq '25.04.2000'
end
end
describe 'getter' do
it 'should be possible to get name, description, location, start_date and end_date' do
expect(@event.name).to eq 'my todes event'
expect(@event.location).to eq 'todes location'
expect(@event.start_date).to eq Date.parse('24.04.1999')
expect(@event.end_date).to eq Date.parse('24.04.2000')
expect(@event.description).to eq 'http://example.com'
expect(@event.short_name).to eq 'h5n1'
expect(@event.wiki_path).to eq '/wiki/h5n1'
expect(@event.buildup).to eq '23.04.1999'
expect(@event.teardown).to eq '25.04.2000'
end
end
describe 'setter' do
it 'should be possible to set event name' do
@event.name = 'new todes event'
expect(@event.name).to eq 'new todes event'
end
it 'should be possible to set event location' do
@event.location = 'new todes location'
expect(@event.location).to eq 'new todes location'
end
it 'should be possible to set event description' do
@event.description = 'new description'
expect(@event.description).to eq 'new description'
end
it 'should be possible to set (voc) event wiki path' do
@event.wiki_path = '/wiki/url'
expect(@event.wiki_path.to_s).to eq '/wiki/url'
end
it 'should be possible to set event short name' do
@event.short_name = 'short name'
expect(@event.short_name).to eq 'short name'
end
end
describe '#check_date_input' do
it 'should return Date object' do
# Input String
date = @event.send(:check_date_input, '2023-05-23')
expect(date.is_a?(Date)).to be true
expect(date.to_s).to eq '2023-05-23'
# Input Date object
date = @event.send(:check_date_input, Date.parse('24.12.2014'))
expect(date.is_a?(Date)).to be true
expect(date.to_s).to eq '2014-12-24'
end
it 'should raise invalid date exception for invalid date input' do
date = @event.send(:check_date_input, '202305')
date2 = @event.send(:check_date_input, '?')
expect(date).to be nil
expect(date2).to be nil
end
it 'should return nil if input type is not a String or Date object' do
date = @event.send(:check_date_input, ['2023-05-23'])
expect(date).to be nil
end
end
describe '#to_ical' do
it 'should convert an event to a valid ical event' do
ical_object = @event.to_ical
array = ical_object.to_ical.split(/\n/)
expect(array.first).to match(/BEGIN:VEVENT/)
expect(array.last).to match(/END:VEVENT/)
expect(array.include?("DTSTART;VALUE=DATE:19990424\r")).to be true
expect(array.include?("DTEND;VALUE=DATE:20000425\r")).to be true
expect(array.include?("SUMMARY:my todes event\r")).to be true
expect(array.include?("LOCATION:todes location\r")).to be true
end
end
describe '.now?' do
it 'should return true if an event is now' do
expect(@event.now?).to be false
@event.start_date = Date.today
@event.end_date = Date.today + 1
expect(@event.now?).to be true
end
end
describe '.upcoming?' do
it 'should return true if an event is upcoming' do
expect(@event.upcoming?).to be false
@event.start_date = Date.today + 23
@event.end_date = Date.today + 42
expect(@event.upcoming?).to be true
end
end
describe '.past?' do
it 'should return true when an event lies in the past' do
expect(@event.past?).to be true
@event.start_date = Date.today + 23
@event.end_date = Date.today + 42
expect(@event.past?).to be false
@event.start_date = Date.today
@event.end_date = Date.today
expect(@event.past?).to be false
end
end
describe '.streaming=' do
it 'should set false, true or nil' do
# yes, we have streaming on this event
@event.streaming = 'ja'
expect(@event.streaming).to be true
@event.streaming = 'Ja'
expect(@event.streaming).to be true
# no streaming
@event.streaming = 'nein'
expect(@event.streaming).to be false
# streaming status is unclear
@event.streaming = 'vielleicht'
expect(@event.streaming).to be nil
@event.streaming = ''
expect(@event.streaming).to be nil
@event.streaming = nil
expect(@event.streaming).to be nil
end
end
describe '.idea?' do
it 'should return true when supporting the event is only an idea' do
expect(@event.idea?).to be false
@event.planing_status = 'idea'
expect(@event.idea?).to be true
end
end
end
|
voc/eventkalender
|
lib/eventkalender/event/meeting.rb
|
<filename>lib/eventkalender/event/meeting.rb
# frozen_string_literal: true
class Eventkalender
# Represents a voc event.
#
# @!attribute [rw] start_date
# @param date [String] witch represents start date of the event
# @return [Date] event start date
# @!attribute [rw] end_date
# @param date [String] witch represents end date of the event
# @return [Date] event end date
# @!attribute [rw] name
# @return [String] event name
# @!attribute [rw] location
# @return [String] event location
# @!attribute [rw] description
# @return [String] event description, in general it's used for event url
# @!attribute [rw] short_name
# @return [String] event synonym
# @!attribute [rw] wiki_path
# @return [String] event path in voc wiki
# @!attribute [rw] streaming
# @return [String] event streaming status
# @!attribute [rw] planing_status
# @return [String] event planing status
class Meeting < Event
attr_reader :start_date, :end_date
attr_accessor :type, :link, :location, :name
# Create new event object
#
# @param options [Hash] to create an event with.
# @option options [String] :name The event name
# @option options [String] :location The event location
# @option options [String] :start_date Events start date
# @option options [String] :end_date Events end date
# @option options [String] :description The event description
# @option options [String] :link The mumble url
# @option options [String] :planing_status Planed event status
# @option options [Boolean] :mumble Planed event status
def initialize(options = {})
super(options)
# optional
@type = options[:type]
@link = options[:link]
@tags = convert_tags(options[:tags])
end
# Convert event to ical.
#
# @example Convert event to ical object.
# event.to_ical #=> #<Icalendar::Event:0x00000002f02ee8 @name="VEVENT" … >
#
# @return [Icalendar::Event] converted ical event
def to_ical
Icalendar::Event.new.tap do |e|
e.summary = @name
e.location = @location
e.dtstart = @start_date
e.dtend = @end_date
e.description = @link
end
end
def description
@link.to_s
end
# Convert given string to an array with tags.
#
# @param string [String]
# @return [Array] tags
def convert_tags(string)
if string.nil?
[]
else
tags = string.split(',')
tags.map(&:strip)
end
end
# Is that meeting a mumble meeting?
#
# @return [Boolean]
def mumble?
@type =~ /[Mm]umble/ ? true : false
end
# Setter for tags.
#
# @param string [String] with tags comma seperated
# @return [Array] with tags
def tags=(string)
@tags = convert_tags(string)
end
# Getter for tags.
#
# @return [Array] with tags
def tags
@tags
end
end
end
|
voc/eventkalender
|
spec/lib/eventkalender/event/meeting_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Meeting do
before(:each) do
@meeting = Eventkalender::Meeting.new(
name: '<NAME>',
type: 'Mumble',
location: 'todes location',
start_date: '24.04.1999',
end_date: '24.04.2000',
link: 'https://exampele.com',
tags: 'a,b,c'
)
end
after(:each) do
@meeting = nil
end
describe '#new' do
it 'should accept options hash' do
expect(@meeting.name).to eq '<NAME>'
expect(@meeting.location).to eq 'todes location'
expect(@meeting.start_date).to eq Date.parse('24.04.1999')
expect(@meeting.end_date).to eq Date.parse('24.04.2000')
expect(@meeting.tags).to eq %w[a b c]
expect(@meeting.link).to eq 'https://exampele.com'
end
end
end
|
voc/eventkalender
|
scripts/unicorn.rb
|
# frozen_string_literal: true
process = ENV['PROCESS'] || 1
listen = ENV['LISTEN'] || 8000
worker_processes process
listen listen
stdout_path '/var/log/unicorn/stdout.log'
stderr_path '/var/log/unicorn/stderr.log'
|
voc/eventkalender
|
spec/lib/eventkalender/parser/parser_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Parser do
before(:each) do
@parser = Eventkalender::Parser.new
@scraper = Eventkalender::Scraper.new
end
after(:each) do
@parser = nil
end
# TODO: fix tests
#
# describe '#events' do
# it 'should return an array of events' do
# events = @parser.events
#
# expect(events.first).to be_instance_of Eventkalender::Conference
# expect(events.last).to be_instance_of Eventkalender::Conference
# end
#
# it 'should be possible to force scraping' do
# # do not force
# @parser.events
# last_parser_run = @parser.timestamp
#
# sleep 2
#
# # force scraping
# @parser.events(force_scraping = true)
# expect(@parser.timestamp.to_s).not_to eq last_parser_run.to_s
# end
# end
#
# describe '#to_event' do
# it 'should genetrate Eventkalender::Event object' do
# table = @scraper.get_tables
# rows = table.search('./*/tr')
#
# event = @parser.to_event(rows[2])
#
# expect(event.name).to match(/Easterhegg 2014/)
# expect(event.location).to match(/Stuttgart/)
# expect(event.start_date.to_s).to match(/2014-04-18/)
# expect(event.end_date.to_s).to match(/2014-04-21/)
# expect(event.description).to match(/https:\/\/eh14.easterhegg.eu\/)
# expect(event.streaming).to be true
# expect(event.short_name).to match(/easterhegg14/)
# expect(event.wiki_path.to_s).to match(/\/wiki\/easterhegg14/)
# expect(event.wiki_path).to be_instance_of String
# end
# end
#
# describe '#to_ical_calendar' do
# it 'should accept a list of events' do
# calendar = @parser.to_ical_calendar
#
# expect(Icalendar.parse(calendar.to_ical)).to be_instance_of(Array)
# end
#
# it 'should return valid ical calendar' do
# calendar = @parser.to_ical_calendar
#
# expect(calendar).to be_instance_of(Icalendar::Calendar)
# expect(Icalendar.parse(calendar.to_ical)).to be_instance_of(Array)
# end
# end
#
# describe '.date' do
# it 'should return date object' do
# date = Eventkalender::Parser.date('2023-05-23')
#
# expect(date).to be_instance_of(Date)
# end
#
# it 'should accept date as a string' do
# date = Eventkalender::Parser.date('2023-05-23')
#
# expect(date.to_s).to eq '2023-05-23'
# end
# end
#
# describe '#to_atom' do
# it 'should return valid atom feed' do
# feed = @parser.to_atom
#
# expect(feed.to_s).to match(/<id>tag:c3voc.de,2014-08-23:6<\/id>/)
# end
#
# it 'should return atom feed object' do
# feed = @parser.to_atom
# expect(feed).to be_instance_of(RSS::Atom::Feed)
# end
# end
#
# describe '#to_json' do
# it 'should return events in json' do
# json = @parser.to_json
#
# expect(json).to be_instance_of(String)
# expect(json).to match(/{\n \"voc_events\":/)
# end
#
# it 'should have some statistical data' do
# data = JSON.parse(@parser.to_json)
#
# expect(data['voc_events_count']['all']).to eq 9
# expect(data['voc_events_count']['with_streaming']).to eq 8
# expect(data['voc_events_count']['without_streaming']).to eq 0
# expect(data['voc_events_count']['undefined_streaming']).to eq 1
# end
# end
#
# describe '#filter' do
# it 'should filter events' do
# # Overwrite Date.today to have every time same conditions
# Date.stub(:today).and_return(Date.parse('2014-04-15'))
#
# # case past
# events = @parser.filter( { general: 'past' } )
# expect(events.count).to eq 1
# expect(events.first.name).to match(/FOSSGIS/)
#
# # case upcoming
# events = @parser.filter( { general: 'upcoming' } )
# expect(events.count).to eq 7
#
# # case year
# events = @parser.filter( { general: '2014' } )
# expect(events.count).to eq 8
#
# # case year
# events = @parser.filter( { general:'2013' } )
# expect(events.count).to eq 0
#
# # default case
# events = @parser.filter( { general: 'random_input' })
# expect(events.count).to eq 8
# end
#
# it 'should return events array' do
# events = @parser.filter( { general: 'all' } )
#
# expect(events.last).to be_instance_of(Eventkalender::Conference)
# end
#
# it 'should accept streaming filter' do
# # Overwrite Date.today to have every time same conditions
# Date.stub(:today).and_return(Date.parse('2014-04-15'))
#
# # case past, streaming off
# events = @parser.filter( { general: 'past', streaming: 'false' } )
# expect(events.count).to eq 0
#
# # case past, streaming off
# events = @parser.filter( { general: 'past', streaming: 'true' } )
# expect(events.count).to eq 1
# expect(events.first.name).to match(/FOSSGIS/)
#
# # case upcoming, streaming on
# events = @parser.filter( { general: 'upcoming', streaming: 'true' } )
# expect(events.count).to eq 6
# expect(events.last.name).to match(/31C3/)
#
# # case upcoming, streaming on, idea event
# events = @parser.filter( { general: 'upcoming', streaming: 'true', idea: 'true' } )
# expect(events.count).to eq 7
# expect(events.last.name).to match(/ICMP/)
# end
# end
#
# describe '#filter_streaming' do
# it 'should filter events' do
# # Overwrite Date.today to have every time same conditions
# Date.stub(:today).and_return(Date.parse('2014-04-15'))
#
# events = @parser.filter_streaming('false')
# expect(events.count).to eq 0
#
# events = @parser.filter_streaming('true')
# expect(events.count).to eq 8
#
# events = @parser.filter_streaming('undefined')
# expect(events.count).to eq 1
# end
# end
#
# describe '#remove_idea_events' do
# it 'should remove events with planing status idea' do
# events = @parser.events
# expect(events.count).to eq 9
#
# expect(@parser.remove_idea_events(events).count).to eq 8
# end
# end
end
|
voc/eventkalender
|
lib/eventkalender/parser/parser.rb
|
# frozen_string_literal: true
# stdlib
require 'pathname'
require 'date'
require 'rss'
require 'json'
# gem
require 'icalendar'
class Eventkalender
# Parser class can be used to parse dokuwiki table and return events in multiple formats.
#
# @example Create parser to parse voc wiki events page.
# parser = Eventkalender::Parser.new
# parser.events #=> [#<Eventkalender::Conference:0x00000002a49f78 … ]
#
# @example Convert date String into Date object.
# Eventkalender::Parser.date('23-12-2014') #=> #<Date: 2014-12-23 ((2457015j,0s,0n),+0s,2299161j)>
#
# @!attribute [r] events_table
# @return [Nokogiri::XML::Element] Contains scraped event table.
# @!attribute [r] timestamp
# @return [Time] Last scraping time.
class Parser
attr_reader :events_tables, :timestamp
def parse(table = @event_table)
found_events = []
# Events inside table are separated in rows.
event_rows = table.search('./tr')
# HACK: Ugly workaround for unknown xpath matching problems.
# If clause is only needed for rspec and webmock.
event_rows = table.search('./*/tr') if event_rows.count.zero?
# Iterate over all rows and create ical events for every event.
events = event_rows.map do |row|
# Skip headlines
next if row.search('./td').empty?
event = to_event(row)
if event.nil?
next
else
found_events << event
end
end
# Remove nil objects
events.compact
found_events
end
# Parsed content from dokuwiki page and returned Hash with events.
#
# @example Scrape events
# parser.events(true) #=> [#<Eventkalender::Conference:0x0000000332e300 @name=…, …]
#
# @param force_scraping [Boolean] to force scraping
# @return [Array] scraped events
def events(force_scraping = false)
# Get events table from web page scraper or from instance variable
if @events_tables.nil? || (@timestamp - 20.minutes.ago).negative? || force_scraping
@events_tables = Eventkalender::Scraper.scrape!
@timestamp = Time.now
end
events = {}
@events_tables.each do |e_table|
case e_table[:type]
when :meetings
events[:meetings] = Eventkalender::Parser::Meetings.new(e_table[:table])
when :conferences
events[:conferences] = Eventkalender::Parser::Conferences.new(e_table[:table])
end
end
events
end
# Converts array with events into ical calendar.
#
# @param events [Array<Event>, #events] to convert to an ical calender
# @return [Icalendar::Calendar] converted events
def to_ical_calendar(events)
# Create new ical calendar
calendar = Icalendar::Calendar.new
# Setting time zone
calendar.timezone { |t| t.tzid = 'Europe/Berlin' }
# Add every object in array to new created calendar
events.each { |event| calendar.add_event(event.to_ical) }
calendar
end
# Date converter, witch converts strings into valid date objects if possible.
#
# @example Parse date string
# Eventkalender::parser.date('2014-12-24') #=> #<Date: 2014-12-24 ((2457016j,0s,0n),+0s,2299161j)>
#
# @raise
# [ArgumentError] if invalid date is given and parsing failed
# @param date [String] content looks like
# @return [Date, nil] created date object or nil if creation failed
def self.date(date)
# Catching type class of input value
case date
when Date
date
when String
begin
Date.parse(date)
rescue StandardError
nil
end
end
end
# Detect if there is live streaming planed.
#
# @example
# Eventkalender.parser.detect_streaming('yes') #=> true
#
# @param string [String] to check
# @return [Boolean, nil] streaming status true or false or not defined
def self.detect_streaming(string)
case string
when /[Jj]a|[Yy]es/
true
when /[Nn]ein|[Nn]o/
false
end
end
end
end
|
voc/eventkalender
|
lib/eventkalender/parser/conferences.rb
|
<filename>lib/eventkalender/parser/conferences.rb
# frozen_string_literal: true
class Eventkalender
class Parser::Conferences < Eventkalender::Parser
def initialize(event_table)
@event_table = event_table
parse(event_table)
end
def events(events = parse)
events
end
# Converts events array to plain text.
#
# @example Convert events to text.
# parser.to_txt(events) #=> "Hack*n*Play2 - Freiburg21.02.2014 - 23.02.2014"
#
# @param events [Array<Event>, #events] to convert to plain text
# @return [String] txt file
def to_txt(events = self.events)
# Create empty string
txt = +''
events.each do |event|
# Add event to string
txt << "#{event.name} - #{event.location}\n"\
"#{event.start_date.strftime('%d.%m.%Y')} - #{event.end_date.strftime('%d.%m.%Y')}"
# Adding two empty lines when current event is not the last one
txt << "\n\n" unless events.last.name == event.name
end
txt
end
# Converts string into event object.
#
# @param table_row [Nokogiri::XML::Element] that should be converted to an event
# @return [Event] event
def to_event(table_row)
# Search all cols in event row.
raw_event = table_row.search('./td')
# Return nil if dates are not set
return nil if raw_event[3].text.empty? || raw_event[2].text.empty?
start_date = self.class.date(raw_event[2].text) # Start date
end_date = self.class.date(raw_event[3].text) # End date
buildup = self.class.date(raw_event[9].text)
teardown = self.class.date(raw_event[10].text)
return nil if start_date.nil? || end_date.nil?
# Create new ical object and return it
Eventkalender::Conference.new.tap do |e|
# Add more information to ical object.
e.name = raw_event[0].text # Event name
e.location = raw_event[1].text # Event location
e.start_date = start_date
e.end_date = end_date
e.description = raw_event[5].text # URL
e.streaming = raw_event[7].text # Is streaming planed?
e.planing_status = raw_event[8].text # Event planing status
e.buildup = buildup
e.teardown = teardown
e.cases = raw_event[11].text
url_path = raw_event[0].xpath('./a[@href]')[0]['href']
e.short_name = %r{^.*/(.*)$}.match(url_path)[1]
e.wiki_path = url_path
end
end
# Create atom feed from given events array.
#
# @example Generate rss feed for given events.
# parser.events #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" …"
#
# @param events [Array<Event>, #events] to convert to an atom feed
# @return [RSS::Atom::Feed] created rss feed
def to_atom(events = self.events)
RSS::Maker.make('atom') do |maker|
maker.channel.author = 'eventkalender'
maker.channel.updated = Time.now.to_s
maker.channel.about = 'http://c3voc.de/'
maker.channel.link = 'http://c3voc.de/eventkalender/events.atom'
maker.channel.links.first.rel = 'self'
maker.channel.links.first.type = 'application/atom+xml'
maker.channel.title = 'VOC Events'
events.each do |event|
maker.items.new_item do |item|
item.updated = Time.now.to_s
item.title = event.name
item.id = "tag:c3voc.de,#{event.start_date.strftime('%Y-%m-%d')}:#{events.index(event) + 1}"
item.description = "#{event.name} in #{event.location} "\
"vom #{event.start_date.strftime('%d.%m.%Y')} "\
"bis #{event.end_date.strftime('%d.%m.%Y')}."
item.link = 'http://c3voc.de/eventkalender'
end
end
end
end
# Create json stream from a give events array.
#
# @example Convert given events to json
# parser.to_json #=> ""{\n \"voc_events\": {\n …"
#
# @param events [Array<Event>, #events] to convert to json
# @return [JSON] events in json
def to_json(events = self.events)
hash = { voc_events: {}, voc_events_count: {} }
events.each do |event|
hash[:voc_events][event.name] = {}
hash[:voc_events][event.name][:name] = event.name
hash[:voc_events][event.name][:short_name] = event.short_name
hash[:voc_events][event.name][:location] = event.location
hash[:voc_events][event.name][:start_date] = event.start_date
hash[:voc_events][event.name][:end_date] = event.end_date
hash[:voc_events][event.name][:description] = event.description
hash[:voc_events][event.name][:voc_wiki_path] = event.wiki_path
hash[:voc_events][event.name][:streaming] = event.streaming
hash[:voc_events][event.name][:planing_status] = event.planing_status
hash[:voc_events][event.name][:cases] = event.cases
hash[:voc_events][event.name][:buildup] = event.buildup
hash[:voc_events][event.name][:teardown] = event.teardown
end
# Adding statistical data
hash[:voc_events_count][:all] = events.count
hash[:voc_events_count][:with_streaming] = filter_streaming('true', events).count
hash[:voc_events_count][:without_streaming] = filter_streaming('false', events).count
hash[:voc_events_count][:undefined_streaming] = filter_streaming('nil', events).count
JSON.pretty_generate(hash)
end
end
end
|
voc/eventkalender
|
webapp.rb
|
<filename>webapp.rb
# frozen_string_literal: true
require 'sinatra'
require 'sinatra/namespace'
require 'haml'
require_relative 'lib/eventkalender'
set :views, File.dirname(__FILE__) + '/views'
set :parser, Eventkalender::Parser.new
set :public_folder, File.dirname(__FILE__) + '/views/public'
set :sub_path, ''
# HTML pages
namespace settings.sub_path.to_s do
get '/' do
@events = settings.parser.events[:conferences].events.map do |event|
# orange: #FF8C00
<<-EOF
{
title: "#{event.name}",
start: "#{event.start_date}",
end: "#{event.end_date + 1}",
url: "#{event.description}",
color: '#28c3ab'
},
EOF
end << settings.parser.events[:meetings].events.map do |event|
# orange: #FF8C00
<<-EOF
{
title: "#{event.name}",
start: "#{event.start_date}",
end: "#{event.end_date}",
url: "#{event.description}",
color: 'orange'
},
EOF
end
@gotodate = if params[:gotodate]
@params[:gotodate]
else
Date.today
end
haml :index
end
get '/events.html' do
@events = filter(filter_params,
settings.parser.events[meetings_or_conferences].events)
haml :events
end
# Formats
get '/events.ical' do
content_type 'text/calendar'
events = filter
cal = settings.parser.to_ical_calendar(events)
cal.to_ical
end
get '/events.atom' do
content_type 'application/atom+xml'
events = filter
feed = settings.parser.events[meetings_or_conferences].to_atom(events)
feed.to_s
end
get '/events.txt' do
content_type 'text/plain'
events = filter
settings.parser.events[meetings_or_conferences].to_txt(events)
end
get '/events.json' do
content_type 'application/json'
events = filter
json = settings.parser.events[meetings_or_conferences].to_json(events)
json.to_s
end
end
# helper function
def filter_params
{ general: params[:filter], streaming: params[:streaming], idea: params[:idea] }
end
def meetings_or_conferences
params[:meetings].nil? ? :conferences : :meetings
end
# Filter for specific keywords or parameter.
# @todo
# Filtering for time and streaming is ugly implemented.
# Looping and checking multiple times should be removed, soon.
#
# @example Filter for past events
# parser.filter({ general: past, streaming: true }) #=> [#<Eventkalender::Conference:0x00000002ab5b88 … >, …]
#
# @param filter [Hash] used for filtering
# @option filter [String] :general Normal filter option
# @option filter [String] :streaming Streaming status
# @param events [Array<Event>, #events] witch schould be filtered
#
# @return [Array] with filtered events
def filter(filter = filter_params,
events = settings.parser.events[meetings_or_conferences].events)
filtered_events = case filter[:general]
# All past events
when /past/
events.find_all(&:past?)
# All upcoming events
when /upcoming/
events.find_all(&:upcoming?)
# Currently running events
when /now|today/
events.find_all(&:now?)
# Match a year
when /\d{4}/
events.find_all { |event| event.start_date.year == filter[:general].to_i }
# Return all events if no filter is set
when /meeting/
events.find_all { |event| event.class == Eventkalender::Meeting }
when /conference/
events.find_all { |event| event.class == Eventkalender::Conference }
# Return all events if no filter is set
else
events
end
# filter for idea events
# default: remove idea events
if filter[:idea] == 'true'
filtered_events
else
filtered_events = remove_idea_events(filtered_events)
end
filter_streaming(filter[:streaming], filtered_events)
end
# Filter for events with streaming status.
#
# @example Filter for events with streaming
# parser.filter_streaming('true') #=> [#<Eventkalender::Conference:0x000000036b6810 … @streaming=true>, …]
#
# @param filter [String] witch is used for filtering
# @param events [Array<Event>, #events] to filter
#
# @return [Array] events witch match the given filter
def filter_streaming(filter, events)
case filter
when /true|yes/
events.find_all(&:streaming)
when /false|no/
events.find_all { |event| event.streaming == false }
when /undefined|nil|null/
events.find_all { |e| e.streaming.nil? }
else
events
end
end
# Remove events with status idea
#
# @param events [Array<Event>, #events] to filter
# @return [Array] events with status idea
def remove_idea_events(events)
events.delete_if(&:idea?)
end
|
voc/eventkalender
|
spec/lib/eventkalender/scraper_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Scraper do
before(:each) do
@scraper = Eventkalender::Scraper.new
end
after(:each) do
@scraper = nil
end
describe '#new' do
# TODO: pending
end
describe '.scrape!' do
it 'should return Nokogiri::XML::Element object' do
expect(Eventkalender::Scraper.scrape!).to be_instance_of Array
expect(Eventkalender::Scraper.scrape!.first).to be_instance_of Hash
expect(Eventkalender::Scraper.scrape!.first[:page]).to be_instance_of Mechanize::Page
end
end
describe '#get_pages' do
it 'should return array with Mechanize::Page objects' do
expect(@scraper.get_pages).to be_instance_of Array
expect(@scraper.get_pages.first).to be_instance_of Hash
expect(@scraper.get_pages.first[:page]).to be_instance_of Mechanize::Page
end
it 'should be possible to change url for this function' do
stub_request(:get, 'http://c3voc.de/wiki/bla').to_return(body: 'bla')
pages = @scraper.get_pages([{ type: :conferences,
url: 'http://c3voc.de/wiki/bla',
xpath: "//*/div[@class='table dataaggregation']/descendant::table[1]" }])
expect(pages.first[:page].body).to eq 'bla'
end
end
describe '#get_tables' do
it 'should return an Array with Hashes defined with :table keys as Nokogiri::XML::Element' do
# TODO: just, wat. (first[:table].first)
expect(@scraper.get_tables.first[:table].first).to be_instance_of Nokogiri::XML::Element
end
end
end
|
voc/eventkalender
|
spec/webapp_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe 'Webpage eventkalender' do
# conferences
describe '/events.ical' do
it 'should return valid response on GET' do
get '/events.ical'
expect(last_response).to be_ok
end
it 'should return valid ical feed' do
get '/events.ical'
expect(last_response.body).to match(/END:VCALENDAR/)
expect(last_response.body).to match(/SUMMARY:FrOSCon/)
end
end
describe '/events.atom' do
it 'should return valid response on GET' do
get '/events.atom'
expect(last_response).to be_ok
end
it 'should return valid atom feed' do
get '/events.atom'
expect(RSS::Parser.parse(last_response.body)).to be_instance_of(RSS::Atom::Feed)
end
end
describe '/events.txt' do
it 'should return valid response on GET' do
get '/events.txt'
expect(last_response).to be_ok
end
it 'should return text data' do
get '/events.txt'
expect(last_response.body).to match(/31C3 - Hamburg/)
expect(last_response.status).to eq 200
end
end
describe '/events.json' do
it 'should return valid response on GET' do
get '/events.json'
expect(last_response).to be_ok
end
it 'should return valid json on GET' do
get '/events.json'
expect(JSON.parse(last_response.body)).to be_instance_of(Hash)
end
end
describe '/events.html' do
it 'should return valid response on GET' do
get '/events.html'
expect(last_response).to be_ok
end
it 'should render events html page on GET' do
get '/events.html'
expect(last_response.body).to match(/past and upcoming/)
end
it 'should render events html page with defined filter on GET' do
get '/events.html?filter=past'
expect(last_response.body).to match(/Berlin/)
expect(last_response.body).to match(/Hamburg/)
expect(last_response.body).not_to match(/Ziegeleipark/)
end
it 'should render event description as html link' do
get '/events.html'
expect(last_response.body).to match(%r{http://hacknplay.org})
expect(last_response.body).not_to match(%r{>keine webseite</a>})
end
end
# meetings
describe '/?meetings=yes' do
it 'should return valid response on GET' do
get '/?meetings=yes'
expect(last_response).to be_ok
end
it 'should render index template on GET' do
get '/?meetings=yes'
expect(last_response.body).to match(/c3voc events/)
end
end
describe '/events.ical?meetings=yes' do
it 'should return valid response on GET' do
get '/events.ical'
expect(last_response).to be_ok
end
it 'should return valid ical feed' do
get '/events.ical?meetings=yes'
expect(last_response.body).to match(/END:VCALENDAR/)
expect(last_response.body).to match(/SUMMARY:Mumble/)
end
end
describe '/events.atom?meetings=yes' do
it 'should return valid response on GET' do
get '/events.atom?meetings=yes'
expect(last_response).to be_ok
end
it 'should return valid atom feed' do
get '/events.atom?meetings=yes'
expect(RSS::Parser.parse(last_response.body)).to be_instance_of(RSS::Atom::Feed)
end
end
describe '/events.txt?meetings=yes' do
it 'should return valid response on GET' do
get '/events.txt'
expect(last_response).to be_ok
end
it 'should return text data' do
get '/events.txt?meetings=yes'
expect(last_response.body).to match(/Geekend 2014 - CCCB/)
expect(last_response.status).to eq 200
end
end
describe '/events.json?meetings=yes' do
it 'should return valid response on GET' do
get '/events.json?meetings=yes'
expect(last_response).to be_ok
end
it 'should return valid json on GET' do
get '/events.json?meetings=yes'
expect(JSON.parse(last_response.body)).to be_instance_of(Hash)
end
end
describe '/events.html?meetings=yes' do
it 'should return valid response on GET' do
get '/events.html?meetings=yes'
expect(last_response).to be_ok
end
it 'should render events html page on GET' do
get '/events.html?meetings=yes'
expect(last_response.body).to match(/past and upcoming/)
end
it 'should render events html page with defined filter on GET' do
get '/events.html?filter=past&meetings=yes'
expect(last_response.body).to match(/Geekend 2014/)
end
end
describe '/?meetings=yes' do
it 'should return valid response on GET' do
get '/?meetings=yes'
expect(last_response).to be_ok
end
it 'should render index template on GET' do
get '/?meetings=yes'
expect(last_response.body).to match(/c3voc events/)
end
end
end
|
voc/eventkalender
|
lib/eventkalender/event/conference.rb
|
<gh_stars>1-10
# frozen_string_literal: true
class Eventkalender
# Represents a voc event.
#
# @!attribute [rw] start_date
# @param date [String] witch represents start date of the event
# @return [Date] event start date
# @!attribute [rw] end_date
# @param date [String] witch represents end date of the event
# @return [Date] event end date
# @!attribute [rw] name
# @return [String] event name
# @!attribute [rw] location
# @return [String] event location
# @!attribute [rw] description
# @return [String] event description, in general it's used for event url
# @!attribute [rw] short_name
# @return [String] event synonym
# @!attribute [rw] wiki_path
# @return [String] event path in voc wiki
# @!attribute [rw] streaming
# @return [String] event streaming status
# @!attribute [rw] planing_status
# @return [String] event planing status
class Conference < Event
attr_reader :start_date, :end_date, :streaming, :buildup, :teardown
attr_accessor :wiki_path, :planing_status, :name, :location, :description,
:short_name
# Create new event object
#
# @param options [Hash] to create an event with.
# @option options [String] :name The event name
# @option options [String] :location The event location
# @option options [String] :start_date Events start date
# @option options [String] :end_date Events end date
# @option options [String] :description The event description
# @option options [String] :wiki_path The event path in c3voc wiki
# @option options [String] :short_name The event short name
# @option options [String] :streaming Planed event streaming status
# @option options [String] :planing_status Planed event status
# @option cases [Array] :cases Used onsite
# @option teardown [Date] teardown of the Event
# @option buildup [Date] :buildup of the Event
def initialize(options = {})
super(options)
# optional
@description = options[:description]
@wiki_path = options[:wiki_path]
@short_name = options[:short_name]
self.streaming = options[:streaming]
@planing_status = options[:planing_status]
self.cases = options[:cases]
@buildup = options[:buildup]
@teardown = options[:teardown]
end
# Setter for buildup.
#
# @example Setting events buildup date.
# event.buildup = "2014-05-23" #=> "2014-05-23"
#
# @param date [String] buildup date of a event to set
# @return [Date] converted and set buildup date
def buildup=(date)
@buildup = check_date_input(date)
end
# Setter for buildup.
#
# @example Setting events teardown date.
# event.buildup = "2014-05-23" #=> "2014-05-23"
#
# @param date [String] teardown date of a event to set
# @return [Date] converted and set teardown date
def teardown=(date)
@teardown = check_date_input(date)
end
# Convert event to ical.
#
# @example Convert event to ical object.
# event.to_ical #=> #<Icalendar::Event:0x00000002f02ee8 @name="VEVENT" … >
#
# @return [Icalendar::Event] converted ical event
def to_ical
Icalendar::Event.new.tap do |e|
e.summary = @name
e.location = @location
e.dtstart = Icalendar::Values::Date.new(@start_date.to_date)
e.dtend = Icalendar::Values::Date.new(@end_date.to_date + 1)
e.description = @description
end
end
# Setter for streaming.
#
# @example Setting events end date.
# event.streaming = "yes" #=> true
#
# @param status [String] streaming of an event to set
# @return [Boolean] converted and set streaming status
def streaming=(status)
@streaming = Eventkalender::Parser.detect_streaming(status)
end
# Setter for cases
#
# @param cases_string [string] from doku wiki
# @return [Array] room cases
def cases=(cases_string)
@cases = if cases_string.nil?
[]
else
cases_string.delete(' ').split(',')
end
end
# Getter for cases
#
# @return [Array] room cases
def cases
@cases
end
end
end
|
voc/eventkalender
|
lib/eventkalender/scraper.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'mechanize'
class Eventkalender
# Web crawler that can be found event table.
#
# @example Get event page.
# scraper = Eventkalender::Scraper.new
# scraper.get_page #=> #<Eventkalender::Scraper:0x0000000148c3c0 @url="http://c3voc.de/wiki/events", @xpath=" … ">
#
# @example Get event table without initialising a scraper object.
# Eventkalender::Scraper.scrape! #=> #<Nokogiri::XML::Element:0xbd5740 name="table" … >
#
# @!attribute [rw] url
# @return [String] URL for webpage that holds events.
# @!attribute [rw] xpath
# @return [String] XPATH to find event table.
# @!attribute [r] page
# @return [Mechanize::Page] That holds events.
# @attribute [r] table
# @return [Nokogiri::XML::Element] That holds events.
class Scraper
# web page to scrape
PAGES_TO_SCRAPE = [
{ type: :conferences,
url: 'https://c3voc.de/wiki/eventz',
xpath: '//*/descendant::table[1]' },
{ type: :meetings,
url: 'https://c3voc.de/wiki/meetingz',
xpath: '//*/descendant::table[1]' }
].freeze
attr_reader :pages, :tables
# Class initializer for scraper class.
#
# @example Create new scraper
# Eventkalender::Scraper.new #=> #<Eventkalender::Scraper:0x00000003eeb7d8 @url="…", @xpath="…">
#
# @param url [String, URL] to parse
# @param xpath [String, XPATH] to find event table
def initialize
@pages # TODO: should be removed?
end
# Instance method to run scraper.
#
# @example Start web page scraping with initialized scraper
# scraper.scrape #=> #<Nokogiri::XML::Element:0x1290224 name="table" … >
#
# @return [Nokogiri::XML::Element] scrapped event table
def scrape
get_tables
end
# Class method to scrape events page without initialize own scraper instance.
#
# @example Start scraper
# Eventkalender::Scraper.scrape! #=> #<Nokogiri::XML::Element:0x1290224 name="table" … >
#
# @return [Nokogiri::XML::Element] scrapped event table
def self.scrape!
scraper = new
scraper.scrape
end
# Initialize mechanize object to get events page.
#
# @param page [String] URL to scrape
# @return [Mechanize::Page] events page
def get_pages(urls = PAGES_TO_SCRAPE)
# Create agent
agent = Mechanize.new
agent.user_agent = "eventkalender/#{Eventkalender::VERSION} "\
'(https://github.com/voc/eventkalender)'
# create copy of PAGES_TO_SCRAPE
@pages = urls.clone
# Get web page
urls.each do |page|
page[:page] = agent.get(page[:url])
end
agent.shutdown
@pages
end
# Search xpath expression in events page and returned xml events table.
#
# @param xpath [Array] xpath pattern
# @return [Nokogiri::XML::Element] Events table
def get_tables(pages = get_pages)
pages.each do |page|
page[:table] = page[:page].search(page[:xpath])
page[:timestamp] = Time.now
end
pages
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.