Corrections auto avec standardrb

This commit is contained in:
Jérémy Lecour 2023-02-26 15:09:08 +01:00 committed by Jérémy Lecour
parent b27a63ba9c
commit 2dc085be6f
33 changed files with 142 additions and 162 deletions

13
Gemfile
View File

@ -37,7 +37,7 @@ gem "redis", "~> 4.0"
gem "bcrypt", "~> 3.1.7"
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]
gem "tzinfo-data", platforms: %i[mingw mswin x64_mingw jruby]
# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false
@ -53,14 +53,14 @@ gem "heroicon"
# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"
gem 'pundit', "~> 2.1.1"
gem "pundit", "~> 2.1.1"
gem "ransack", "~> 2.5.0"
gem "kaminari", "~> 1.2.2"
group :development, :test do
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
gem "debug", platforms: %i[ mri mingw x64_mingw ]
gem "debug", platforms: %i[mri mingw x64_mingw]
gem "standard"
end
@ -77,15 +77,14 @@ group :development do
gem "capistrano", "~> 3.16", require: false
gem "capistrano-rails", require: false
gem "capistrano-rbenv", require: false
gem 'capistrano3-puma', require: false
gem "capistrano3-puma", require: false
# Necessary for elliptic curve SSH keys
# gem 'rbnacl', ">= 3.2", "<5.0"
# gem 'rbnacl-libsodium'
gem 'bcrypt_pbkdf', ">= 1.0", "<2.0"
gem 'ed25519', ">= 1.2", "< 2.0"
gem "bcrypt_pbkdf", ">= 1.0", "<2.0"
gem "ed25519", ">= 1.2", "< 2.0"
gem "openssl", "< 3.0.0"
end
group :test do

View File

@ -1,28 +1,28 @@
class Api::V1::ApiKeysController < Api::V1::BaseController
# Require API key authentication
prepend_before_action :authenticate_with_api_key!, only: %i[index destroy]
# Require API key authentication
prepend_before_action :authenticate_with_api_key!, only: %i[index destroy]
def index
render json: current_bearer.api_keys
end
def index
render json: current_bearer.api_keys
end
def create
authenticate_with_http_basic do |email, password|
user = User.find_by email: email
def create
authenticate_with_http_basic do |email, password|
user = User.find_by email: email
if user&.authenticate(password)
api_key = user.api_keys.create! token: SecureRandom.hex
if user&.authenticate(password)
api_key = user.api_keys.create! token: SecureRandom.hex
render json: api_key, status: :created and return
end
render json: api_key, status: :created and return
end
render status: :unauthorized
end
def destroy
api_key = current_bearer.api_keys.find(params[:id])
render status: :unauthorized
end
api_key.destroy
end
end
def destroy
api_key = current_bearer.api_keys.find(params[:id])
api_key.destroy
end
end

View File

@ -9,7 +9,7 @@ class Api::V1::BaseController < ApplicationController
protect_from_forgery with: :null_session
def ping
render json: { message: "pong" }, status: :ok
render json: {message: "pong"}, status: :ok
end
private
@ -25,6 +25,6 @@ class Api::V1::BaseController < ApplicationController
end
def handle_bad_authentication
render json: { message: "Bad credentials" }, status: :unauthorized
render json: {message: "Bad credentials"}, status: :unauthorized
end
end
end

View File

@ -1,20 +1,18 @@
class Api::V1::CheckReportsController < Api::V1::BaseController
# POST /check-reports or /check-reports.json
def create
@check_report = CheckReport.new(check_report_params)
if @check_report.checks.empty?
render json: { message: "At least 1 check must be present" }, status: :unprocessable_entity
render json: {message: "At least 1 check must be present"}, status: :unprocessable_entity
else
checks_params = @check_report.checks.map { |check|
{
hostname: @check_report.hostname,
date: @check_report.date,
name: check.fetch("name", ""),
description: check.fetch("description", "")
}
{
hostname: @check_report.hostname,
date: @check_report.date,
name: check.fetch("name", ""),
description: check.fetch("description", "")
}
}
checks = Check.create(checks_params)
@ -22,9 +20,9 @@ class Api::V1::CheckReportsController < Api::V1::BaseController
invalid = checks.count(&:invalid?)
if checks.all?(&:persisted?)
render json: { message: "#{persisted} checks created" }, status: :created
render json: {message: "#{persisted} checks created"}, status: :created
else
render json: { message: "error while creating checks : #{persisted} persisted, #{invalid} invalid" }, status: :unprocessable_entity
render json: {message: "error while creating checks : #{persisted} persisted, #{invalid} invalid"}, status: :unprocessable_entity
end
end
end
@ -35,5 +33,4 @@ class Api::V1::CheckReportsController < Api::V1::BaseController
def check_report_params
params.require(:check_report).permit(:hostname, :date, {checks: [:name, :description]})
end
end
end

View File

@ -1,3 +1,3 @@
class AuthenticatedController < ApplicationController
before_action :authenticate_user!
end
before_action :authenticate_user!
end

View File

@ -1,5 +1,5 @@
class ChecksController < AuthenticatedController
before_action :set_check, only: %i[ show edit update destroy ]
before_action :set_check, only: %i[show edit update destroy]
# GET /checks or /checks.json
def index
@ -25,20 +25,20 @@ class ChecksController < AuthenticatedController
def create
@check = Check.new(check_params)
if @check.save
redirect_to check_url(@check), notice: "Check was successfully created."
else
render :new, status: :unprocessable_entity
end
if @check.save
redirect_to check_url(@check), notice: "Check was successfully created."
else
render :new, status: :unprocessable_entity
end
end
# PATCH/PUT /checks/1
def update
if @check.update(check_params)
redirect_to check_url(@check), notice: "Check was successfully updated."
else
render :edit, status: :unprocessable_entity
end
if @check.update(check_params)
redirect_to check_url(@check), notice: "Check was successfully updated."
else
render :edit, status: :unprocessable_entity
end
end
# DELETE /checks/1
@ -49,13 +49,14 @@ class ChecksController < AuthenticatedController
end
private
# Use callbacks to share common setup or constraints between actions.
def set_check
@check = Check.find(params[:id])
end
# Only allow a list of trusted parameters through.
def check_params
params.require(:check).permit(:name, :description, :hostname)
end
# Use callbacks to share common setup or constraints between actions.
def set_check
@check = Check.find(params[:id])
end
# Only allow a list of trusted parameters through.
def check_params
params.require(:check).permit(:name, :description, :hostname)
end
end

View File

@ -10,12 +10,12 @@ module ApiKeyAuthentication
# Use this to raise an error and automatically respond with a 401 HTTP status
# code when API key authentication fails
def authenticate_with_api_key!
@current_bearer = authenticate_or_request_with_http_token &method(:authenticator)
@current_bearer = authenticate_or_request_with_http_token(&method(:authenticator))
end
# Use this for optional API key authentication
def authenticate_with_api_key
@current_bearer = authenticate_with_http_token &method(:authenticator)
@current_bearer = authenticate_with_http_token(&method(:authenticator))
end
private
@ -28,4 +28,4 @@ module ApiKeyAuthentication
current_api_key&.bearer
end
end
end

View File

@ -55,4 +55,4 @@ module BasicAuthentication
def user_signed_in?
Current.user.present?
end
end
end

View File

@ -25,5 +25,4 @@ class ConfirmationsController < ApplicationController
def new
@user = User.new
end
end
end

View File

@ -29,4 +29,4 @@ class SessionsController < ApplicationController
def new
end
end
end

View File

@ -1,5 +1,5 @@
class UsersController < ApplicationController
before_action :set_user, only: %i[ show edit update destroy ]
before_action :set_user, only: %i[show edit update destroy]
# GET /users or /users.json
def index
@ -71,13 +71,14 @@ class UsersController < ApplicationController
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a list of trusted parameters through.
def user_params
params.require(:user).permit(:name, :email, :admin)
end
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a list of trusted parameters through.
def user_params
params.require(:user).permit(:name, :email, :admin)
end
end

View File

@ -1,28 +1,26 @@
module ApplicationHelper
def colored_pill_tag(content_or_options_with_block = nil, options = nil, &block)
if block_given?
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
end
color_classes = case options.fetch(:color)
when "red"
"bg-red-100 text-red-800"
when "green"
"bg-green-100 text-green-800"
when "orange"
"bg-orange-100 text-orange-800"
else
"bg-gray-100 text-gray-800"
end
classes = "px-2 inline-flex text-xs leading-5 font-semibold rounded-full #{color_classes}"
if block_given?
content_tag(:span, class: classes, &block)
else
content_tag(:span, content_or_options_with_block, class: classes)
end
def colored_pill_tag(content_or_options_with_block = nil, options = nil, &block)
if block
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
end
color_classes = case options.fetch(:color)
when "red"
"bg-red-100 text-red-800"
when "green"
"bg-green-100 text-green-800"
when "orange"
"bg-orange-100 text-orange-800"
else
"bg-gray-100 text-gray-800"
end
classes = "px-2 inline-flex text-xs leading-5 font-semibold rounded-full #{color_classes}"
if block
content_tag(:span, class: classes, &block)
else
content_tag(:span, content_or_options_with_block, class: classes)
end
end
end

View File

@ -2,4 +2,4 @@
module HeroiconHelper
include Heroicon::Engine.helpers
end
end

View File

@ -1,10 +1,10 @@
module UsersHelper
def user_gravatar(user, options = {})
options = {:alt => 'avatar', :class => 'avatar', :size => 80}.merge! options
id = Digest::MD5::hexdigest(user.email.strip.downcase)
url = 'http://www.gravatar.com/avatar/' + id + '.jpg?s=' + options[:size].to_s
options = {alt: "avatar", class: "avatar", size: 80}.merge! options
id = Digest::MD5.hexdigest(user.email.strip.downcase)
url = "http://www.gravatar.com/avatar/" + id + ".jpg?s=" + options[:size].to_s
options.delete :size
image_tag(url, options)
end
end
end

View File

@ -12,4 +12,4 @@ class ApiKey < ApplicationRecord
rescue ActiveRecord::RecordNotFound
nil
end
end
end

View File

@ -1,4 +1,4 @@
class Check < ApplicationRecord
validates_presence_of :name
validates_presence_of :hostname
validates_presence_of :name
validates_presence_of :hostname
end

View File

@ -1,8 +1,8 @@
class CheckReport
include ActiveModel::API
include ActiveModel::Attributes
include ActiveModel::API
include ActiveModel::Attributes
attribute :hostname, :string
attribute :date, :datetime, default: -> { Time.now }
attribute :checks, array: true
attribute :hostname, :string
attribute :date, :datetime, default: -> { Time.now }
attribute :checks, array: true
end

View File

@ -26,4 +26,4 @@ class CheckPolicy < ApplicationPolicy
def destroy?
user.admin?
end
end
end

View File

@ -36,4 +36,4 @@ class UserPolicy < ApplicationPolicy
def destroy?
user.admin?
end
end
end

View File

@ -26,8 +26,8 @@ set :repo_url, "git@gitea.evolix.org:evolix/evodata.git"
# Default value for linked_dirs is []
# append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system"
append :linked_dirs, 'log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', '.bundle', 'public/system', 'public/uploads'
append :linked_files, 'config/master.key'
append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "vendor/bundle", ".bundle", "public/system", "public/uploads"
append :linked_files, "config/master.key"
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
@ -42,4 +42,4 @@ append :linked_files, 'config/master.key'
# set :ssh_options, verify_host_key: :secure
Net::SSH::Transport::Algorithms::ALGORITHMS.values.each { |algs| algs.reject! { |a| a =~ /^ecd(sa|h)-sha2/ } }
Net::SSH::KnownHosts::SUPPORTED_TYPE.reject! { |t| t =~ /^ecd(sa|h)-sha2/ }
Net::SSH::KnownHosts::SUPPORTED_TYPE.reject! { |t| t =~ /^ecd(sa|h)-sha2/ }

View File

@ -1,4 +1,4 @@
config = YAML::load_file(File.join(__dir__, 'config.yml')).fetch("production")
config = YAML.load_file(File.join(__dir__, "config.yml")).fetch("production")
config.fetch("servers").each do |sc|
server sc.fetch("host"), user: sc.fetch("user"), roles: sc.fetch("roles")
@ -11,7 +11,6 @@ if config.has_key?(:keep_releases)
set :keep_releases, config.fetch("keep_releases").to_i
end
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
@ -21,8 +20,6 @@ end
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", roles: %w{db}
# role-based syntax
# ==================
@ -35,8 +32,6 @@ end
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
@ -45,8 +40,6 @@ end
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a

View File

@ -1,4 +1,4 @@
config = YAML::load_file(File.join(__dir__, 'config.yml')).fetch("staging")
config = YAML.load_file(File.join(__dir__, "config.yml")).fetch("staging")
config.fetch("servers").each do |sc|
server sc.fetch("host"), user: sc.fetch("user"), roles: sc.fetch("roles")
@ -11,12 +11,10 @@ if config.has_key?("keep_releases")
set :keep_releases, config.fetch("keep_releases").to_i
end
if config.has_key?("tmp_dir")
set :tmp_dir, config.fetch("tmp_dir")
end
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
@ -38,8 +36,6 @@ end
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
@ -48,8 +44,6 @@ end
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a

View File

@ -41,7 +41,7 @@ Rails.application.configure do
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.default_url_options = {host: "localhost", port: 3000}
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log

View File

@ -13,7 +13,7 @@ Rails.application.configure do
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
@ -53,7 +53,7 @@ Rails.application.configure do
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
@ -64,7 +64,7 @@ Rails.application.configure do
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { host: 'evocheck-web.evolix.org' }
config.action_mailer.default_url_options = {host: "evocheck-web.evolix.org"}
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
@ -85,9 +85,9 @@ Rails.application.configure do
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name")
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.

View File

@ -13,7 +13,7 @@ Rails.application.configure do
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
@ -53,7 +53,7 @@ Rails.application.configure do
config.log_level = :info
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
config.log_tags = [:request_id]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
@ -64,7 +64,7 @@ Rails.application.configure do
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { host: 'staging.evodata.evolix.eu' }
config.action_mailer.default_url_options = {host: "staging.evodata.evolix.eu"}
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
@ -85,9 +85,9 @@ Rails.application.configure do
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name")
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.

View File

@ -23,7 +23,7 @@ Rails.application.configure do
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.cache_store = :null_store

View File

@ -1,5 +1,5 @@
# frozen_string_literal: true
Heroicon.configure do |config|
config.variant = :solid # Options are :solid and :outline
end
config.variant = :solid # Options are :solid and :outline
end

View File

@ -4,7 +4,7 @@
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
max_threads_count = ENV.fetch("RAILS_MAX_THREADS", 5)
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
@ -15,7 +15,7 @@ worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development"
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
port ENV.fetch("PORT", 3000)
# Specifies the `environment` that Puma will run in.
#

View File

@ -1,9 +1,8 @@
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
defaults format: :json do
get '/ping', to: 'base#ping'
get "/ping", to: "base#ping"
resources :check_reports, path: "check-reports", only: [:create]
end
end

View File

@ -17,7 +17,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
test "should create user" do
assert_difference("User.count") do
post users_url, params: { user: { } }
post users_url, params: {user: {}}
end
assert_redirected_to user_url(User.last)
@ -34,7 +34,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
end
test "should update user" do
patch user_url(@user), params: { user: { } }
patch user_url(@user), params: {user: {}}
assert_redirected_to user_url(@user)
end

View File

@ -17,7 +17,7 @@ class ChecksControllerTest < ActionDispatch::IntegrationTest
test "should create check" do
assert_difference("Check.count") do
post checks_url, params: { check: { description: @check.description, hostname: @check.hostname, name: @check.name } }
post checks_url, params: {check: {description: @check.description, hostname: @check.hostname, name: @check.name}}
end
assert_redirected_to check_url(Check.last)
@ -34,7 +34,7 @@ class ChecksControllerTest < ActionDispatch::IntegrationTest
end
test "should update check" do
patch check_url(@check), params: { check: { description: @check.description, hostname: @check.hostname, name: @check.name } }
patch check_url(@check), params: {check: {description: @check.description, hostname: @check.hostname, name: @check.name}}
assert_redirected_to check_url(@check)
end

View File

@ -17,7 +17,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
test "should create user" do
assert_difference("User.count") do
post users_url, params: { user: { } }
post users_url, params: {user: {}}
end
assert_redirected_to user_url(User.last)
@ -34,7 +34,7 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
end
test "should update user" do
patch user_url(@user), params: { user: { } }
patch user_url(@user), params: {user: {}}
assert_redirected_to user_url(@user)
end

View File

@ -1,4 +1,3 @@
# Preview all emails at http://localhost:3000/rails/mailers/user_mailer
class UserMailerPreview < ActionMailer::Preview
end