updates database design for mariadb

This commit is contained in:
2020-05-27 20:06:43 +02:00
parent 0cfc801f59
commit 355ba99ca3
18 changed files with 435 additions and 139 deletions

View File

@ -13,7 +13,6 @@ app = Flask(__name__,
static_folder='static',
template_folder='template')
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)
app.config.from_object(Config)
db = SQLAlchemy(app)

View File

@ -9,7 +9,6 @@ import flask
# Python standard libraries
import json
import os
import sqlite3
# Third-party libraries
import flask
@ -24,31 +23,47 @@ from flask_login import (
import requests
from database.models import Calendar as dbCalendar
from server import db
# Configuration
CLIENT_SECRETS_FILE = "certificate/client_secret.json"
class GoogleClient():
def __init__(self):
self.CLIENT_SECRETS_FILE = "certificate/client_secret.json"
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/calendar.readonly", "openid"]
API_SERVICE_NAME = 'calendar'
API_VERSION = 'v3'
with open("/home/calendarwatch/certificate/google_client.json", encoding='utf-8') as json_file:
self.google_client = json.load(json_file)
GOOGLE_CLIENT_ID ="377787187748-shuvi4iq5bi4gdet6q3ioataimobs4lh.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET = "Hu_YWmKsVKUcLwyeINYzdKfZ"
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
self.SCOPES = self.google_client.get('scopes')
self.API_SERVICE_NAME = 'calendar'
self.API_VERSION = 'v3'
# OAuth 2 client setup
client = WebApplicationClient(GOOGLE_CLIENT_ID)
# GOOGLE_CLIENT_ID ="377787187748-shuvi4iq5bi4gdet6q3ioataimobs4lh.apps.googleusercontent.com"
self.GOOGLE_CLIENT_ID = self.google_client.get('client_id')
# GOOGLE_CLIENT_SECRET = "Hu_YWmKsVKUcLwyeINYzdKfZ"
self.GOOGLE_CLIENT_SECRET = self.google_client.get('client_secret')
self.GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)
# OAuth 2 client setup
self.client = WebApplicationClient(self.GOOGLE_CLIENT_ID)
def build_credentials(self, token, refresh_token):
data = {}
data['token'] = token
data['refresh_token'] = refresh_token
data['token_uri'] = self.google_client.get('token_uri')
data['client_id'] = self.google_client.get('client_id')
data['client_secret'] = self.google_client.get('client_secret')
data['scopes'] = self.google_client.get('scopes')
return data
GC = GoogleClient()
def login():
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)
GC.CLIENT_SECRETS_FILE, scopes=GC.SCOPES)
# The URI created here must exactly match one of the authorized redirect URIs
# for the OAuth 2.0 client, which you configured in the API Console. If this
# value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
@ -72,7 +87,7 @@ def verifyResponse():
state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
GC.CLIENT_SECRETS_FILE, scopes=GC.SCOPES, state=state)
flow.redirect_uri = flask.url_for('callback', _external=True)
# Use the authorization server's response to fetch the OAuth 2.0 tokens.
@ -91,11 +106,11 @@ def verifyResponse():
def get_google_provider_cfg():
return requests.get(GOOGLE_DISCOVERY_URL).json()
return requests.get(GC.GOOGLE_DISCOVERY_URL).json()
def deleteAccount(user):
result = requests.post('https://oauth2.googleapis.com/revoke',
params={'token': user.get('token')},
params={'token': user.google_token.token},
headers = {'content-type': 'applixation/x-www-form-urlencoded'})
print(result, flush=True)
return
@ -107,10 +122,10 @@ class Calendar:
self.toggle=toggle
self.calendarId = calendarId
# TODO move this to databas
def calendarsFromDb():
calendars = dbCalendar.getCalendars(dbCalendar, current_user.id)
pyCalendars = []
for calendar in calendars:
for calendar in current_user.calendars:
name = (calendar.name[:16] + '..') if len(calendar.name)> 18 else calendar.name
calendarId = calendar.calendar_id
toggle = calendar.toggle
@ -121,20 +136,6 @@ def calendarsFromDb():
return pyCalendars
def getCalendarJson():
if 'credentials' not in flask.session:
return flask.redirect('login/google')
# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])
with open('./userinfo/' + current_user.id + '/calendarevents.json', 'w') as outfile:
json.dump(todaysCal, outfile)
return todaysCal
def updateCalendars():
if 'credentials' not in flask.session:
return flask.redirect('login/google')
@ -145,23 +146,36 @@ def updateCalendars():
# a = flask.session['credentials']
# print(a, flush=True)
# print(current_user.getGoogleCredentials(), flush=True)
if current_user.getGoogleCredentials() == None:
if current_user.google_token == None:
print("notok", flush=True)
return
credentials = google.oauth2.credentials.Credentials(**current_user.getGoogleCredentials())
client_token = GC.build_credentials(current_user.google_token.token,
current_user.google_token.refresh_token)
credentials = google.oauth2.credentials.Credentials(**client_token)
calendars = caltojson.getCalendarList(credentials)
print(calendars, flush=True)
for calendar in calendars:
if dbCalendar.getCalendar(dbCalendar, current_user.id, calendar.calendarId) == None:
dbCalendar.create(dbCalendar, current_user.id, calendar.calendarId, calendar.summary, calendar.color)
print(calendar, flush=True)
if not current_user.hasCalendar(calendar.calendarId):
print("adding", flush=True)
c = dbCalendar(calendar_id=calendar.calendarId,
name = calendar.summary,
toggle = "False",
color = calendar.color)
db.session.add(c)
current_user.calendars.append(c)
db.session.commit()
print("updated Calendars")
# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
# TODO add save updated token to database here
flask.session['credentials'] = credentials_to_dict(credentials)
def credentials_to_dict(credentials):
return {'token': credentials.token,
'refresh_token': credentials.refresh_token,

View File

@ -21,7 +21,7 @@ import server.googleHandler as google
from backend.Routine import Routine
from server import login_manager, app, db
from server.forms import LoginForm, RegistrationForm, DeviceForm
from database.models import User, Calendar, Device
from database.models import User, Calendar, Device, GoogleToken
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
@ -105,19 +105,18 @@ def register():
def deleteAccount():
if not current_user.is_authenticated:
return redirect(url_for('account'))
print(current_user.getGoogleCredentials(), flush=True)
google.deleteAccount(current_user.getGoogleCredentials())
# TODO fix google delete account
google.deleteAccount(current_user)
user = db.session.query(User).filter(User.id==current_user.id).first()
logout_user()
db.session.delete(user)
db.session.delete(current_user)
db.session.commit()
logout_user()
return redirect(url_for('account'))
@app.route("/login/google")
def googlelogin():
if current_user.is_authenticated and current_user.getGoogleCredentials() != None:
if current_user.is_authenticated and current_user.google_credentials.refresh_token != None:
return redirect(url_for('account'))
authorization_url = google.login()
@ -127,35 +126,33 @@ def googlelogin():
@app.route("/login/google/callback")
def callback():
session, credentials = google.verifyResponse()
if current_user.is_authenticated and current_user.getGoogleCredentials == None:
current_user.setGoogleCredentials(credentials)
userinfo = session.get('https://www.googleapis.com/userinfo/v2/me').json()
# Create a user in your db with the information provided
# by Google
# Doesn't exist? Add it to the database.
if not User.query.get(userinfo['id']):
if not db.session.query(User).filter(User.userid==userinfo['id']).first():
gc = GoogleToken(token=credentials.get("token"),
refresh_token=credentials.get("refresh_token"))
db.session.add(gc)
newser = User(
id=userinfo['id'],
userid=userinfo['id'],
username=userinfo['name'],
email=userinfo['email'],
profile_pic=userinfo['picture'],
password_hash=""
password_hash="",
google_token = gc
)
db.session.add(newser)
db.session.commit()
user = User.query.get(userinfo['id'])
user = db.session.query(User).filter(User.userid==userinfo['id']).first()
# Begin user session by logging the user in
print("login:" + user.id)
login_user(user)
# TODO currently not using the credentials anymore
if user.getGoogleCredentials() is None:
user.setGoogleCredentials(credentials)
return flask.redirect(flask.url_for('index'))
@app.route("/logout")

Binary file not shown.