style(format): run rubocop format autocorrect

This commit is contained in:
Luis Castro 2019-07-30 23:29:24 +02:00
parent 04a5eb039f
commit f0fd393be4
No known key found for this signature in database
GPG key ID: 0A8F33D4C4E27639
759 changed files with 14563 additions and 14380 deletions

50
Gemfile
View file

@ -1,14 +1,16 @@
# frozen_string_literal: true
source 'https://rubygems.org'
ruby '2.5.1'
gem 'rake'
gem 'rails', '= 5.2.3'
gem 'rake'
# https://stripe.com/docs/api
gem 'stripe'
# Compression of assets on heroku
# https://github.com/romanbsd/heroku-deflater
gem 'heroku-deflater', :group => :production
gem 'heroku-deflater', group: :production
# json serialization
# https://github.com/nesquena/rabl
@ -16,17 +18,17 @@ gem 'rabl'
gem 'parallel'
gem 'puma'
gem 'bootsnap', require: false
gem 'rack-timeout'
gem 'rack-ssl'
gem 'puma'
gem 'puma_worker_killer'
gem 'rack-ssl'
gem 'rack-timeout'
gem 'test-unit', '~> 3.0'
gem 'hamster'
gem 'test-unit', '~> 3.0'
gem 'aws-ses'
gem 'aws-sdk', '~> 1'
gem 'aws-ses'
# for blocking ip addressses
gem 'rack-attack'
@ -44,7 +46,6 @@ gem 'qx', path: 'gems/ruby-qx'
gem 'dalli'
gem 'memcachier'
gem 'param_validation', path: 'gems/ruby-param-validation'
# Print colorized text lol
@ -89,33 +90,32 @@ gem 'table_print'
gem 'bunny', '>= 2.6.3'
gem 'rails-i18n'
gem 'i18n-js'
gem 'countries'
gem 'i18n-js'
gem 'rails-i18n'
group :development, :ci do
gem 'traceroute'
gem 'debase'
gem 'ruby-debug-ide'
gem 'traceroute'
end
group :development, :ci, :test do
gem 'timecop'
gem 'pry'
#gem 'pry-byebug'
gem 'binding_of_caller'
gem 'rspec'
gem 'rspec-rails'
gem 'database_cleaner'
gem 'pry'
gem 'timecop'
# gem 'pry-byebug'
gem 'action_mailer_matchers'
gem 'binding_of_caller'
gem 'database_cleaner'
gem 'dotenv-rails'
gem 'ruby-prof', '0.15.9'
gem 'stripe-ruby-mock', '~> 2.4.1', :require => 'stripe_mock', git: 'https://github.com/commitchange/stripe-ruby-mock.git', :branch => '2.4.1'
gem 'factory_bot'
gem 'factory_bot_rails'
gem 'action_mailer_matchers'
gem 'factory_bot_rails'
gem 'rspec'
gem 'rspec-rails'
gem 'ruby-prof', '0.15.9'
gem 'simplecov', '~> 0.16.1', require: false
gem 'solargraph'
gem 'stripe-ruby-mock', '~> 2.4.1', require: 'stripe_mock', git: 'https://github.com/commitchange/stripe-ruby-mock.git', branch: '2.4.1'
end
group :test do
@ -139,6 +139,6 @@ gem 'grape'
gem 'grape-entity'
gem 'grape-swagger'
gem 'grape-swagger-entity'
gem 'grape_url_validator'
gem 'grape_logging'
gem 'grape_devise', path: 'gems/grape_devise'
gem 'grape_logging'
gem 'grape_url_validator'

View file

@ -1,7 +1,9 @@
#!/usr/bin/env rake
# frozen_string_literal: true
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require File.expand_path('config/application', __dir__)
Commitchange::Application.load_tasks

View file

@ -1,5 +1,7 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::API < Grape::API
format :json
mount Houdini::V1::API => '/v1'
end
end

View file

@ -1,22 +1,24 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
require 'houdini/v1/validations'
class Houdini::V1::API < Grape::API
logger.formatter = GrapeLogging::Formatters::Rails.new
use GrapeLogging::Middleware::RequestLogger, { logger: logger }
content_type :json, 'application/json'
default_format :json
rescue_from Grape::Exceptions::ValidationErrors do |e|
output = {errors: e}
error! output, 400
end
logger.formatter = GrapeLogging::Formatters::Rails.new
use GrapeLogging::Middleware::RequestLogger, logger: logger
content_type :json, 'application/json'
default_format :json
rescue_from Grape::Exceptions::ValidationErrors do |e|
output = { errors: e }
error! output, 400
end
#include Houdini::V1::Helpers::ApplicationHelper
mount Houdini::V1::Nonprofit => '/nonprofit'
# Additional mounts are added via generators above this line
# include Houdini::V1::Helpers::ApplicationHelper
mount Houdini::V1::Nonprofit => '/nonprofit'
# Additional mounts are added via generators above this line
# DON'T REMOVE THIS OR THE PREVIOUS LINES!!!
uri_for_host = URI.parse(Settings.api_domain&.url || Settings.cdn.url)
add_swagger_documentation \
host: "#{uri_for_host.host}#{uri_for_host.port ? ":#{uri_for_host.port}" : ""}",
schemes: [uri_for_host.scheme],
base_path: '/api/v1'
end
uri_for_host = URI.parse(Settings.api_domain&.url || Settings.cdn.url)
add_swagger_documentation \
host: "#{uri_for_host.host}#{uri_for_host.port ? ":#{uri_for_host.port}" : ''}",
schemes: [uri_for_host.scheme],
base_path: '/api/v1'
end

View file

@ -1,6 +1,8 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::BaseAPI < Grape::API
#helpers ApplicationHelper
# helpers ApplicationHelper
# helpers do
# def session
# env['rack.session']
@ -27,4 +29,4 @@ class Houdini::V1::BaseAPI < Grape::API
# allow_forgery_protection.nil? || allow_forgery_protection
# end
# end
end
end

View file

@ -1,4 +1,6 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::Entities::Nonprofit < Grape::Entity
expose :id
end
end

View file

@ -1,5 +1,7 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::Entities::ValidationError < Grape::Entity
expose :params, documentation: {type: 'String', desc: 'Params where the following had an error.', is_array: true}
expose :messages, documentation: {type:'String', desc: 'The validation messages for the params', is_array: true}
end
expose :params, documentation: { type: 'String', desc: 'Params where the following had an error.', is_array: true }
expose :messages, documentation: { type: 'String', desc: 'The validation messages for the params', is_array: true }
end

View file

@ -1,4 +1,6 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::Entities::ValidationErrors < Grape::Entity
expose :errors, documentation: {type: ValidationError, desc: 'errors', is_array:true}
end
expose :errors, documentation: { type: ValidationError, desc: 'errors', is_array: true }
end

View file

@ -1,22 +1,21 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
module Houdini::V1::Helpers::ApplicationHelper
extend Grape::API::Helpers
def session
env['rack.session']
env['rack.session']
end
def protect_against_forgery
unless verified_request?
error!('Unauthorized', 401)
end
error!('Unauthorized', 401) unless verified_request?
end
def verified_request?
!protect_against_forgery? || request.get? || request.head? ||
form_authenticity_token == request.headers['X-CSRF-Token'] ||
form_authenticity_token == request.headers['X-Csrf-Token']
form_authenticity_token == request.headers['X-CSRF-Token'] ||
form_authenticity_token == request.headers['X-Csrf-Token']
end
def form_authenticity_token
@ -24,11 +23,10 @@ module Houdini::V1::Helpers::ApplicationHelper
end
def protect_against_forgery?
allow_forgery_protection = Rails.configuration.action_controller.allow_forgery_protection
allow_forgery_protection = Rails.configuration.action_controller.allow_forgery_protection
allow_forgery_protection.nil? || allow_forgery_protection
end
# def rescue_ar_invalid( *class_to_hash)
# rescue_with ActiveRecord::RecordInvalid do |error|
# output = []
@ -40,6 +38,4 @@ module Houdini::V1::Helpers::ApplicationHelper
#
# end
# end
end

View file

@ -1,19 +1,20 @@
# frozen_string_literal: true
module Houdini::V1::Helpers::RescueHelper
require 'active_support/concern'
extend ActiveSupport::Concern
include Grape::DSL::Configuration
module ClassMethods
def rescue_ar_invalid( *class_to_hash)
rescue_with ActiveRecord::RecordInvalid do |error|
output = []
error.record.errors do |attr,message|
output.push({params: "#{class_to_hash[error.record.class]}['#{attr}']",
message: message})
def rescue_ar_invalid(*class_to_hash)
rescue_with ActiveRecord::RecordInvalid do |error|
output = []
error.record.errors do |attr, message|
output.push(params: "#{class_to_hash[error.record.class]}['#{attr}']",
message: message)
end
raise Grape::Exceptions::ValidationErrors, output
end
raise Grape::Exceptions::ValidationErrors.new(output)
end
end
end
end
end

View file

@ -1,10 +1,12 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::Nonprofit < Houdini::V1::BaseAPI
helpers Houdini::V1::Helpers::ApplicationHelper, Houdini::V1::Helpers::RescueHelper
helpers Houdini::V1::Helpers::ApplicationHelper, Houdini::V1::Helpers::RescueHelper
before do
protect_against_forgery
end
before do
protect_against_forgery
end
desc 'Return a nonprofit.' do
success Houdini::V1::Entities::Nonprofit
@ -18,103 +20,92 @@ class Houdini::V1::Nonprofit < Houdini::V1::BaseAPI
present np, as: Houdini::V1::Entities::Nonprofit
end
end
desc 'Register a nonprofit' do
success Houdini::V1::Entities::Nonprofit
#this needs to be a validation an array
failure [{code:400, message:'Validation Errors', model: Houdini::V1::Entities::ValidationErrors}]
# this needs to be a validation an array
failure [{ code: 400, message: 'Validation Errors', model: Houdini::V1::Entities::ValidationErrors }]
end
params do
requires :nonprofit, type: Hash do
requires :name, type:String, desc: 'Organization Name', allow_blank: false, documentation: { param_type: 'body' }
optional :website, type:String, desc: 'Organization website URL', allow_blank:true, regexp: URI::regexp, documentation: { param_type: 'body' }, coerce_with: ->(url) {
requires :nonprofit, type: Hash do
requires :name, type: String, desc: 'Organization Name', allow_blank: false, documentation: { param_type: 'body' }
optional :website, type: String, desc: 'Organization website URL', allow_blank: true, regexp: URI::DEFAULT_PARSER.make_regexp, documentation: { param_type: 'body' }, coerce_with: lambda { |url|
coerced_url = url
unless (url =~ /\Ahttp:\/\/.*/i || url =~ /\Ahttps:\/\/.*/i)
coerced_url = 'http://'+ coerced_url
unless url =~ %r{\Ahttp://.*}i || url =~ %r{\Ahttps://.*}i
coerced_url = 'http://' + coerced_url
end
coerced_url
}
requires :zip_code, type:String, allow_blank: false, desc: "Organization Address ZIP Code", documentation: { param_type: 'body' }
requires :state_code, type:String, allow_blank: false, desc: "Organization Address State Code", documentation: { param_type: 'body' }
requires :city, type:String, allow_blank: false, desc: "Organization Address City", documentation: { param_type: 'body' }
optional :email, type:String, desc: 'Organization email (public)', regexp: Email::Regex, documentation: { param_type: 'body' }
optional :phone, type:String, desc: 'Organization phone (public)', documentation: { param_type: 'body' }
requires :zip_code, type: String, allow_blank: false, desc: 'Organization Address ZIP Code', documentation: { param_type: 'body' }
requires :state_code, type: String, allow_blank: false, desc: 'Organization Address State Code', documentation: { param_type: 'body' }
requires :city, type: String, allow_blank: false, desc: 'Organization Address City', documentation: { param_type: 'body' }
optional :email, type: String, desc: 'Organization email (public)', regexp: Email::Regex, documentation: { param_type: 'body' }
optional :phone, type: String, desc: 'Organization phone (public)', documentation: { param_type: 'body' }
end
requires :user, type: Hash do
requires :name, type:String, desc: 'Full name', allow_blank:false, documentation: { param_type: 'body' }
requires :email, type:String, desc: 'Username', allow_blank: false, documentation: { param_type: 'body' }
requires :password, type:String, desc: 'Password', allow_blank: false, is_equal_to: :password_confirmation, documentation: { param_type: 'body' }
requires :password_confirmation, type:String, desc: 'Password confirmation', allow_blank: false, documentation: { param_type: 'body' }
requires :name, type: String, desc: 'Full name', allow_blank: false, documentation: { param_type: 'body' }
requires :email, type: String, desc: 'Username', allow_blank: false, documentation: { param_type: 'body' }
requires :password, type: String, desc: 'Password', allow_blank: false, is_equal_to: :password_confirmation, documentation: { param_type: 'body' }
requires :password_confirmation, type: String, desc: 'Password confirmation', allow_blank: false, documentation: { param_type: 'body' }
end
end
post do
declared_params = declared(params)
np = nil
u = nil
Qx.transaction do
np = Nonprofit.new(OnboardAccounts.set_nonprofit_defaults(declared_params[:nonprofit]))
begin
np = Nonprofit.new(OnboardAccounts.set_nonprofit_defaults(declared_params[:nonprofit]))
begin
np.save!
rescue ActiveRecord::RecordInvalid => e
if (e.record.errors[:slug])
begin
slug = SlugNonprofitNamingAlgorithm.new(np.state_code_slug, np.city_slug).create_copy_name(np.slug)
np.slug = slug
np.save!
rescue UnableToCreateNameCopyError
raise Grape::Exceptions::ValidationErrors.new(errors:[Grape::Exceptions::Validation.new(
params: ["nonprofit[name]"],
message: "has an invalid slug. Contact support for help."
)])
end
else
raise e
end
end
u = User.new(declared_params[:user])
u.save!
role = u.roles.build(host: np, name: 'nonprofit_admin')
role.save!
billing_plan = BillingPlan.find(Settings.default_bp.id)
b_sub = np.build_billing_subscription(billing_plan: billing_plan, status: 'active')
b_sub.save!
np.save!
rescue ActiveRecord::RecordInvalid => e
class_to_name = {Nonprofit => 'nonprofit', User => 'user'}
if class_to_name[e.record.class]
errors = e.record.errors.keys.map {|k|
errors = e.record.errors[k].uniq
errors.map{|error| Grape::Exceptions::Validation.new(
params: ["#{class_to_name[e.record.class]}[#{k.to_s}]"],
message: error
)}
}
raise Grape::Exceptions::ValidationErrors.new(errors:errors.flatten)
if e.record.errors[:slug]
begin
slug = SlugNonprofitNamingAlgorithm.new(np.state_code_slug, np.city_slug).create_copy_name(np.slug)
np.slug = slug
np.save!
rescue UnableToCreateNameCopyError
raise Grape::Exceptions::ValidationErrors.new(errors: [Grape::Exceptions::Validation.new(
params: ['nonprofit[name]'],
message: 'has an invalid slug. Contact support for help.'
)])
end
else
raise e
end
end
u = User.new(declared_params[:user])
u.save!
role = u.roles.build(host: np, name: 'nonprofit_admin')
role.save!
billing_plan = BillingPlan.find(Settings.default_bp.id)
b_sub = np.build_billing_subscription(billing_plan: billing_plan, status: 'active')
b_sub.save!
rescue ActiveRecord::RecordInvalid => e
class_to_name = { Nonprofit => 'nonprofit', User => 'user' }
if class_to_name[e.record.class]
errors = e.record.errors.keys.map do |k|
errors = e.record.errors[k].uniq
errors.map do |error|
Grape::Exceptions::Validation.new(
params: ["#{class_to_name[e.record.class]}[#{k}]"],
message: error
)
end
end
raise Grape::Exceptions::ValidationErrors.new(errors: errors.flatten)
else
raise e
end
end
#onboard callback
# onboard callback
present np, with: Houdini::V1::Entities::Nonprofit
end
end
end

View file

@ -1,2 +1,4 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
require 'houdini/v1/validators/is_equal_to'
require 'houdini/v1/validators/is_equal_to'

View file

@ -1,8 +1,10 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class Houdini::V1::Validators::IsEqualTo < Grape::Validations::Base
def validate_param!(attr_name, params)
if params[attr_name] != params[@option]
fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name), @scope.full_name(@option)], message: message(:is_equal_to)
raise Grape::Exceptions::Validation, params: [@scope.full_name(attr_name), @scope.full_name(@option)], message: message(:is_equal_to)
end
end
end
end

View file

@ -1,10 +1,10 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class ActivitiesController < ApplicationController
before_action :authenticate_user!, only: [:create]
before_action :authenticate_user!, only: [:create]
def create
json_saved Activity.create(params[:activity])
end
def create
json_saved Activity.create(params[:activity])
end
end

View file

@ -1,174 +1,178 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class ApplicationController < ActionController::Base
before_action :set_locale, :redirect_to_maintenance
before_action :set_locale, :redirect_to_maintenance
protect_from_forgery
protect_from_forgery
helper_method \
:current_role?,
:current_nonprofit_user?,
:administered_nonprofit,
helper_method \
:current_role?,
:current_nonprofit_user?,
:administered_nonprofit,
:nonprofit_in_trial?,
:current_plan_tier #int
:current_plan_tier # int
def set_locale
if params[:locale] && Settings.available_locales.include?(params[:locale])
I18n.locale = params[:locale]
else
I18n.locale = Settings.language
end
end
def set_locale
if params[:locale] && Settings.available_locales.include?(params[:locale])
I18n.locale = params[:locale]
else
I18n.locale = Settings.language
end
end
def redirect_to_maintenance
if (Settings&.maintenance&.maintenance_mode && !current_user)
unless (self.class == Users::SessionsController &&
((Settings.maintenance.maintenance_token && params[:maintenance_token] == Settings.maintenance.maintenance_token) || params[:format] == 'json'))
redirect_to Settings.maintenance.maintenance_page
end
end
end
def redirect_to_maintenance
if Settings&.maintenance&.maintenance_mode && !current_user
unless self.class == Users::SessionsController &&
((Settings.maintenance.maintenance_token && params[:maintenance_token] == Settings.maintenance.maintenance_token) || params[:format] == 'json')
redirect_to Settings.maintenance.maintenance_page
end
end
end
protected
protected
def json_saved(model, msg=nil)
if model.valid?
flash[:notice] = msg if msg
render json: model, status: 200
else
render json: model.errors.full_messages, status: :unprocessable_entity
end
end
def json_saved(model, msg = nil)
if model.valid?
flash[:notice] = msg if msg
render json: model, status: 200
else
render json: model.errors.full_messages, status: :unprocessable_entity
end
end
# A response helper for use with the param_validation gem
# use like: render_json{ UpdateUsers.update(params[:user]) }
# will catch and pretty print exceptions using the rails loggers
def render_json(&block)
begin
result = {status: 200, json: yield(block)}
result = { status: 200, json: yield(block) }
rescue ParamValidation::ValidationError => e
logger.info "422: #{e}".red.bold
#logger.info ">>".bold.red + " #{{'Failed key name' => e.data[:key], 'Value' => e.data[:val], 'Failed validator' => e.data[:name]}}".red
result = {status: 422, json: {error: e.message}}
rescue CCOrgError => e
logger.info "422: #{e}".red.bold
result = {status: 422, json: {error: e.message}}
# logger.info ">>".bold.red + " #{{'Failed key name' => e.data[:key], 'Value' => e.data[:val], 'Failed validator' => e.data[:name]}}".red
result = { status: 422, json: { error: e.message } }
rescue CCOrgError => e
logger.info "422: #{e}".red.bold
result = { status: 422, json: { error: e.message } }
rescue ActiveRecord::RecordNotFound => e
logger.info "404: #{e}".red.bold
result = {status: 404, json: {error: e.message}}
rescue AuthenticationError => e
logger.info "401: #{e}".red.bold
result = {status: 401, json: {error: e.message}}
rescue ExpiredTokenError => e
logger.info "422: #{e}".red.bold
result = {status: 422, json: {error: e.message}}
result = { status: 404, json: { error: e.message } }
rescue AuthenticationError => e
logger.info "401: #{e}".red.bold
result = { status: 401, json: { error: e.message } }
rescue ExpiredTokenError => e
logger.info "422: #{e}".red.bold
result = { status: 422, json: { error: e.message } }
rescue Exception => e # a non-validation related exception
logger.error "500: #{e}".red.bold
logger.error e.backtrace.take(5).map{|l| ">>".red.bold + " #{l}"}.join("\n").red
result = {status: 500, json: {error: e.message, backtrace: e.backtrace}}
logger.error e.backtrace.take(5).map { |l| '>>'.red.bold + " #{l}" }.join("\n").red
result = { status: 500, json: { error: e.message, backtrace: e.backtrace } }
end
render result
end
# Test that within the last 5 minutes, the user has confirmed their password
def password_was_confirmed(token)
session[:pw_token] == token && Chronic.parse(session[:pw_timestamp]) >= 5.minutes.ago.utc
end
# Test that within the last 5 minutes, the user has confirmed their password
def password_was_confirmed(token)
session[:pw_token] == token && Chronic.parse(session[:pw_timestamp]) >= 5.minutes.ago.utc
end
def store_location
referrer = request.fullpath
no_redirects = ['/users', '/signup', '/signin', '/users/sign_in', '/users/sign_up', '/users/password', '/users/sign_out', /.*\.json.*/, /.*auth\/facebook.*/]
unless request.format.symbol == :json || no_redirects.map{|p| referrer.match(p)}.any?
session[:previous_url] = referrer
end
end
def store_location
referrer = request.fullpath
no_redirects = ['/users', '/signup', '/signin', '/users/sign_in', '/users/sign_up', '/users/password', '/users/sign_out', /.*\.json.*/, %r{.*auth/facebook.*}]
unless request.format.symbol == :json || no_redirects.map { |p| referrer.match(p) }.any?
session[:previous_url] = referrer
end
end
def block_with_sign_in(msg=nil)
store_location
def block_with_sign_in(msg = nil)
store_location
if current_user
flash[:notice] = "It looks like you're not allowed to access that page. If this seems like a mistake, please contact #{Settings.mailer.email}"
redirect_to root_path
else
msg ||= 'We need to sign you in before you can do that.'
redirect_to new_user_session_path, :flash => {:error => msg}
redirect_to new_user_session_path, flash: { error: msg }
end
end
end
def authenticate_user!(options={})
block_with_sign_in unless current_user
end
def authenticate_user!(_options = {})
block_with_sign_in unless current_user
end
def authenticate_confirmed_user!
if !current_user
block_with_sign_in
elsif !current_user.confirmed? && !current_role?([:super_associate, :super_admin])
redirect_to new_user_confirmation_path, flash: {error: 'You need to confirm your account to do that.'}
end
end
def authenticate_confirmed_user!
if !current_user
block_with_sign_in
elsif !current_user.confirmed? && !current_role?(%i[super_associate super_admin])
redirect_to new_user_confirmation_path, flash: { error: 'You need to confirm your account to do that.' }
end
end
def authenticate_super_associate!
unless current_role?(:super_admin) || current_role?(:super_associate)
block_with_sign_in 'Please login.'
end
end
def authenticate_super_associate!
unless current_role?(:super_admin) || current_role?(:super_associate)
block_with_sign_in 'Please login.'
end
end
def authenticate_super_admin!
unless current_role?(:super_admin)
block_with_sign_in 'Please login.'
end
end
def authenticate_super_admin!
block_with_sign_in 'Please login.' unless current_role?(:super_admin)
end
def current_role?(role_names, host_id = nil)
def current_role?(role_names, host_id = nil)
return false unless current_user
role_names = Array(role_names)
key = "current_role_user_#{current_user_id}_names_#{role_names.join("_")}_host_#{host_id}"
QueryRoles.user_has_role?(current_user.id, role_names, host_id)
end
def nonprofit_in_trial?(npo_id=nil)
role_names = Array(role_names)
key = "current_role_user_#{current_user_id}_names_#{role_names.join('_')}_host_#{host_id}"
QueryRoles.user_has_role?(current_user.id, role_names, host_id)
end
def nonprofit_in_trial?(npo_id = nil)
return false if !npo_id && !administered_nonprofit
npo_id ||= administered_nonprofit.id
key = "in_trial_user_#{current_user_id}_nonprofit_#{npo_id}"
QueryBillingSubscriptions.currently_in_trial?(npo_id)
end
def current_plan_tier(npo_id=nil)
def current_plan_tier(npo_id = nil)
return 0 if !npo_id && !administered_nonprofit
npo_id ||= administered_nonprofit.id
return 2 if current_role?(:super_admin)
key = "plan_tier_user_#{current_user_id}_nonprofit_#{npo_id}"
return 2 if current_role?(:super_admin)
key = "plan_tier_user_#{current_user_id}_nonprofit_#{npo_id}"
administered_nonprofit ? QueryBillingSubscriptions.plan_tier(npo_id) : 0
end
end
def administered_nonprofit
return nil unless current_user
key = "administered_nonprofit_user_#{current_user_id}_nonprofit"
Nonprofit.where(id: QueryRoles.host_ids(current_user_id, [:nonprofit_admin, :nonprofit_associate])).last
end
def administered_nonprofit
return nil unless current_user
# devise config
key = "administered_nonprofit_user_#{current_user_id}_nonprofit"
Nonprofit.where(id: QueryRoles.host_ids(current_user_id, %i[nonprofit_admin nonprofit_associate])).last
end
def after_sign_in_path_for(resource)
request.env['omniauth.origin'] || session[:previous_url] || root_path
end
# devise config
def after_sign_up_path_for(resource)
request.env['omniauth.origin'] || session[:previous_url] || root_path
end
def after_sign_in_path_for(_resource)
request.env['omniauth.origin'] || session[:previous_url] || root_path
end
def after_update_path_for(resource)
profile_path(current_user.profile)
end
def after_sign_up_path_for(_resource)
request.env['omniauth.origin'] || session[:previous_url] || root_path
end
def after_inactive_sign_up_path_for(resource)
profile_path(current_user.profile)
end
def after_update_path_for(_resource)
profile_path(current_user.profile)
end
# /devise config
def after_inactive_sign_up_path_for(_resource)
profile_path(current_user.profile)
end
private
# /devise config
def current_user_id
current_user && current_user.id
end
private
def current_user_id
current_user&.id
end
end

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class AwsPresignedPostsController < ApplicationController
before_action :authenticate_user!
@ -7,12 +9,12 @@ class AwsPresignedPostsController < ApplicationController
# http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/PresignedPost.html
def create
uuid = SecureRandom.uuid
p = S3Bucket.presigned_post({
p = S3Bucket.presigned_post(
key: "tmp/#{uuid}/${filename}",
success_action_status: 201,
acl: 'public-read',
expiration: 30.days.from_now
})
)
render json: {
s3_presigned_post: p.fields.to_json,
@ -20,5 +22,4 @@ class AwsPresignedPostsController < ApplicationController
s3_uuid: uuid
}
end
end

View file

@ -1,30 +1,32 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class BillingSubscriptionsController < ApplicationController
include Controllers::NonprofitHelper
include Controllers::NonprofitHelper
before_action :authenticate_nonprofit_admin!
before_action :authenticate_nonprofit_admin!
def create_trial
render JsonResp.new(params){|params|
render JsonResp.new(params) do |_params|
requires(:nonprofit_id).as_int
requires(:stripe_plan_id).as_string
}.when_valid{|params|
end.when_valid do |params|
InsertBillingSubscriptions.trial(params[:nonprofit_id], params[:stripe_plan_id])
}
end
end
def create
def create
@nonprofit ||= Nonprofit.find(params[:nonprofit_id])
@subscription = BillingSubscription.create_with_stripe(@nonprofit, params[:billing_subscription])
json_saved(@subscription, "Success! You are subscribed to #{Settings.general.name}.")
end
@subscription = BillingSubscription.create_with_stripe(@nonprofit, params[:billing_subscription])
json_saved(@subscription, "Success! You are subscribed to #{Settings.general.name}.")
end
# post /nonprofits/:nonprofit_id/billing_subscription/cancel
def cancel
@result = CancelBillingSubscription.with_stripe(@nonprofit)
flash[:notice] = "Your subscription has been cancelled. We'll email you soon with exports."
def cancel
@result = CancelBillingSubscription.with_stripe(@nonprofit)
flash[:notice] = "Your subscription has been cancelled. We'll email you soon with exports."
redirect_to root_url
end
end
# get nonprofits/:nonprofit_id/billing_subscription/cancellation
def cancellation

View file

@ -1,12 +1,14 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class ButtonDebugController < ApplicationController
def embedded
@np = params[:id] || 1
respond_to { |format| format.html{render layout: 'layouts/empty'} }
respond_to { |format| format.html { render layout: 'layouts/empty' } }
end
def button
@np = params[:id] || 1
respond_to { |format| format.html{render layout: 'layouts/empty'} }
respond_to { |format| format.html { render layout: 'layouts/empty' } }
end
end

View file

@ -1,29 +1,31 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class CampaignGiftOptionsController < ApplicationController
include Controllers::CampaignHelper
include Controllers::CampaignHelper
before_action :authenticate_campaign_editor!, only: [:create, :destroy, :update, :update_order]
before_action :authenticate_campaign_editor!, only: %i[create destroy update update_order]
def index
@gift_options = current_campaign.campaign_gift_options.order('"order", amount_recurring, amount_one_time')
render json: {data: @gift_options}
end
def index
@gift_options = current_campaign.campaign_gift_options.order('"order", amount_recurring, amount_one_time')
render json: { data: @gift_options }
end
def show
render json: {data: current_campaign.campaign_gift_options.find(params[:id])}
end
def show
render json: { data: current_campaign.campaign_gift_options.find(params[:id]) }
end
def create
campaign = current_campaign
json_saved CreateCampaignGiftOption.create(campaign, params[:campaign_gift_option]),
'Gift option successfully created!'
end
def create
campaign = current_campaign
json_saved CreateCampaignGiftOption.create(campaign, params[:campaign_gift_option]),
'Gift option successfully created!'
end
def update
@campaign = current_campaign
gift_option = @campaign.campaign_gift_options.find params[:id]
json_saved UpdateCampaignGiftOption.update(gift_option, params[:campaign_gift_option]), 'Successfully updated'
end
def update
@campaign = current_campaign
gift_option = @campaign.campaign_gift_options.find params[:id]
json_saved UpdateCampaignGiftOption.update(gift_option, params[:campaign_gift_option]), 'Successfully updated'
end
# put /nonprofits/:nonprofit_id/campaigns/:campaign_id/campaign_gift_options/update_order
# Pass in {data: [{id: 1, order: 1}]}
@ -32,9 +34,9 @@ class CampaignGiftOptionsController < ApplicationController
render json: updated_gift_options
end
def destroy
@campaign = current_campaign
def destroy
@campaign = current_campaign
render_json { DeleteCampaignGiftOption.delete(@campaign, params[:id])}
end
render_json { DeleteCampaignGiftOption.delete(@campaign, params[:id]) }
end
end

View file

@ -1,8 +1,9 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class CampaignGiftsController < ApplicationController
# post /campaign_gifts
def create
json_saved CreateCampaignGift.create params[:campaign_gift]
end
def create
json_saved CreateCampaignGift.create params[:campaign_gift]
end
end

View file

@ -1,51 +1,51 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
module Campaigns; class CampaignGiftOptionsController < ApplicationController
include Controllers::CampaignHelper
module Campaigns
class CampaignGiftOptionsController < ApplicationController
include Controllers::CampaignHelper
before_action :authenticate_campaign_editor!, only: [:create, :destroy, :update, :update_order, :report]
before_action :authenticate_campaign_editor!, only: %i[create destroy update update_order report]
def report
respond_to do |format|
format.json do
render json: QueryCampaignGifts.report_metrics(current_campaign.id)
end
end
end
def report
respond_to do |format|
format.json do
render json: QueryCampaignGifts.report_metrics(current_campaign.id)
end
end
end
def index
@gift_options = current_campaign.campaign_gift_options.order('"order", amount_recurring, amount_one_time')
render json: { data: @gift_options }
end
def show
render json: { data: current_campaign.campaign_gift_options.find(params[:id]) }
end
def index
@gift_options = current_campaign.campaign_gift_options.order('"order", amount_recurring, amount_one_time')
render json: {data: @gift_options}
end
def create
campaign = current_campaign
json_saved CreateCampaignGiftOption.create(campaign, params[:campaign_gift_option]),
'Gift option successfully created!'
end
def show
render json: {data: current_campaign.campaign_gift_options.find(params[:id])}
end
def update
@campaign = current_campaign
gift_option = @campaign.campaign_gift_options.find params[:id]
json_saved UpdateCampaignGiftOption.update(gift_option, params[:campaign_gift_option]), 'Successfully updated'
end
def create
campaign = current_campaign
json_saved CreateCampaignGiftOption.create(campaign, params[:campaign_gift_option]),
'Gift option successfully created!'
end
# put /nonprofits/:nonprofit_id/campaigns/:campaign_id/campaign_gift_options/update_order
# Pass in {data: [{id: 1, order: 1}]}
def update_order
updated_gift_options = UpdateOrder.with_data('campaign_gift_options', params[:data])
render json: updated_gift_options
end
def update
@campaign = current_campaign
gift_option = @campaign.campaign_gift_options.find params[:id]
json_saved UpdateCampaignGiftOption.update(gift_option, params[:campaign_gift_option]), 'Successfully updated'
end
# put /nonprofits/:nonprofit_id/campaigns/:campaign_id/campaign_gift_options/update_order
# Pass in {data: [{id: 1, order: 1}]}
def update_order
updated_gift_options = UpdateOrder.with_data('campaign_gift_options', params[:data])
render json: updated_gift_options
end
def destroy
@campaign = current_campaign
render_json { DeleteCampaignGiftOption.delete(@campaign, params[:id])}
end
def destroy
@campaign = current_campaign
render_json { DeleteCampaignGiftOption.delete(@campaign, params[:id]) }
end
end; end

View file

@ -1,19 +1,20 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
module Campaigns
class DonationsController < ApplicationController
include Controllers::CampaignHelper
class DonationsController < ApplicationController
include Controllers::CampaignHelper
before_action :authenticate_campaign_editor!, only: [:index]
def index
respond_to do |format|
format.csv do
file_date = Date.today.strftime("%m-%d-%Y")
donations = QueryDonations.campaign_export(current_campaign.id)
send_data(Format::Csv.from_vectors(donations), filename: "campaign-donations-#{file_date}.csv")
end
end
end
before_action :authenticate_campaign_editor!, only: [:index]
end
def index
respond_to do |format|
format.csv do
file_date = Date.today.strftime('%m-%d-%Y')
donations = QueryDonations.campaign_export(current_campaign.id)
send_data(Format::Csv.from_vectors(donations), filename: "campaign-donations-#{file_date}.csv")
end
end
end
end
end

View file

@ -1,22 +1,23 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
module Campaigns
class SupportersController < ApplicationController
include Controllers::CampaignHelper
class SupportersController < ApplicationController
include Controllers::CampaignHelper
before_action :authenticate_campaign_editor!, only: [:index]
before_action :authenticate_campaign_editor!, only: [:index]
def index
@panels_layout = true
@nonprofit = current_nonprofit
@campaign = current_campaign
respond_to do |format|
format.json do
render json: QuerySupporters.campaign_list(@nonprofit.id, @campaign.id, params)
end
format.html
end
end
def index
@panels_layout = true
@nonprofit = current_nonprofit
@campaign = current_campaign
end
respond_to do |format|
format.json do
render json: QuerySupporters.campaign_list(@nonprofit.id, @campaign.id, params)
end
format.html
end
end
end
end

View file

@ -1,15 +1,17 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class CampaignsController < ApplicationController
include Controllers::CampaignHelper
helper_method :current_campaign_editor?
before_action :authenticate_confirmed_user!, only: [:create, :name_and_id, :duplicate]
before_action :authenticate_campaign_editor!, only: [:update, :soft_delete]
before_action :check_nonprofit_status, only: [:index, :show]
before_action :authenticate_confirmed_user!, only: %i[create name_and_id duplicate]
before_action :authenticate_campaign_editor!, only: %i[update soft_delete]
before_action :check_nonprofit_status, only: %i[index show]
def index
@nonprofit = current_nonprofit
if (current_nonprofit_user?)
if current_nonprofit_user?
@campaigns = @nonprofit.campaigns.includes(:nonprofit).not_deleted.order('created_at desc')
@deleted_campaigns = @nonprofit.campaigns.includes(:nonprofit).deleted.order('created_at desc')
else
@ -70,14 +72,11 @@ class CampaignsController < ApplicationController
# post 'nonprofits/:np_id/campaigns/:campaign_id/duplicate'
def duplicate
render_json {
render_json do
InsertDuplicate.campaign(current_campaign.id, current_user.profile.id)
}
end
end
def soft_delete
current_campaign.update_attribute(:deleted, params[:delete])
render json: {}
@ -101,17 +100,17 @@ class CampaignsController < ApplicationController
end
def peer_to_peer
session[:donor_signup_url] = request.env["REQUEST_URI"]
session[:donor_signup_url] = request.env['REQUEST_URI']
@nonprofit = Nonprofit.find_by_id(params[:npo_id])
@parent_campaign = Campaign.find_by_id(params[:campaign_id])
if params[:campaign_id].present? && !@parent_campaign
raise ActionController::RoutingError.new('Not Found')
raise ActionController::RoutingError, 'Not Found'
end
if current_user
@profile = current_user.profile
if (@parent_campaign)
if @parent_campaign
@child_campaign = Campaign.where(
profile_id: @profile.id,
parent_campaign_id: @parent_campaign.id
@ -124,7 +123,7 @@ class CampaignsController < ApplicationController
def check_nonprofit_status
if !current_role?(:super_admin) && !current_nonprofit.published
raise ActionController::RoutingError.new('Not Found')
raise ActionController::RoutingError, 'Not Found'
end
end
end

View file

@ -1,22 +1,22 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class CardsController < ApplicationController
before_action :authenticate_user!, except: [:create]
before_action :authenticate_user!, :except => [:create]
# post /cards
def create
# post /cards
def create
acct = Supporter.find(params[:card][:holder_id]).nonprofit.stripe_account_id
render(
JsonResp.new(params) do |d|
JsonResp.new(params) do |_d|
requires(:card).nested do
requires(:name, :stripe_card_token).as_string
requires(:holder_id).as_int
requires(:holder_type).one_of('Supporter')
end
end.when_valid do |d|
InsertCard.with_stripe(d[:card], acct, params[:event_id], current_user)
InsertCard.with_stripe(d[:card], acct, params[:event_id], current_user)
end
)
end
end
end

View file

@ -1,19 +1,19 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class DirectDebitDetailsController < ApplicationController
# POST /sepa
# This endpoint is used for saving direct debit account details
# when SEPA payment is selected in the donation widget. Actual charge is
# happening offline, after donations are exported to an external CRM.
def create
render(
JsonResp.new(params) do |data|
JsonResp.new(params) do |_data|
requires(:supporter_id).as_int
requires(:sepa_params).nested do
requires(:iban, :name, :bic).as_string
end
end.when_valid do |data|
end.when_valid do |_data|
InsertDirectDebitDetail.execute(params)
end
)

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class EmailSettingsController < ApplicationController
include Controllers::NonprofitHelper
@ -15,6 +17,4 @@ class EmailSettingsController < ApplicationController
user = current_role?(:super_admin) ? User.find(params[:user_id]) : current_user
render json: UpdateEmailSettings.save(params[:nonprofit_id], user.id, params[:email_settings])
end
end

View file

@ -1,11 +1,12 @@
# frozen_string_literal: true
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
class EmailsController < ApplicationController
before_action :authenticate_user!
def create
email = params[:email]
GenericMailer.delay.generic_mail(email[:from_email], email[:from_name], email[:message], email[:subject], email[:to_email], email[:to_name])
render :json => {:notification => 'Email successfully sent'}, :status => :created
end