プログラミングを完全に理解したエンジニアのメモ

チラ裏レベルのことしか書いてないインターネットの藻屑

All-in-One WP Migrationの"Maximum upload file size: 40 MB."の解決方法

問題

All-in-One WP Migrationでエクスポートしたデータが容量制限のせいでインポートできない f:id:fujitora:20181128150458p:plain

"Maximum upload file size: 40 MB."

Bitnamiで構築したサーバーなので

$ vi /opt/bitnami/php/etc/php.ini 

post_max_sizeupload_max_filesize の16を512にして

$ sudo /opt/bitnami/ctlscript.sh restart

Docs

Modify the PHP file upload limit

AdminLTEのサイドバーを固定した時にスクロールすると背景色がかからない

問題

f:id:fujitora:20181109135253p:plain

AdminLTEでヘッダ固定、サイドバー固定をして、スクロールすると画像の赤枠以降に背景色が適用されない。 bodyについてるクラスはこれ

body class="skin-blue fixed sidebar-mini sidebar-mini-expand-feature"

解決方法

cssを書く

.content-wrapper {
  overflow-y: auto;
}

RailsでFUJISSLのファイル認証をする

NginxでなくRails側でファイル認証をする

routes.rb

get "/.well-known/pki-validation/fileauth.txt" => "top#ssl"

top_controller.rb

class TopController < ApplicationController
  def index
    hogehoge
  end

  def ssl
    render plain: "(ファイル認証の文字列)"
  end
end

スクロールしたときに要素が画面上部からどの位置にいるか取得する

coffeescript

$ ->
  $(window).scroll ->
    console.log $('.target-element').offset().top - $(window).scrollTop();

スクロールするたびにコンソールに画面上部からの位置が表示される

f:id:fujitora:20180905154144p:plain

bitnamiをssl化する

csrの作成

秘密鍵を作成

$ sudo openssl genrsa -out /opt/bitnami/apache2/conf/server.key 2048

秘密鍵からCSRを作成

$ sudo openssl req -new -key /opt/bitnami/apache2/conf/server.key -out /opt/bitnami/apache2/conf/cert.csr

作成のための質問項目に回答する

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:JP
State or Province Name (full name) [Some-State]:Tokyo
Locality Name (eg, city) []:Minato-ku
Organization Name (eg, company) [Internet Widgits Pty Ltd]:hogehoge, inc.
Organizational Unit Name (eg, section) []:development
Common Name (e.g. server FQDN or YOUR name) []:hogehoge.com
Email Address []:info@hogehoge.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
$ mv cert.csr server.csr

ファイル認証

$ sudo vi /opt/bitnami/apache2/conf/bitnami/bitnami.conf
<VirtualHost _default_:80>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  RewriteEngine on←追加
  RewriteCond %{REQUEST_URI} !=/.well-known/pki-validation/fileauth.txt←追加

/home/bitnami/apps/wordpress/htdocs/.well-known/pki-validation にfileauth.txtを作成

各種ファイル作成

crtとcaを作成する。

$ sudo vi /opt/bitnami/apache2/conf/server.crt
$ sudo vi /opt/bitnami/apache2/conf/server-ca.crt

権限変更

$ sudo chown root:root /opt/bitnami/apache2/conf/server*
$ sudo chmod 600 /opt/bitnami/apache2/conf/server*

conf file編集

$ sudo vi /opt/bitnami/apache2/conf/bitnami/bitnami.conf
<VirtualHost _default_:80>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  RewriteEngine On←追加
  RewriteCond %{HTTPS} !=on←追加
  RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]←追加
<VirtualHost _default_:443>
  DocumentRoot "/opt/bitnami/apache2/htdocs"
  SSLEngine on
  SSLCertificateFile "/opt/bitnami/apache2/conf/server.crt"
  SSLCertificateKeyFile "/opt/bitnami/apache2/conf/server.key"
  SSLCertificateChainFile "/opt/bitnami/apache2/conf/server-ca.crt" ←追加
$ sudo /opt/bitnami/ctlscript.sh restart apache

(注)

SSLCertificateChainFile "/opt/bitnami/apache2/conf/server-ca.crt"

ApacheのバージョンでSSLCACertificateFileかSSLCertificateChainFile変わる

Doc

Bitnami Application Stacks

Bitnami Application Stacks

AWS EC2のbitnamiにbasic認証をかける

環境

実装

$ cd /opt/bitnami
$ sudo apache2/bin/htpasswd -cb apache2/wordpress_users USERNAME PASSWORD
$ sudo vi /opt/bitnami/apps/wordpress/conf/httpd-app.conf

以下に書き換える。

4行追加 & Require all grantedコメントアウト

<Directory "/opt/bitnami/apps/wordpress/htdocs">
    ...
      AuthType Basic
      AuthName MyAuthName
      AuthUserFile "/opt/bitnami/apache2/wordpress_users"
      Require valid-user
    ...  

    <IfVersion >= 2.3>
    # Require all granted
    </IfVersion>
    ...
  </Directory>
$ sudo /opt/bitnami/ctlscript.sh restart apache

ドキュメント

docs.bitnami.com

docs.bitnami.com

EC2とRailsとnginxのサイトをLet’s EncryptでSSL化

httpで動いてるとこからhttpsに変更する手順

準備

$ git clone https://github.com/letsencrypt/letsencrypt
$ cd ./letsencrypt
$ ./letsencrypt-auto --help --debug

最後に以下のようにでればOK

Complete!
Creating virtual environment...
Installing Python packages...
Installation succeeded.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  letsencrypt-auto [SUBCOMMAND] [options] [-d DOMAIN] [-d DOMAIN] ...

Certbot can obtain and install HTTPS/TLS/SSL certificates.  By default,
it will attempt to use a webserver both for obtaining and installing the
certificate. The most common SUBCOMMANDS and flags are:

obtain, install, and renew certificates:
    (default) run   Obtain & install a certificate in your current webserver
    certonly        Obtain or renew a certificate, but do not install it
    renew           Renew all previously obtained certificates that are near
expiry
    enhance         Add security enhancements to your existing configuration
   -d DOMAINS       Comma-separated list of domains to obtain a certificate for

  --apache          Use the Apache plugin for authentication & installation
  --standalone      Run a standalone webserver for authentication
  --nginx           Use the Nginx plugin for authentication & installation
  --webroot         Place files in a server's webroot folder for authentication
  --manual          Obtain certificates interactively, or using shell script
hooks

   -n               Run non-interactively
  --test-cert       Obtain a test certificate from a staging server
  --dry-run         Test "renew" or "certonly" without saving any certificates
to disk

manage certificates:
    certificates    Display information about certificates you have from Certbot
    revoke          Revoke a certificate (supply --cert-path)
    delete          Delete a certificate

manage your account with Let's Encrypt:
    register        Create a Let's Encrypt ACME account
  --agree-tos       Agree to the ACME server's Subscriber Agreement
   -m EMAIL         Email address for important account notifications

More detailed help:

  -h, --help [TOPIC]    print this message, or detailed help on a topic;
                        the available TOPICS are:

   all, automation, commands, paths, security, testing, or any of the
   subcommands or plugins (certonly, renew, install, register, nginx,
   apache, standalone, webroot, etc.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

nginxのconfigファイルを編集

server {
  listen 80 default;
  (省略)
  location /.well-known/ {
    root /home/user_name/app_name;
  }
}

読み込み&再起動

$ sudo service nginx reload
$ sudo service nginx restart

証明書作成

$ sudo ./letsencrypt-auto certonly --webroot -w ドキュメントルート -d ドメイン
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel):

でメアド入力

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N
$ cd /etc/letsencrypt/

配下にドメインの名前のフォルダで作成される

Nginx

nginxに証明書の場所を設定

server {
  listen 443 ssl;
  server_name hogeohoge.com;

  ssl on;
  ssl_certificate      /etc/letsencrypt/live/hogehoge.com/fullchain.pem;
  ssl_certificate_key  /etc/letsencrypt/live/hogehoge.com/privkey.pem;
  (略)
}

reload & restartして完了

参考サイト

qiita.com

knowledge.sakura.ad.jp

bitnamiでLet's EncryptでSSL化するときに読むメモ

Doc

Generate And Install A Let's Encrypt SSL Certificate For A Bitnami Application

Generate and Install a Let's Encrypt SSL Certificate for a Bitnami Application

How To Force HTTPS Redirection With Apache?

Bitnami Stacks for AWS Cloud

Force HTTPS Redirection With Apache

https://docs.bitnami.com/aws/infrastructure/lamp/administration/force-https-apache/

bitnamiのメモ

httpd.confの場所

/opt/bitnami/apache2/conf/httpd.conf

welcartのSSL設定

www.welcart.com

Railsで多言語対応する

トップページを多言語化するサンプルコードのメモ

Gemfile

gem 'rails-i18n'
gem 'http_accept_language'

config/routes.rb

Rails.application.routes.draw do
  scope '(:locale)', locale: /#{I18n.available_locales.join('|')}/ do
    root 'top#index'
  end
end

config/application.rb

require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module CwSystem
  class Application < Rails::Application
    config.load_defaults 5.1
    config.i18n.available_locales = %i(ja en fr es pt)
    config.i18n.enforce_available_locales = true
    config.i18n.default_locale = :ja
  end
end

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_locale

  def set_locale
    I18n.locale = locale
  end

  def locale
    @locale ||= params[:locale] || I18n.default_locale || http_accept_language.compatible_language_from(I18n.available_locales || I18n.default_locale)
  end

  def default_url_options
    return {} if params[:local].blank?
    {locale: locale}
  end
end

app/helpers/application_helper.rb

module ApplicationHelper
  def i18n_url_for(options)
    if options[:locale] == I18n.default_locale
      options[:locale] = nil
    end
    url_for(options)
  end
end

config/locales/

それぞれの言語のymlを作成

carrierwaveで画像名をユニークにした時にS3とDBでファイル名が異なる

問題

ファイル名をユニークにするために以下の処理をしていた

def filename
  p "#{SecureRandom.uuid}.#{file.extension}" if original_filename.present?
end

がs3にcarrierwaveで画像アップ&DBに保存すると、s3とDBのファイル名が違っていた。

この人たちと同じ現象

stackoverflow.com

teratail.com

原因

filenameメソッドが複数回呼ばれているため。 save前に2回、saveの後に1回の計3回呼ばれている。

解決方法

github.com

def filename
  "#{secure_token}.png" if original_filename.present?
end

protected
def secure_token
  var = :"@#{mounted_as}_secure_token"
  model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end

Rspec導入

gem導入

group :development, :test do
  (略)
  gem 'rspec-rails'
end
$ bundle install --path vendor/bundle

configファイル生成

$ rails generate rspec:install
.rspec
spec/spec_helper.rb
spec/rails_helper.rb

が生成される

.rspec編集

--warnings
--color
--format documentation
--require spec_helper

application.rb

config/application.rb

config.generators do |g|
  g.test_framework :rspec,
  view_specs: false,
  helper_specs: false,
  routing_specs: false
end