Skip to content

Feedback #1

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

Open
wants to merge 9 commits into
base: feedback
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions datastore/.gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# This file specifies files that are *not* uploaded to Google Cloud
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

# Python pycache:
__pycache__/
# Ignored by the build system
/setup.cfg
6 changes: 6 additions & 0 deletions datastore/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
runtime: python39
handlers:
- url: /static
static_dir: static
- url: /.*
script: auto
20 changes: 20 additions & 0 deletions datastore/index.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Copyright 2021 Google LLC
#
# 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.

indexes:
- kind: visit
ancestor: yes
properties:
- name: timestamp
direction: desc
93 changes: 93 additions & 0 deletions datastore/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import datetime

from flask import Flask, render_template, request
from google.auth.transport import requests
from google.cloud import datastore
import google.oauth2.id_token

firebase_request_adapter = requests.Request()
# [START gae_python38_datastore_store_and_fetch_user_times]
# [START gae_python3_datastore_store_and_fetch_user_times]

datastore_client = datastore.Client()
# [END gae_python3_datastore_store_and_fetch_user_times]
# [END gae_python38_datastore_store_and_fetch_user_times]
app = Flask(__name__)


# [START gae_python38_datastore_store_and_fetch_user_times]
# [START gae_python3_datastore_store_and_fetch_user_times]
def store_time(email, dt):
entity = datastore.Entity(key=datastore_client.key('User', email, 'visit'))
entity.update({
'timestamp': dt
})

datastore_client.put(entity)


def fetch_times(email, limit):
ancestor = datastore_client.key('User', email)
query = datastore_client.query(kind='visit', ancestor=ancestor)
query.order = ['-timestamp']

times = query.fetch(limit=limit)

return times


@app.route('/')
def root():
# Verify Firebase auth.
id_token = request.cookies.get("token")
error_message = None
claims = None
times = None

if id_token:
try:
# Verify the token against the Firebase Auth API. This example
claims = google.oauth2.id_token.verify_firebase_token(
id_token, firebase_request_adapter)

store_time(claims['email'], datetime.datetime.now())
times = fetch_times(claims['email'], 10)

except ValueError as exc:
# verification checks fail.
error_message = str(exc)

return render_template(
'index.html',
user_data=claims, error_message=error_message, times=times)

@app.route('/uploadfile')
def uploadfile():
# Verify Firebase auth.
id_token = request.cookies.get("token")
error_message = None
claims = None
times = None

if id_token:
try:
# Verify the token against the Firebase Auth
claims = google.oauth2.id_token.verify_firebase_token(
id_token, firebase_request_adapter)

store_time(claims['email'], datetime.datetime.now())
times = fetch_times(claims['email'], 10)

except ValueError as exc:
# verification checks fail.
error_message = str(exc)

return render_template(
'uploadfile.html',
user_data=claims, error_message=error_message, times=times)



if __name__ == '__main__':
# This is used when running locally only.
app.run(host='127.0.0.1', port=8080, debug=True)
4 changes: 4 additions & 0 deletions datastore/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Flask==2.0.1
google-cloud-datastore==2.1.6
google-auth==1.31.0
requests==2.26.0
68 changes: 68 additions & 0 deletions datastore/static/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* Copyright 2018, Google LLC
* 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 gae_python38_log]
'use strict';
window.addEventListener('load', function () {
document.getElementById('sign-out').onclick = function () {
firebase.auth().signOut();
};
// FirebaseUI config.
var uiConfig = {
signInSuccessUrl: '/',
signInOptions: [
// Comment out any lines corresponding to providers you did not check in
// the Firebase console.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
//firebase.auth.FacebookAuthProvider.PROVIDER_ID,
//firebase.auth.TwitterAuthProvider.PROVIDER_ID,
//firebase.auth.GithubAuthProvider.PROVIDER_ID,
//firebase.auth.PhoneAuthProvider.PROVIDER_ID
],
// Terms of service url.
tosUrl: '<your-tos-url>'
};
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in, so display the "sign out" button and login info.
document.getElementById('sign-out').hidden = false;
document.getElementById('login-info').hidden = false;
console.log(`Signed in as ${user.displayName} (${user.email})`);
user.getIdToken().then(function (token) {
// Add the token to the browser's cookies. The server will then be
// able to verify the token against the API.
// SECURITY NOTE: As cookies can easily be modified, only put the
// token (which is verified server-side) in a cookie; do not add other
// user information.
document.cookie = "token=" + token;
});
} else {
// User is signed out.
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// Show the Firebase login button.
ui.start('#firebaseui-auth-container', uiConfig);
// Update the login state indicators.
document.getElementById('sign-out').hidden = true;
document.getElementById('login-info').hidden = true;
// Clear the token cookie.
document.cookie = "token=";
}
}, function (error) {
console.log(error);
alert('Unable to log in: ' + error)
});
});
19 changes: 19 additions & 0 deletions datastore/static/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Copyright 2021 Google LLC
*
* 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.
*/
body {
font-family: "helvetica", sans-serif;
text-align: center;
}
34 changes: 34 additions & 0 deletions datastore/static/upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// connect to appropriate page elements via the DOM
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// add an event listener to the
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
// Create file metadata including the content type
var metadata = {
customMetadata: {
userid: '1',
activity: 'Course Work',
notes: 'A fixed message about this file'
}
};
// set upload locaation
var storageRef = firebase.storage().ref('img/'+file.name);
//upload file and metadata
var task = storageRef.put(file, metadata);
// set callback event + function, error function and complete function
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
uploader.value = percentage;

}, function error(err) {
alert("File upload failed:" + err.message);

},function complete() {
alert("File upload successful");
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});
});
94 changes: 94 additions & 0 deletions datastore/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<!doctype html>
<!--
Copyright 2021 Google LLC
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.
-->

<html>
<head>
<title>Datastore and Firebase Auth Example</title>

<!-- See https://github.com/firebase/firebaseui-web. -->
<!-- [START gae_python38_auth_init_firebase] -->
<!-- [START gae_python3_auth_init_firebase] -->
<!-- *******************************************************************************************
* TODO(DEVELOPER): Paste the initialization snippet from:
* http://console.firebase.google.com > Overview > Add Firebase to your web app.
***************************************************************************************** -->
<!-- [END gae_python3_auth_init_firebase] -->
<!-- [END gae_python38_auth_init_firebase] -->

<!-- [START gae_python38_auth_include_firebaseui] -->
<!-- [START gae_python3_auth_include_firebaseui] -->
<script src="https://www.gstatic.com/firebasejs/ui/4.5.0/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.5.0/firebase-ui-auth.css">
<!-- [END gae_python3_auth_include_firebaseui] -->
<!-- [END gae_python38_auth_include_firebaseui] -->
<script src="{{ url_for('static', filename='script.js') }}"></script>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

</head>
<body>

<h1>Datastore and Firebase Auth Example</h1>

<!-- [START gae_python38_auth_firebase_html] -->
<!-- [START gae_python3_auth_firebase_html] -->
<div id="firebaseui-auth-container"></div>

<button id="sign-out" hidden=true>Sign Out</button>

<div id="login-info" hidden=true>
<h2>Login info:</h2>
{% if user_data %}
<dl>
<dt>Name</dt><dd>{{ user_data['name'] }}</dd>
<dt>Email</dt><dd>{{ user_data['email'] }}</dd>
<dt>Last 10 visits</dt><dd>
{% for time in times %}
<p>{{ time['timestamp'] }}</p>
{% endfor %} </dd>
</dl>
{% elif error_message %}
<p>Error: {{ error_message }}</p>
{% endif %}
</div>
<!-- [END gae_python3_auth_firebase_html] -->
<!-- [END gae_python38_auth_firebase_html] -->
</body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.9.0/firebase-app.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.9.0/firebase-auth.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.9.0/firebase-analytics.js"></script>

<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBgVLptO71EgUsSNy3POG2vAT_chDkxzuk",
authDomain: "ad-assignment-335217.firebaseapp.com",
projectId: "ad-assignment-335217",
storageBucket: "ad-assignment-335217.appspot.com",
messagingSenderId: "90196863214",
appId: "1:90196863214:web:17eb70962a9f8cf5392bff",
measurementId: "G-T1BG5KWP2S"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>


</html>
19 changes: 19 additions & 0 deletions sqlconnection/.gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# This file specifies files that are *not* uploaded to Google Cloud
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

# Python pycache:
__pycache__/
# Ignored by the build system
/setup.cfg
Loading