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

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

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

CKEditorのフォームにhtmlタグを貼ると記号がエスケープされる

問題

フォームに

<h3>hogehoge</h3>

と入れて保存して

css

h3 {
  font-size: 24px;
}

みたいにやってもCSSは当たらない。

解決策

エスケープされて

&lt;h3&gt;hogehoge&lt;/h3&gt;

の形で保存される。

app/assets/javascripts/ckeditor/config.js

if (typeof(CKEDITOR) != 'undefined') {
  CKEDITOR.editorConfig = function (config) {
    config.basicEntities = false;
    config.entities = false;
  }
}

とすればOK

ちなみに

if (typeof(CKEDITOR) != 'undefined') {
}

がないと、ckeditorのフォームが無いページで

uncaught ReferenceError: CKEDITOR is not defined

のエラーが出る

仮想通貨bot開発でよく見るやつメモ(随時更新)

全共通

github.com

これの中身みればだいたい分かる

bitflyer

ドキュメント lightning.bitflyer.com

サンプル lightning.bitflyer.com

bitmex

ドキュメント

www.bitmex.com

ruby用ライブラリ github.com

github.com

binance

ドキュメント

github.com

deviseで招待用リンクを生成する(メールを使わずに招待機能を実装)

したいこと

  • 招待用URLを発行できる
  • メールを使わずにユーザーを招待できる

端折ること

  • URLと発行したユーザーのリレーション
  • 招待されたユーザーがどのURLから登録されたか
  • URLの期限
  • クリック数

実装

model

$ rails g model initation

migrationファイルは

class CreateInvitations < ActiveRecord::Migration[5.1]
  def change
    create_table :invitations do |t|
      t.string :token
      t.timestamps
    end
  end
end

端折った機能作りたいならここでclick_countなりlimited_atなりを足す

controller

$ rails g controller users::invitations

routes.rb

namespace :users do
    resource :invitations, only: [:show, :update]
  end

を追加

invitations_controller.rb

class Users::InvitationsController < ApplicationController
  before_action :authenticate_user!

  def show
    if Invitation.count == 0
      Invitation.create!(token: SecureRandom.uuid.gsub!(/-/,''))
      @invitation_token_url =  "http://localhost:3000/users/sign_up?tk=" + Invitation.all.last.token.to_s
    else
      @invitation_token_url =  "http://localhost:3000/users/sign_up?tk=" + Invitation.all.last.token.to_s
    end
  end

  def update
    Invitation.create!(token: SecureRandom.uuid.gsub!(/-/,''))
    @invitation_token_url =  "http://localhost:3000/users/sign_up?tk=" + Invitation.all.last.token.to_s
    redirect_to users_invitations_path, notice: "URLを作成しました"
  end
end

(注意)

  • ここらへんheplerにまとめる。
  • URLはgem 'config'でベタ打ちにしない

views/invitations/show.html.slim

.container-fluid
  .container
    .row
      .col-sm-12
        h4 招待用URL作成
        = text_field_tag '#', @invitation_token_url, class: 'form-control'

        .margin-top-30
          = link_to 'URLを再作成する', users_invitations_path, { method: 'put', class: 'btn btn-primary' }

clipboardjs.com

これとか入れる

registrations_controller.rb

ここで一番はじめのユーザー以外の直リンクと不正なtoken or token無しをはじく

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :check_sign_up_token, only: [:new]

  (略)

  protected

  # 新規登録にtoken無しでアクセスさせない
  def check_sign_up_token
    return redirect_to root_path if params[:tk].nil? || User.count == 0 || !Invitation.exists?(token: params[:tk])
  end
end

アクセスした時にtokenをcookieに保存して、createの時にチェックするようにした方がよい(?)

deviseでユーザー招待機能の追加

したいこと

  • 登録されているユーザーがメアドを入力して送信すると招待用URLが記載されているメールを送信できる
  • 招待用URLを踏むとパスワード設定画面に遷移できる
  • パスワードが完了すると登録が完了する

=>slackに招待用URLで人追加する時と同じ

businesschatmaster.com

前提

  • deviseは導入済み
  • deviseを適用しているモデルはuser
  • viewとcontrollerもdeviseディレクトリでなくusersディレクトリ配下にある
  • devise.rbはconfig.scoped_views = trueになっている
  • 開発環境でのメール確認はletter_openerletter_opener_webを導入済み

実装方法

github.com

Gemfile

追加してbundle install

gem 'devise_invite'

rails command

$ rails generate devise_invitable:install
$ rails generate devise_invitable user
$ bundle exec rake db:migrate

models/user.rbの変更、migrationファイル、viewファイルができる

models/user.rb

これが既存

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

修正後

class User < ApplicationRecord
  devise :invitable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         invite_for: 2.weeks
end

routes.rb

devise_for :users, controllers: {
    sessions:      'users/sessions',
    passwords:     'users/passwords',
    registrations: 'users/registrations',
    invitations: 'users/invitations' # 追加
}

確認

  • http://localhost:3000/users/invitation/newにアクセスして、メールフォームにメアドを入れて送信すると、root_pathにリダイレクトする。
  • シークレットブラウザでhttp://localhost:3000/letter_openerにアクセスすると招待メールがきていて、"Accept invitation"を押すと、http://localhost:3000/users/invitation/accept?invitation_token=XXXXXXXXXXXXXXに飛んで、パスワード設定画面が表示される。
  • パスワードを設定するとログインできる

参考URL

github.com

railsの開発でメール送信テスト

gemfile

developmentのグループに以下を追加

gem 'letter_opener'
gem 'letter_opener_web'

routes.rb

以下を追加

mount LetterOpenerWeb::Engine, at: '/letter_opener' if Rails.env.development?

development.rb

config/environments/development.rb

以下を追加

config.action_mailer.delivery_method = :letter_opener_web
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

動作確認

http://localhost:3000/users/password/new

にアクセスしてパスワードリセットのメールを送信してみる。

http://localhost:3000/letter_opener

にアクセスすると送信されたメールの一覧が見れる

enumを日本語化するenum_help

topic.rb

class Topic < ApplicationRecord
  enum status: {
    draft: 0,
    published: 1,
    privated: 2
  }
end

gem

gem 'enum_help'

ja.yml

config/locales/ja.yml

ja:
  enums:
    topic:
      status:
        draft: 下書き
        published: 公開
        privated: 非公開

application.rb

config/application.rb

config.i18n.default_locale = :ja

を追加