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

Copied Endpoints Echo sample from /appengine/endpoints #247

Merged
merged 8 commits into from
Nov 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions endpoints/getting-started/Dockerfile.custom
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM gcr.io/google_appengine/nodejs

ADD . /app
WORKDIR /app

RUN npm install
ENV PORT=8081
ENTRYPOINT ["npm", "start"]
39 changes: 39 additions & 0 deletions endpoints/getting-started/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Google Cloud Endpoints sample for Node.js

This sample demonstrates how to use Google Cloud Endpoints using Node.js.

For a complete walkthrough showing how to run this sample in different
environments, see the
[Google Cloud Endpoints Quickstarts](https://cloud.google.com/endpoints/docs/quickstarts).

## Running locally

Refer to the [appengine/README.md](../../appengine/README.md) file for
instructions on running locally.

## Send an echo request

Choose your local or production server:

```
# If you're running locally, you won't need an API key.
$ export ENDPOINTS_HOST=http://localhost:8080

$ export ENDPOINTS_HOST=https://PROJECT-ID.appspot.com
$ export ENDPOINTS_KEY=AIza...
```

Send the request:

```
$ curl -vv -d '{"message":"foo"}' -H 'Content-Type: application/json' "${ENDPOINTS_HOST}/echo?key=${ENDPOINTS_KEY}"
```

If you're running locally, you won't need an API key.

## Sending authenticated requests

No Node.js client is written yet, but you can try the Python client found [here][python-client].
It will send authenticated JWT requests using a Google Cloud service account, or using a three-legged OAuth flow.

[python-client]: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/endpoints/getting-started
51 changes: 51 additions & 0 deletions endpoints/getting-started/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2015-2016, Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START app]
'use strict';

// [START setup]
var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
// [END setup]

app.post('/echo', function (req, res) {
res.status(200).json({ message: req.body.message });
});

function authInfoHandler (req, res) {
var authUser = { id: 'anonymous' };
var encodedInfo = req.get('X-Endpoint-API-UserInfo');
if (encodedInfo) {
authUser = JSON.parse(new Buffer(encodedInfo, 'base64'));
}
res.status(200).json(authUser);
}

app.get('/auth/info/googlejwt', authInfoHandler);
app.get('/auth/info/googleidtoken', authInfoHandler);

// [START listen]
var PORT = process.env.PORT || 8080;
app.listen(PORT, function () {
console.log('App listening on port %s', PORT);
console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
21 changes: 21 additions & 0 deletions endpoints/getting-started/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright 2015-2016, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: nodejs
vm: true

beta_settings:
# Enable Google Cloud Endpoints API management.
use_endpoints_api_management: true
# Specify the Swagger API specification.
endpoints_swagger_spec_file: swagger.yaml
56 changes: 56 additions & 0 deletions endpoints/getting-started/container-engine.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: Service
metadata:
name: esp-echo
spec:
ports:
- port: 80
targetPort: 8080
protocol: TCP
name: http
selector:
app: esp-echo
type: LoadBalancer
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: esp-echo
spec:
replicas: 1
template:
metadata:
labels:
app: esp-echo
spec:
containers:
# [START esp]
- name: esp
image: b.gcr.io/endpoints/endpoints-runtime:0.3
args: [
"-p", "8080",
"-a", "127.0.0.1:8081",
"-s", "SERVICE_NAME",
"-v", "SERVICE_VERSION",
]
# [END esp]
ports:
- containerPort: 8080
- name: echo
image: gcr.io/google-samples/node-echo:1.0
ports:
- containerPort: 8081
22 changes: 22 additions & 0 deletions endpoints/getting-started/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "appengine-endpoints",
"description": "Endpoints Node.js sample for Google App Engine",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "~4.2"
},
"scripts": {
"start": "node app.js",
"test": "mocha -R spec -t 120000 --require intelli-espower-loader ../../test/_setup.js test/*.test.js"
},
"dependencies": {
"express": "^4.13.4",
"body-parser": "^1.15.0"
},
"devDependencies": {
"mocha": "^2.5.3"
}
}
108 changes: 108 additions & 0 deletions endpoints/getting-started/swagger.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# [START swagger]
swagger: "2.0"
info:
description: "A simple Google Cloud Endpoints API example."
title: "Endpoints Example"
version: "1.0.0"
host: "YOUR-PROJECT-ID.appspot.com"
# [END swagger]
basePath: "/"
consumes:
- "application/json"
produces:
- "application/json"
schemes:
- "https"
paths:
"/echo":
post:
description: "Echo back a given message."
operationId: "echo"
produces:
- "application/json"
responses:
200:
description: "Echo"
schema:
$ref: "#/definitions/echoMessage"
parameters:
- description: "Message to echo"
in: body
name: message
required: true
schema:
$ref: "#/definitions/echoMessage"
"/auth/info/googlejwt":
get:
description: "Returns the requests' authentication information."
operationId: "auth_info_google_jwt"
produces:
- "application/json"
responses:
200:
description: "Authenication info."
schema:
$ref: "#/definitions/authInfoResponse"
x-security:
- google_jwt:
audiences:
# This must match the "aud" field in the JWT. You can add multiple
# audiences to accept JWTs from multiple clients.
- "echo.endpoints.sample.google.com"
"/auth/info/googleidtoken":
get:
description: "Returns the requests' authentication information."
operationId: "authInfoGoogleIdToken"
produces:
- "application/json"
responses:
200:
description: "Authenication info."
schema:
$ref: "#/definitions/authInfoResponse"
x-security:
- google_id_token:
audiences:
# Your OAuth2 client's Client ID must be added here. You can add
# multiple client IDs to accept tokens from multiple clients.
- "YOUR-CLIENT-ID"
definitions:
echoMessage:
properties:
message:
type: "string"
authInfoResponse:
properties:
id:
type: "string"
email:
type: "string"
# This section requires all requests to any path to require an API key.
security:
- api_key: []
securityDefinitions:
# This section configures basic authentication with an API key.
api_key:
type: "apiKey"
name: "key"
in: "query"
# This section configures authentication using Google API Service Accounts
# to sign a json web token. This is mostly used for server-to-server
# communication.
google_jwt:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
# This must match the 'iss' field in the JWT.
x-issuer: "jwt-client.endpoints.sample.google.com"
# Update this with your service account's email address.
x-jwks_uri: "https://www.googleapis.com/service_accounts/v1/jwk/YOUR-SERVICE-ACCOUNT-EMAIL"
# This section configures authentication using Google OAuth2 ID Tokens.
# ID Tokens can be obtained using OAuth2 clients, and can be used to access
# your API on behalf of a particular user.
google_id_token:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
x-issuer: "accounts.google.com"
x-jwks_uri: "https://www.googleapis.com/oauth2/v1/certs"
81 changes: 81 additions & 0 deletions endpoints/getting-started/test/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

var express = require('express');
var path = require('path');
var proxyquire = require('proxyquire').noPreserveCache();
var request = require('supertest');

var SAMPLE_PATH = path.join(__dirname, '../app.js');

function getSample () {
var testApp = express();
sinon.stub(testApp, 'listen').callsArg(1);
var expressMock = sinon.stub().returns(testApp);

var app = proxyquire(SAMPLE_PATH, {
express: expressMock
});
return {
app: app,
mocks: {
express: expressMock
}
};
}

describe('appengine/endpoints/app.js', function () {
var sample;

beforeEach(function () {
sample = getSample();

assert(sample.mocks.express.calledOnce);
assert(sample.app.listen.calledOnce);
assert.equal(sample.app.listen.firstCall.args[0], process.env.PORT || 8080);
});

it('should echo a message', function (done) {
request(sample.app)
.post('/echo')
.send({ message: 'foo' })
.expect(200)
.expect(function (response) {
assert.equal(response.body.message, 'foo');
})
.end(done);
});

it('should try to parse encoded info', function (done) {
request(sample.app)
.get('/auth/info/googlejwt')
.expect(200)
.expect(function (response) {
assert.deepEqual(response.body, { id: 'anonymous' });
})
.end(done);
});

it('should successfully parse encoded info', function (done) {
request(sample.app)
.get('/auth/info/googlejwt')
.set('X-Endpoint-API-UserInfo', new Buffer(JSON.stringify({ id: 'foo' })).toString('base64'))
.expect(200)
.expect(function (response) {
assert.deepEqual(response.body, { id: 'foo' });
})
.end(done);
});
});