Skip to content

Commit

Permalink
Add GAE standard + firebase tictactoe sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Jerjou Cheng committed Oct 13, 2016
1 parent 012874e commit 99dc698
Show file tree
Hide file tree
Showing 16 changed files with 1,236 additions and 0 deletions.
62 changes: 62 additions & 0 deletions appengine/firebase-tictactoe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Tic Tac Toe on Google App Engine Standard using Firebase

This directory contains a project that implements a realtime two-player game of
Tic Tac Toe on Google [App Engine Standard][standard], using the [Firebase] database
for realtime notifications when the board changes.

[Firebase]: https://firebase.google.com
[standard]: https://cloud.google.com/appengine/docs/about-the-standard-environment

## Prerequisites

* Install [Apache Maven][maven] 3.0.5 or later
* Create a project in the [Firebase Console][fb-console]
* Install the [Google Cloud SDK][sdk]
* For staging locally, you must supply credentials that would otherwise be
inferred from the App Engine environment. Download [service account
credentials][creds] and set the `GOOGLE_APPLICATION_CREDENTIALS` environment
variable to its path:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.json

* In the [Overview section][fb-overview] of the Firebase console, click 'Add
Firebase to your web app' and replace the contents of the file
`src/main/webapp/WEB-INF/view/firebase_config.jspf` with that code snippet.
* Edit
[`src/main/webapp/WEB-INF/appengine-web.xml`](src/main/webapp/WEB-INF/appengine-web.xml)
and replace `_your_app_id_here_` with your project id.

[fb-console]: https://console.firebase.google.com
[sdk]: https://cloud.google.com/sdk
[creds]: https://console.firebase.google.com/iam-admin/serviceaccounts/project?project=_&consoleReturnUrl=https:%2F%2Fconsole.firebase.google.com%2Fproject%2F_%2Fsettings%2Fgeneral%2F
[fb-overview]: https://console.firebase.google.com/project/_/overview


## Run the sample

* To run the app locally:

```sh
$ mvn appengine:run
```

## Troubleshooting

* If you see the error `Google Cloud SDK path was not provided ...`:
* Make sure you've installed the [Google cloud SDK][sdk]
* You may have installed it in a non-standard path. In that case, set the
environment variable `GOOGLE_CLOUD_SDK_HOME` to point to where you
installed the SDK:
```sh
export GOOGLE_CLOUD_SDK_HOME=/path/to/google-cloud-sdk
```
## Contributing changes
See [CONTRIBUTING.md](../../CONTRIBUTING.md).
## Licensing
See [LICENSE](../../LICENSE).
121 changes: 121 additions & 0 deletions appengine/firebase-tictactoe/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<!--
Copyright 2015 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.
-->
<project>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.appengine</groupId>
<artifactId>appengine-firebase</artifactId>
<parent>
<groupId>com.google.cloud</groupId>
<artifactId>doc-samples</artifactId>
<version>1.0.0</version>
<relativePath>../..</relativePath>
</parent>
<properties>
<objectify.version>5.1.13</objectify.version>
</properties>
<!-- [START set_versions] -->
<prerequisites>
<maven>3.3.9</maven>
</prerequisites>
<!-- [END set_versions] -->
<dependencies>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.sdk.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>${objectify.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-appengine</artifactId>
<version>1.22.0</version>
</dependency>


<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-tools-sdk</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.30</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
</outputDirectory>
<plugins>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>1.0.0</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 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.
*/

package com.example.appengine.firetactoe;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String gameId = req.getParameter("gameKey");
Objectify ofy = ObjectifyService.ofy();
Game game = ofy.load().type(Game.class).id(gameId).safe();

UserService userService = UserServiceFactory.getUserService();
String currentUserId = userService.getCurrentUser().getUserId();

game.deleteChannel(currentUserId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* 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.
*/

package com.example.appengine.firetactoe;

import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CharStreams;

import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class FirebaseChannel {
private static final String FIREBASE_SNIPPET_PATH = "WEB-INF/view/firebase_config.jspf";
private static final Collection FIREBASE_SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/firebase.database",
"https://www.googleapis.com/auth/userinfo.email"
);
private static final String IDENTITY_ENDPOINT =
"https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";
static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();

private String firebaseDbUrl;
private GoogleCredential credential;

private static FirebaseChannel instance;

public static FirebaseChannel getInstance() {
if (instance == null) {
instance = new FirebaseChannel();
}
return instance;
}

private FirebaseChannel() {
try {
String firebaseSnippet = CharStreams.toString(
new InputStreamReader(new FileInputStream(FIREBASE_SNIPPET_PATH)));
firebaseDbUrl = parseFirebaseUrl(firebaseSnippet);

credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private static String parseFirebaseUrl(String firebaseSnippet) {
int idx = firebaseSnippet.indexOf("databaseURL");
if (-1 == idx) {
throw new RuntimeException(
"Please copy your Firebase web snippet into " + FIREBASE_SNIPPET_PATH);
}
idx = firebaseSnippet.indexOf(':', idx);
int openQuote = firebaseSnippet.indexOf('"', idx);
int closeQuote = firebaseSnippet.indexOf('"', openQuote + 1);
return firebaseSnippet.substring(openQuote + 1, closeQuote);
}

public void sendFirebaseMessage(String channelKey, Game game)
throws IOException {
// Make requests auth'ed using Application Default Credentials
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
GenericUrl url = new GenericUrl(
String.format("%s/channels/%s.json", firebaseDbUrl, channelKey));
HttpResponse response = null;

try {
if (null == game) {
response = requestFactory.buildDeleteRequest(url).execute();
} else {
String gameJson = game.getMessageString();
response = requestFactory.buildPatchRequest(
url, new ByteArrayContent("application/json", gameJson.getBytes())).execute();
}

if (response.getStatusCode() != 200) {
throw new RuntimeException(
"Error code while updating Firebase: " + response.getStatusCode());
}

} finally {
if (null != response) {
response.disconnect();
}
}
}

/**
* Create a secure JWT token for the given userId.
*/
public String createFirebaseToken(Game game, String userId) {
final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
final BaseEncoding base64 = BaseEncoding.base64();

String header = base64.encode("{\"typ\":\"JWT\",\"alg\":\"RS256\"}".getBytes());

// Construct the claim
String channelKey = game.getChannelKey(userId);
String clientEmail = appIdentity.getServiceAccountName();
long epochTime = System.currentTimeMillis() / 1000;
long expire = epochTime + 60 * 60; // an hour from now

Map<String, Object> claims = new HashMap<String, Object>();
claims.put("iss", clientEmail);
claims.put("sub", clientEmail);
claims.put("aud", IDENTITY_ENDPOINT);
claims.put("uid", channelKey);
claims.put("iat", epochTime);
claims.put("exp", expire);

String payload = base64.encode(new JSONObject(claims).toString().getBytes());
String toSign = String.format("%s.%s", header, payload);
AppIdentityService.SigningResult result = appIdentity.signForApp(toSign.getBytes());
return String.format("%s.%s", toSign, base64.encode(result.getSignature()));
}
}
Loading

0 comments on commit 99dc698

Please sign in to comment.