カテゴリー: tech

  • 手動で作った lambda を code として管理する

    手動で作った lambda を code として管理する

    tl;dr;

    既存の lambda をダウンロードし、コンソールを使わず sam を用いて管理する方法をまとめた。deploy 方法から注意事項までを記載。

    既存 lambda をダウンロード

     lambda をダウンロードすると大きく2つに分けてダウンロードすることができる。

    sam のドキュメントについてはこちら

    関数のエクスポートを押下すると、

     

    • AWS SAM ファイルのダウンロード
    • デプロイパッケージのダウンロード

    が選択できる。

    端的に言うと

    • lambda の設定ファイル
    • プログラムのコード

    だ。両方ダウンロードする。

    sam のセットアップ

    公式ドキュメントの手順を準拠すると、 sam のインストールは以下の通りとなる。

    brew tap aws/tap
    brew install aws-sam-cli

    deploy ディレクトリの初期化

    今回は python3.8 を利用するので以下のように設定した。
    ダウンロードした zipファイル は unzipコマンドなどで解凍しておく。

    sam init
    
    
    	SAM CLI now collects telemetry to better understand customer needs.
    
    	You can OPT OUT and disable telemetry collection by setting the
    	environment variable SAM_CLI_TELEMETRY=0 in your shell.
    	Thanks for your help!
    
    	Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html
    
    Which template source would you like to use?
    	1 - AWS Quick Start Templates
    	2 - Custom Template Location
    Choice: 1
    
    Which runtime would you like to use?
    	1 - nodejs12.x
    	2 - python3.8
    	3 - ruby2.5
    	4 - go1.x
    	5 - java11
    	6 - dotnetcore2.1
    	7 - nodejs10.x
    	8 - nodejs8.10
    	9 - python3.7
    	10 - python3.6
    	11 - python2.7
    	12 - java8
    	13 - dotnetcore2.0
    	14 - dotnetcore1.0
    Runtime: 2
    
    Project name [sam-app]: 
    
    Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git
    
    AWS quick start application templates:
    	1 - Hello World Example
    	2 - EventBridge Hello World
    	3 - EventBridge App from scratch (100+ Event Schemas)
    Template selection: 1
    
    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Runtime: python3.8
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    
    Next steps can be found in the README file at ./sam-app/README.md
        
    coco@darkenagy sam % 

    ダウンロードした yamlファイル を、 template.yml と言うファイル名に変更する。

    mv test-imagemagick.yaml template.yml 

    requirements.txt も必要になるので、作成する。使わない場合でも空のファイルを用意する必要があるので、 touch するなり作成する。

    touch requirements.txt

    以下のように表示されれば成功。

    sam build
    Building resource 'testimagemagick'
    Running PythonPipBuilder:ResolveDependencies
    Running PythonPipBuilder:CopySource
    
    Build Succeeded
    
    Built Artifacts  : .aws-sam/build
    Built Template   : .aws-sam/build/template.yaml
    
    Commands you can use next
    =========================
    [*] Invoke Function: sam local invoke
    [*] Deploy: sam deploy --guided
        

    ちなみに、sam コマンドでも、.aws 配下の profile を読み込むことも可能。

    `sam build –profile cloudformation` 

    エラーが発生した場合は debugモード で確認することができる。

    sam build --debug

    あとは invoke するなり、deploy するなりすればよい。

    deploy

    `sam deploy –guided`コマンドを利用することで deploy が可能。

    % sam deploy --guided
    
    Configuring SAM deploy
    ======================
    
    	Looking for samconfig.toml :  Not found
    
    	Setting default arguments for 'sam deploy'
    	=========================================
    	Stack Name [sam-app]: 
    	AWS Region [us-east-1]: ap-northeast-1
    	#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
    	Confirm changes before deploy [y/N]: y
    	#SAM needs permission to be able to create roles to connect to the resources in your template
    	Allow SAM CLI IAM role creation [Y/n]: y
    	Save arguments to samconfig.toml [Y/n]: y
    
    	Looking for resources needed for deployment: Found!
    
    		Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1dc492sz2bqu7
    		A different default S3 bucket can be set in samconfig.toml
    
    	Saved arguments to config file
    	Running 'sam deploy' for future deployments will use the parameters saved above.
    	The above parameters can be changed by modifying samconfig.toml
    	Learn more about samconfig.toml syntax at 
    	https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
    
    	Deploying with following values
    	===============================
    	Stack name                 : sam-app
    	Region                     : ap-northeast-1
    	Confirm changeset          : True
    	Deployment s3 bucket       : aws-sam-cli-managed-default-samclisourcebucket-1dc492sz2bqu7
    	Capabilities               : ["CAPABILITY_IAM"]
    	Parameter overrides        : {}
    
    Initiating deployment
    =====================
    Uploading to sam-app/9a97ece5eb5fac3dd9dff84a97110722  9611 / 9611.0  (100.00%)
    Uploading to sam-app/cac8e2252620a466ff8e4becb2d4a8ed.template  638 / 638.0  (100.00%)
    
    Waiting for changeset to be created..
    
    CloudFormation stack changeset
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Operation                                                           LogicalResourceId                                                   ResourceType                                                      
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    + Add                                                               testimagemagick                                                     AWS::Lambda::Function                                             
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    Changeset created successfully. arn:aws:cloudformation:ap-northeast-1:821594579130:changeSet/samcli-deploy1578156109/01d374f5-800c-438e-b4cb-4f25d8d0bc4d
    
    
    Previewing CloudFormation changeset before deployment
    ======================================================
    Deploy this changeset? [y/N]:

    問題なければyを押す。

    2020-01-05 01:42:01 - Waiting for stack create/update to complete
    
    CloudFormation events from changeset
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    ResourceStatus                                     ResourceType                                       LogicalResourceId                                  ResourceStatusReason                             
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              testimagemagick                                    -                                                
    CREATE_IN_PROGRESS                                 AWS::Lambda::Function                              testimagemagick                                    Resource creation Initiated                      
    CREATE_COMPLETE                                    AWS::Lambda::Function                              testimagemagick                                    -                                                
    CREATE_COMPLETE                                    AWS::CloudFormation::Stack                         sam-app                                            -                                                
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    
    Successfully created/updated stack - sam-app in ap-northeast-1
    

    確認

    成功すれば以下の通り作成される。

    function name が、意図した名前と違う場合、明示的に指定することができる。

    AWSTemplateFormatVersion: '2010-09-09'
    Transform: 'AWS::Serverless-2016-10-31'
    Description: An AWS Serverless Specification template describing your function.
    Resources:
      testimagemagick:
        Type: 'AWS::Serverless::Function'
        Properties:
          FunctionName: test-imagemagick-123
          Handler: lambda_function.lambda_handler
          Runtime: python3.8
          CodeUri: .
          Description: ''
          MemorySize: 128
          Timeout: 3
          Role: 'arn:aws:iam::123:role/lambdaExecution'
          Layers:
            - 'arn:aws:lambda:ap-northeast-1:123:layer:image-magick:2'

    template.yml で`FunctionName`を指定する。

    再度`sam build`、 `sam deploy` を行うと、新しい lambda function に置き換わる。

    注意点

    手動で作り上げた lambda を sam を用いて上書いて管理することはできないのか。
    結論、そのままはできない。

    現在自分が動かしているものについては、手動で作った lambda は削除し、その後 sam を用いたdepoloy に切替えるなどして対応している。

     

    https://dev.classmethod.jp/cloud/aws/cloudformation-import-existing-resources/

     

    しかし、CloudForomation で手動で作成したリソースをインポートできるようになったので、これを使えばできるかも。(未確認)

    試したことある人いたら twitter でもご一報ください。

     

  • AWS lambda(Python 3.8)でimagemagickを使う

    AWS lambda(Python 3.8)でimagemagickを使う

    tl;dr;

    AWS lambda(Python 3.8)で画像処理ツールのimagemagickを動かした。

    install方法からlambda内でimagemagickの動かす際のコードまでを紹介。

    imagemagickとは

    imagemagick は動的に画像を編集する古典的なツール。こちらの記事によると、なんと1987年から開発されている。wikipediaを確認する限り、Photoshopのリリースが1990年だから、その古さに驚かされる。

    しかしこのツール、度重なる脆弱性は報告されているものの、画像編集の機能としてまだまだ現役として使っているプロジェクトも存在する。

    今回はそのimagemagickをlambdaで。Python 3.8のランタイムから使う方法を紹介する。

    Serverless.Pub

    ありがたい事にServerlessを支援し積極的に情報発信をしてくれている団体がいる。

    彼らが作ったlambdaの`binally layer`をCloudFormationでdeployする機能も提供してくれている。

    https://serverless.pub/lambda-utility-layers/

    GitHubはこちら

    https://github.com/serverlesspub/imagemagick-aws-lambda-2

    こちらを`git clone`して、`make all` すればimagemagickのlambdaの`binally layer`ができる。

    その方法を使ってもよいのだが、
    実は以下のページからDeployボタンを押せば、それだけで自動でCloudFormationが自分のAWSで動き、lambdaの中に`binally layer`が作成されることもできる。

    https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:145266761615:applications~image-magick-lambda-layer

    しかし、注意すべきはここの部分。

    要約すると、nodejs10.xランタイムのようなAmazon Linux 2で使えるよ。とのこと。PythonのPの字も見当たらない。
    対象外かと思い当初諦めていた。

    そんな中、最近、`Python 3.8`ランタイムがlambdaで使えるようになった事を知り、公式ドキュメントを読んでみると、今までのPythonで使っていたOSとは異なり、`Amazon linux2`がベースとなっていることがわかった。

    node.jsに絞っているのはAmazonLinux2がベースのように見受けられたため、これはlambdaの中でPythonでもimagemagickを動かせるかもと思い今回試す事にした。

    やってみた

    https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:145266761615:applications~image-magick-lambda-layer

    を開きDeployボタンを押す。
    しかし、この時点でいきなりDeployされるわけではない。

    DeployはCloudFormationによって行われる。CloudFormationのスタック名確定させたら(デフォルトでもよい)デプロイを押下。

    しばらくすると、AWS LambdaのLayersに新たに`image-magick`が登録される。

    Lambda関数から、Layersを選択する

    レイヤーの追加ボタンを押し、imagemagickを選択する。

    レイヤーに表示されない場合は、以下のようにARNを直接入力する。

    これで下準備は完了

    AWS lambda(Python 3.8)でimagemagickを使う

     ここからがPythonからimagemagickを使えるかの確認。

    今回はシンプルにversionを表示させることで使える事にしたい。

    コードはこちら。

    import json
    import subprocess
    
    def lambda_handler(event, context):
        subprocess.check_call(['convert', '-version'])
      
        return {
            'body': json.dumps('Hello from Lambda!')
        }
    

    subprocessを使って、Pythonから、lambdaが動いているOS側のコマンドを実行する。

    imagemagickをinstallすると使えるようになる`convert`コマンドを叩く。

     

    結果は以下の通り

    無事imagemagickのversionを確認できた。

    最後に

    私が実施した際はレイヤーの追加ボタンを押しても選択肢としてimagemagickが表示されなかった。

    これは、CloudFormationによって作られるimagemagickのレイヤーがnode.jsに限定しているため。不便なのでpull reqを出してmergeしてもらった。

    https://github.com/serverlesspub/imagemagick-aws-lambda-2/pull/18/files

    今はレイヤー選択画面から互換性のあるレイヤーとして選択できるはずだ。

     

  • Cloud functionsを使ってCloud Storageに画像がuploadされるとサムネイルを作成する

    Cloud functionsを使ってCloud Storageに画像がuploadされるとサムネイルを作成する

    tl;dr;

    Cloud Storageにuploadされると、イベントフックでCloud functionsが実行されサムネイル作成処理が走る処理を作った。

    事前準備

    gcloudコマンドのインストール。既に設定済ならスキップを。

    https://cloud.google.com/storage/docs/gsutil_install?hl=ja

    バケットの作成。今回は変換対象、変換後の格納先を作成。

    export YOUR_INPUT_BUCKET_NAME=tsukada-input
    gsutil mb gs://$YOUR_INPUT_BUCKET_NAME
    
    export YOUR_OUTPUT_BUCKET_NAME=tsukada-output
    gsutil mb gs://$YOUR_OUTPUT_BUCKET_NAME

    deploy

    sample productをダウンロード。deploy。

    mkdir project
    cd project
    git clone https://github.com/GitSumito/cloudfunctions-imagemagick-on-gcp
    cd cloudfunctions-imagemagick-on-gcp
    
    # deploy
    gcloud functions deploy ImageConvert --runtime go111 --trigger-bucket $YOUR_INPUT_BUCKET_NAME --set-env-vars THUMBNAILED=$YOUR_OUTPUT_BUCKET_NAME

    `gcloud functions deploy`の後ろは、実行する関数名を入力する。

    また、引数として `(ctx context.Context, e GCSEvent)` を受け付ける必要があるので注意。

    Cloud Functionsのコマンドでは予め`–trigger-bucket`というオプションが用意されていて、任意のバケットを指定すれば簡単にイベント処理を紐付けることができる。便利。

    deployコマンドを実行すると

    ` Deploying function (may take a while – up to 2 minutes)…⠼     `

     と表示され、しばらく待つ。

    result

    左がアップロードしたオリジナルの画像。

    右側がEventを検知して、Cloud Functionsが実行され、サムネイル作成された画像。

    使ってみると非常に簡単にイベント駆動処理を作ることができた。使い方次第では活躍しそう。

     

  • Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

    Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

    概要

    useradd コマンドで作成したユーザでログインできない。

    Permission denied (publickey,gssapi-keyex,gssapi-with-mic).  というエラーが出た際の対処。

    はじめに

    以下の手順でアカウントを作成した。

    useradd sumito.tsukada

    鍵の作成

    ssh-keygen -t rsa

    作成された秘密鍵を、接続元サーバにコピー

    ~/.ssh/id_rsa

    接続元で権限は 400 とした。

    いざsshしてみようとしたら

    Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

    が発生。

    原因

    接続先のサーバに `.ssh/authorized_keys` が存在していない。

    対処

    接続先のサーバで公開鍵をコピーし、権限を644に設定する。

    cp .ssh/id_rsa.pub .ssh/authorized_keys
    chmod 644 .ssh/authorized_keys

    参考情報

    http://dqn.sakusakutto.jp/2012/01/sshpermission_denied_publickey.html

  • Macで録ったmovファイルをgifに変換する

    Macで録ったmovファイルをgifに変換する

    tl;dr

    Macで撮ったmovファイルをgifに変換する方法を紹介。

    手軽に動画のスクリーンショットを撮れるようになっていた

    気がついたらショートカット1発で動画が録れるようになっていた。Mojave から `command + shift + 5 ` で動画のスクリーンショットを録ることができる。

    しかし、デフォルトではmovファイルとして出力される。mov画像は容量も大きくなるし、軽くて使い勝手の良いgitにしたいことがある。 

    `ffmpeg`を使う。

    まだインストールしていなければインストールする。brewコマンドで一発。

    brew install ffmpeg

     

    変換コマンド

    ffmpeg -i [変換元movファイル] -r 24 [変換後gifファイル]

    例)

    ffmpeg -i ~/Desktop/画面収録\ 2019-12-22\ 23.47.33.mov -r 24 chrome.gif

    アウトプット(gifファイル)

    以下の通り。非常に軽量なのでサイトに載せることも容易になった。

     今日からgif多めのブログになりそうだ。

  • MacのターミナルからChromeを開いてサイトにアクセスする

    MacのターミナルからChromeを開いてサイトにアクセスする

    tl;dr;

    ターミナルからGoogle chromeを起動する方法を紹介。起動シェルに登録すれば1行で任意のページを開くことができる。

    起動方法

    実は、macのopenコマンドの後ろに` -a` オプションを付ければ任意のアプリケーションで起動することができる。

    もっと使いやすくする

    起動シェルにaliasを登録する事で、もっと短くすることができる。

    `vi ~/.zshrc`

    以下の行を追加

    alias chrome="open -a 'Google Chrome'"

    その後、sourceコマンドで`~/.zshrc`を再読み込みさせる。

    source ~/.zshrc

    これで、`chrome https://tsukada.sumito.jp` と入力すると、上記と同じ結果になる。

    他によく使うツールを登録する。

    例えばmacに標準搭載のPreviewなど登録すると便利。

    alias preview="open -a 'Preview'"

    `source` コマンドで読み込ませればよい。

  • ERROR: boto3 1.9.226 has requirement botocore=1.12.226, but you’ll have botocore 1.13.37 which is incompatible.

    ERROR: boto3 1.9.226 has requirement botocore<1.13.0,>=1.12.226, but you’ll have botocore 1.13.37 which is incompatible.

    TL;DR

    awsコマンドを実施中に遭遇。versionが求められているものと違うようだ。

    Encountered while executing aws command. The version seems different from what is required.

    ERROR: boto3 1.9.226 has requirement botocore<1.13.0,>=1.12.226, but you'll have botocore 1.13.37 which is incompatible.
    

    対処 deal

    awscliを最新にする

    Update awscli

    pip3 install awscli --upgrade --user

     

    その後、botocore、boto3をuninstall

    Then uninstall botocore, boto3

    pip3 uninstall botocore
    
    pip3 uninstall boto3

     

    再度botocore、boto3をinstall

    Install botocore and boto3 again

    pip3 install botocore
    
    pip3 install boto3

     

    以上。

    That’s it.

    参考情報 FYI

    https://stackoverflow.com/questions/51911075/how-to-check-awscli-and-compatible-botocore-package-is-installed

     

     

  • firebase deploy時のeslintを無効にする

    firebase deploy時のeslintを無効にする

    はじめに

    firebase functionを使えるようにした際、知らず知らずにESLintを有効にしてしまっていた。今回は対処した際の方法を紹介。

    問題

    firebase deploy
    
    === Deploying to 'auth-xxx'...
    
    i  deploying database, functions, hosting
    Running command: npm --prefix "$RESOURCE_DIR" run lint
    
    > functions@ lint /Users/coco/Documents/firebase-auth/functions
    > eslint .
    
    
    /Users/coco/Documents/firebase-auth/functions/index.js
      31:7   error    Expected return with your callback function                     callback-return
      38:24  warning  Use path.join() or path.resolve() instead of + to create paths  no-path-concat
    
    ✖ 2 problems (1 error, 1 warning)
    
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! functions@ lint: `eslint .`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the functions@ lint script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/coco/.npm/_logs/2019-12-10T15_36_22_429Z-debug.log
    
    Error: functions predeploy error: Command terminated with non-zero exit code1
    darkenagy:firebase-auth coco$ cat /Users/coco/.npm/_logs/2019-12-10T15_36_22_429Z-de

    ESLintで引っかかっているようだ。

    ふりかえり

    そもそも、本当にESLintを有効にしたんだっけ。。
    どのようにfirebase functionを有効にしたか振り返る。

    firebase init functions
    
         ######## #### ########  ######## ########     ###     ######  ########
         ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
         ######    ##  ########  ######   ########  #########  ######  ######
         ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
         ##       #### ##     ## ######## ########  ##     ##  ######  ########
    
    You're about to initialize a Firebase project in this directory:
    
      /Users/coco/Documents/firebase-auth
    
    Before we get started, keep in mind:
    
      * You are initializing in an existing Firebase project directory
    
    
    === Project Setup
    
    First, let's associate this project directory with a Firebase project.
    You can create multiple project aliases by running firebase use --add, 
    but for now we'll just set up a default project.
    
    i  .firebaserc already has a default project, using auth-xxx.
    
    === Functions Setup
    
    A functions directory will be created in your project with a Node.js
    package pre-configured. Functions can be deployed with firebase deploy.
    
    ? What language would you like to use to write Cloud Functions? JavaScript
    ? Do you want to use ESLint to catch probable bugs and enforce style? Yes
    ✔  Wrote functions/package.json
    ✔  Wrote functions/.eslintrc.json
    ✔  Wrote functions/index.js
    ✔  Wrote functions/.gitignore
    ? Do you want to install dependencies with npm now? Yes
    
    > protobufjs@6.8.8 postinstall /Users/coco/Documents/firebase-auth/functions/node_modules/protobufjs
    > node scripts/postinstall
    
    npm notice created a lockfile as package-lock.json. You should commit this file.
    added 344 packages from 245 contributors and audited 869 packages in 11.579s
    found 0 vulnerabilities
    
    
    i  Writing configuration info to firebase.json...
    i  Writing project information to .firebaserc...
    
    ✔  Firebase initialization complete!
    
    
       ╭───────────────────────────────────────────╮
       │                                           │
       │      Update available 7.8.1 → 7.9.0       │
       │   Run npm i -g firebase-tools to update   │
       │                                           │
       ╰───────────────────────────────────────────╯
    

    しっかりESLintを有効にしてた。

    現在の設定を確認

    firebase.jsonを確認する

    cat firebase.json 
    {
      "database": {
        "rules": "database.rules.json"
      },
      "hosting": {
        "public": "public",
        "rewrites": [
          {
            "source": "**",
            "function": "firebaseAuth"
          }
        ],
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ]
      },
      "functions": {
        "predeploy": [
          "npm --prefix \"$RESOURCE_DIR\" run lint"
        ]
      }
    }

    黄色の箇所を削除し、再度“` firebase deploy“`を行うと、ESlintが行われずdeployされる。

    参考情報

  • Firebase AuthenticationにFacebook Accountでログインする

    Firebase AuthenticationにFacebook Accountでログインする

    はじめに

    Firebase AuthenticationにFacebook Accountでログインを有効にさせる方法をまとめます。

    設定

    Facebook for Developers(以下Facebook)にログインして、アカウントのセットアップをします

    https://developers.facebook.com/?locale=ja_JP

     

    Firebaseのログインプロバイダの画面で「Facebookログイン」を有効にします。

    Facebook側のページに戻り、左側の設定のからベーシックを押し、アプリID/app secretを確認します。

    Firebase側に戻り、それぞれ埋めます。

    Facebookでクイックスタートからウェブを選択します。

    WebアプリケーションのURLを入力。

    Firebaseの画面に表示されているOAuth リダイレクト URI を Facebook アプリの設定に追加します。

    以上で設定は完了です。

    Signin

    自作のアプリケーションからSigninします

    Facebookログインを試みると、

    よく見るFacebookの承認画面が表示され、ログインを押すと、無事アプリケーションにログインできるようになりました。

    注意すべきところ

    接続元の環境がhttp

    ローカルで開発しているので、http://localhost/ で確認していたのですが、httpでFacebookログインを試みると

    Facebook側で以下のようなアラートが出て、invalid_request

    無視して進めたところ認証エラーが。

    Error getting verification code from facebook.com response: error=invalid_request&error_code=191&error_description

    というエラーが表示されるようになりました。

    その対策としてFirebase Hostingへdeployして、httpsで接続できるようにした上でFacebookとの接続をするようにしました。

    メールアドレスの重複

    既に他のソーシャルアカウントでログインした後に、Facebookアカウントでログインを試みるとエラーが。。

    An account already exists with the same email address but different sign-in credentialsSign in using a provider associated with this email address

    どうやらFirebaseのデフォルトの動きとしてソーシャルアカウントに登録したメールアドレスが、他のソーシャルアカウントで使っている場合、「既に登録してある」と見なされアカウント作成できないようです。

    もちろんFirebaseで承認したアカウントを削除することで、Facebookアカウントでログインできるようになりました。

     

    しかし、やはりユーザーによっては複数ソーシャルアカウントが同一メールアドレスで登録している人も少なくありません。

    設定変更画面から複数メールアドレスの登録を許可させることができます。

    デフォルトでは上段が選択されていますが、下の「複数のアカウントを作成できるようにする」を選択します。

    Google認証に加え、Facebookアカウントでもログインできるようになりました。
    登録アカウントは以下の通り。

    Firebaseはシンプルな認証機能を提供してくれるので、これからアプリケーションを作っていくという場合は最適な選択肢になるのではないでしょうか。

     

     

  • firebase authenticationでユーザーのimport/exportについて調べた

    firebase authenticationでユーザーのimport/exportについて調べた

    はじめに

    Firebase Authentication は、firebase での認証処理を行うための機能です。
    ID/PWによるパスワード認証、電話番号認証、Google、Facebook、Twitterなどソーシャルアカウントを使用した認証を行うことができます。

    本記事はfirebase authenticationでユーザーのimport/exportについて調べました。

    firebase authenticationの責務について

    責務としては認証までです。
    認可については本機能のスコープ外になります。

    詳細は以下参考

    https://apps-gcp.com/firebase-authentication/

     

    コンソール画面での見え方について

    コンソール画面にcsv/json形式でimportする機能があっても良さそうですが、残念ながらそのボタンは見当たりません。

    青い「ユーザーを追加」ボタンを押しても、メールアドレスとパスワードを入力する画面が表示されるのみです。

    対応

    firebase cliを使うことで、具体的には “` firebase auth:import “` コマンドを使うことでimportが可能ということが分かりました。

    https://firebase.google.com/docs/cli/auth-import#syntax

    firebase cliのinstall方法はこちら

    https://firebase.google.com/docs/cli?hl=ja

    jsonファイルを作成する

    試しにtwitter認証アカウントを2つ、Google認証というアカウントを1つ。合計3ユーザーを作成することにします。

    {
      "users": [
        {
          "localId": "1",
          "email": "ec@sumito.jp",
          "emailVerified": null,
          "passwordHash": null,
          "salt": null,
          "displayName": "test1",
          "photoUrl": null,
          "providerUserInfo": [
            {
              "providerId": "twitter.com",
              "rawId": "xxxxxxxxxxxx",
              "email":  null,
              "displayName": "test1",
              "photoUrl": null
            }
          ]
        },
        {
          "localId": "2",
          "email": "sute@sumito.jp",
          "emailVerified": null,
          "passwordHash": null,
          "salt": null,
          "displayName": "test2",
          "photoUrl": null,
          "providerUserInfo": [
            {
              "providerId": "twitter.com",
              "rawId": "xxxxxxxxxxxx",
              "email":  null,
              "displayName": "test2",
              "photoUrl": null
            }
          ]
        },
        {
          "localId": "3",
          "email": "mitsuisumito.viva@gmail.com",
          "emailVerified": true,
          "displayName": "sumito tsukada",
          "photoUrl": "https://lh3.googleusercontent.com/a-/xxx,
          "providerUserInfo": [
            {
              "providerId": "google.com",
              "rawId": "1234",
              "email": "mitsuisumito.viva@gmail.com",
              "displayName": "sumito tsukada",
              "photoUrl": "https://lh3.googleusercontent.com/a-/xxx"
            }
          ]
        }
      ]
    }

     今回はuser.jsonという名前で保存し、読み込ませます。

    $ firebase auth:import ./user.json --hash-algo=HMAC_SHA256  --hash-key=hogehoge
    Processing ./user.json (1451 bytes)
    Starting importing 3 account(s).
    ✔  Imported successfully.
    

    今回はハッシュアルゴリズムをHMAC_SHA256にしましたが、適宜変更してください。

    firebase authentication上でimport確認

    無事importされたようです。

    ちなみに、デフォルトでFirebase authenticationを使いアカウント作成すると、ユーザーUIDはランダム数字になりますが、import形式では任意のIDを指定することができるようです。

    動作確認

    自作のアプリケーションのログイン画面からログインを試みます。

    無事ログインできたようです。

    無事ログイン日時も記載されました

    export

    firebase authenticationに登録されたユーザーは“` firebase auth:export “` コマンドでexportすることができます

    $ firebase auth:export hogehoge --format=json
    Exporting accounts to hogehoge
    ✔  Exported 3 account(s) successfully.

    所感

    firebase authenticationを使えば既存システムからの移行も現実的に見えるかもしれません。
    とはいえ、まだまだ調査すべきところは山のようにあるので、一つ一つ調べていこうと思います。