Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AWSの勉強 #7

Closed
tomoyuki-nakabayashi opened this issue Jun 16, 2018 · 40 comments
Closed

AWSの勉強 #7

tomoyuki-nakabayashi opened this issue Jun 16, 2018 · 40 comments

Comments

@tomoyuki-nakabayashi
Copy link
Owner

tomoyuki-nakabayashi commented Jun 16, 2018

AWSによるサーバレスアーキテクチャをやる。

ソースコードはここ。
https://github.com/sbarski/serverless-architectures-aws

@tomoyuki-nakabayashi
Copy link
Owner Author

過去にAWSアカウントを停止してしまっていた。
サポートフォームから再開を申請中。

@tomoyuki-nakabayashi
Copy link
Owner Author

付録Bのインストールとセットアップをやる。

@tomoyuki-nakabayashi
Copy link
Owner Author

aws-cliをインストールする。

https://docs.aws.amazon.com/ja_jp/streams/latest/dev/kinesis-tutorial-cli-installation.html
$ curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
$ sudo python get-pip.py
$ sudo pip install awscli
$ aws help
AWS()                                                                    AWS()



NAME
       aws -

DESCRIPTION
       The  AWS  Command  Line  Interface is a unified tool to manage your AWS
       services.

SYNOPSIS
...

@tomoyuki-nakabayashi
Copy link
Owner Author

IAM (Identity and Access Management) を設定する。

@tomoyuki-nakabayashi
Copy link
Owner Author

最初のlambdaを作成し、ローカルでテストする。
index.jsがあるディレクトリで次を実行する。

npm install run-local-lambda --save-dev

@tomoyuki-nakabayashi
Copy link
Owner Author

なんか文句を言われたので、言われた通りやってみる。

┌────────────────────────────────────────────────────────────┐
│                  npm update check failed                   │
│            Try running with sudo or get access             │
│            to the local update config store via            │
│ sudo chown -R $USER:$(id -gn $USER) /home/tomoyuki/.config │
└────────────────────────────────────────────────────────────┘

@tomoyuki-nakabayashi
Copy link
Owner Author

tomoyuki-nakabayashi commented Jul 8, 2018

$ npm test
Error: Cannot find module 'aws-sdk'

ムムム?

$ ls node_modules/

にaws-sdkがない。

$ npm install aws-sdk
$ npm test
> [email protected] test /home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video
> run-local-lambda --file index.js --event tests/event.json

key: my video.mp4 my video.mp4 my video
{ errorMessage: 'User: arn:aws:iam::998535819267:user/lambda-upload is not authorized to perform: elastictranscoder:CreateJob on resource: arn:aws:elastictranscoder:us-east-1:998535819267:pipeline/1530966437207-utqiym',
  errorType: 'AccessDeniedException',
  stack: 'AccessDeniedException: User: arn:aws:iam::998535819267:user/lambda-upload is not authorized to perform: elastictranscoder:CreateJob on resource: arn:aws:elastictranscoder:us-east-1:998535819267:pipeline/1530966437207-utqiym\n    at Object.extractError (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/protocol/json.js:48:27)\n    at Request.extractError (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/protocol/rest_json.js:52:8)\n    at Request.callListeners (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/sequential_executor.js:105:20)\n    at Request.emit (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/sequential_executor.js:77:10)\n    at Request.emit (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/request.js:683:14)\n    at Request.transition (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/request.js:22:10)\n    at AcceptorStateMachine.runTo (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/state_machine.js:14:12)\n    at /home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/state_machine.js:26:10\n    at Request.<anonymous> (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/request.js:38:9)\n    at Request.<anonymous> (/home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video/node_modules/aws-sdk/lib/request.js:685:12)' }

OK!

@tomoyuki-nakabayashi
Copy link
Owner Author

package.jsonのscriptsにdeployとpredeployを追加する。
npm run deploy時に実行するスクリプトをここに書けるらしい。

$ npm run deploy
> [email protected] deploy /home/tomoyuki/work/07.PlayGround/MyPlayGround/Serverless/transcode-video
> aws lambda update-function-code --function-name  arn:aws:lambda:us-east-1:998535819267:function:transcode-video --zip-file fileb://Lambda-Deployment.zip

{
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "t0Cm/aecZC/7VjM9pvYInLfzWq9BzhxYQwy4+Ud6Ul8=",
    "FunctionName": "transcode-video",
    "CodeSize": 5432714,
    "RevisionId": "b2463bde-a752-4d39-a539-4d800445eca3",
    "MemorySize": 128,
    "FunctionArn": "arn:aws:lambda:us-east-1:998535819267:function:transcode-video",
    "Version": "$LATEST",
    "Role": "arn:aws:iam::998535819267:role/lambda-s3-execution-role",
    "Timeout": 3,
    "LastModified": "2018-07-08T11:06:42.280+0000",
    "Handler": "index.handler",
    "Runtime": "nodejs6.10",
    "Description": ""
}

OK!

@tomoyuki-nakabayashi
Copy link
Owner Author

AWS Lambdaで動作確認する。

できたぁ!

@tomoyuki-nakabayashi
Copy link
Owner Author

あ、serverless-video-transcoded-nkbじゃなくて、severlessになっている…。ひどいtypoだ…。

@tomoyuki-nakabayashi
Copy link
Owner Author

https://www.johnvansickle.com/ffmpeg/

ffmpegのスタティックビルドを使う。

@tomoyuki-nakabayashi
Copy link
Owner Author

26M 7月 10 20:34 Lambda-Deployment.zip

26MBか。ffprobeが61MBなのにけっこう小さくなるもんだ。

@tomoyuki-nakabayashi
Copy link
Owner Author

3章が一通り終わった。けっこうGUIでポチポチしないといけないのが面倒だが、簡単にできるな。

@tomoyuki-nakabayashi
Copy link
Owner Author

演習問題は一旦お預けで、前に進もう。

@tomoyuki-nakabayashi
Copy link
Owner Author

4章はセキュリティ、ログ、アラート、課金、全て重要だな!

@tomoyuki-nakabayashi
Copy link
Owner Author

tomoyuki-nakabayashi commented Jul 10, 2018

pp.86 ポリシーのバージョンに2018が含まれているとダメらしい?なんで?

かならず、2012-10-17を指定しないといけないらしい。あっそ。

@tomoyuki-nakabayashi
Copy link
Owner Author

仮想マシンを切ってしまった…。明日デプロイテストをしよう。

@tomoyuki-nakabayashi
Copy link
Owner Author

第2部第5章

  • API Gateway
  • Auth0

このあたりのことがわかるようだ。

@tomoyuki-nakabayashi
Copy link
Owner Author

Amazon Cognitoも知りたかったが、これは範囲外か…。

@tomoyuki-nakabayashi
Copy link
Owner Author

少し付録Cに寄り道。認証と認可について。

@tomoyuki-nakabayashi
Copy link
Owner Author

うーん、ちょっと認証周りの説明がちゃんと理解できていないな。作ってから一旦戻ってくる必要がありそうだ。

@tomoyuki-nakabayashi
Copy link
Owner Author

tomoyuki-nakabayashi commented Jul 14, 2018

webサイトをホスティングするのに、local-web-serverモジュールが利用できる。

npm install local-web-server --save-dev
  "scripts": {
    "start": "ws",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

package.jsonに↑のように書いて、npm startでweb serverが起動する。あとはブラウザでアクセスすればよい。

@tomoyuki-nakabayashi
Copy link
Owner Author

html5のローカルストレージ機能を使っている。
過去に1度でもtokenを保存してあれば、local storageからデータをリストアする。

    var idToken = localStorage.getItem('userToken');

    if (idToken) {
      this.configureAuthenticatedRequests();
      this.data.auth0Lock.getProfile(idToken, function(err, profile) {
        if (err) {
          return alert('There was an error getting the profile: ' + err.message);
        }
        that.showUserAuthenticationDetails(profile);
      });
    }

@tomoyuki-nakabayashi
Copy link
Owner Author

今後、HTTPリクエストを出すときに、HTTPリクエストのAuthorizationヘッダーにtokenが組み込まれる、と。

  configureAuthenticatedRequests: function() {
    $.ajaxSetup({
      'beforeSend': function(xhr) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('userToken'));
      }
    });
  },

@tomoyuki-nakabayashi
Copy link
Owner Author

よしよし。

image

@tomoyuki-nakabayashi
Copy link
Owner Author

sign upもlog inもできないが?と思ったら、auth0にアカウントは作られている?

@tomoyuki-nakabayashi
Copy link
Owner Author

うーん?パスワード変更とかはできるぞ。ページからうまくリクエストを遅れていない?

@tomoyuki-nakabayashi
Copy link
Owner Author

やっとできた…。

auth0の設定でAllowed Web Originsを設定しないとダメみたい。しょーもな…。

@tomoyuki-nakabayashi
Copy link
Owner Author

ログアウトボタンにトグルしないんだよなぁ。気になるが、少し先に進めるか。

@tomoyuki-nakabayashi
Copy link
Owner Author

Auth0のAPIバージョンの9が使えなくなっているのか…。

@tomoyuki-nakabayashi
Copy link
Owner Author

https://auth0.com/docs/libraries/lock/v11

ここを参考に作り替えよう。

<script src="https://cdn.auth0.com/js/lock/11.6.1/lock.min.js"></script>
<script>
  var lock = new Auth0Lock('XT8qlbyX4sKkJpjb8QMvprEZmuQ345T5', 't-nakabayashi.auth0.com', {
    auth: {
      redirectUrl: 'http://127.0.0.1:8000',
      responseType: 'code',
      params: {
        scope: 'openid email' // Learn about scopes: https://auth0.com/docs/scopes
      }
    }
  });
</script>
<button onclick="lock.show();">Login</button>

@tomoyuki-nakabayashi

This comment has been minimized.

@tomoyuki-nakabayashi
Copy link
Owner Author

変更箇所

newするときにパラメータを指定しろ、とのことなので、APIリファレンス通りに設定する。

    this.data.auth0Lock = new Auth0Lock(config.auth0.clientId, config.auth0.domain, {
      auth: {
        redirectUrl: 'http://127.0.0.1:8000',
        responseType: 'code',
        params: {
          scope: 'openid email user_metadata picture' // Learn about scopes: https://auth0.com/docs/scopes
        }
      }
    });

ユーザー情報を取得するAPIが、getProfile()からgetUserInfo()に変更されている。

    if (idToken) {
      this.configureAuthenticatedRequests();
      this.data.auth0Lock.getUserInfo(idToken, function(err, profile) {

show()でエラーハンドリングするのではなく、on()でイベントを処理するAPI仕様になっている。
show()は呼び出しだけを行っており、on()の"authenticated"イベントでログイン処理を実行する。

    this.data.auth0Lock.on("authenticated", function(authResult) {
      that.data.auth0Lock.getUserInfo(authResult.accessToken, function(error, profile) {
        that.data.auth0Lock.hide();
        if (error) return alert("Auth0 error:" + error);

        localStorage.setItem("userToken", authResult.accessToken);
        that.configureAuthenticatedRequests();
        that.showUserAuthenticationDetails(profile);
      })
    });

    this.uiElements.loginButton.click(function(e) {
      that.data.auth0Lock.show({
        auth: {
          params: {
              responseType: 'id_token token'
          }
        }
      });
    });

@tomoyuki-nakabayashi
Copy link
Owner Author

curlだと返ってくるね。lambdaでこれが返せればいいわけだ。

curl --request GET   --url 'https://t-nakabayashi.auth0.com/userinfo'   --header 'Authorization: Bearer  {CLIENT_SECRET}'   --header 'Content-Type: application/json'
{"sub":"auth0|5b4aa9c4a177ac1965fd94dd","nickname":"hoge","name":"[email protected]","picture":"https://s.gravatar.com/avatar/6211b8e523369e03e6e33da45fde1c7e?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fch.png","updated_at":"2018-07-15T05:00:04.537Z","email":"[email protected]","email_verified":true}

@tomoyuki-nakabayashi
Copy link
Owner Author

やっと進んだ。長かった。

$.getの返り値がよくわからん。あとで調べておこう。

@tomoyuki-nakabayashi
Copy link
Owner Author

結局、↓で言っている通りで、トークンを両方送らないとダメなんでしょう。問題はどうやって両方送るか、なんだが。

Seems like the userToken from the book is split up into idToken and accessToken.

I tried to go with one of them, but it didn't work.

You need the idToken to do the jwt.verify in the user-profile lambda function.

The POST /tokeninfo endpoind of Auth0 seems to be gone and now you need to use GET /userinfo to get the profile information. This call needs to have the accessToken inside the Authorization header.

So I sent both tokens to the user-profile lambda, one for auth, one for userinfo.

@tomoyuki-nakabayashi
Copy link
Owner Author

tomoyuki-nakabayashi commented Jul 16, 2018

$なんとかってjQueryの関数なのか。

$.get()は次のような感じなので、data部分にidTokenを埋め込んであげれば良い?
後は、Lambdaでどうやって取得できるか、か。

http://semooh.jp/jquery/api/ajax/jQuery.get/+url,+data,+callback+/

ちゃんと見ると↓に書いてありそう。bodyで渡すならpostだよなぁ。クエリパラメータで渡すか?

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html

@tomoyuki-nakabayashi
Copy link
Owner Author

付録EにAPI Gatewayのマッピングについて書いてある。GETメソッドのクエリパラメータで追加してみよう。

@tomoyuki-nakabayashi
Copy link
Owner Author

カスタムリクエストヘッダー、そういうのもあるのか

@tomoyuki-nakabayashi
Copy link
Owner Author

https://auth0.com/docs/integrations/aws/tokens

delegationか。POSTのbodyでid_tokenを投げているな。access tokenは?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant