-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.py
144 lines (120 loc) · 4.56 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
""" This module configures the server app and holds the authentication logic"""
from dotenv import load_dotenv, find_dotenv
from flask import Flask, request, redirect, url_for, session, render_template
from flask_cache import Cache
from flask_compress import Compress
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from flask_sslify import SSLify
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
from models import get_models
from requests_oauthlib import OAuth2Session
import json
import os
COMPRESS_MIMETYPES = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript']
COMPRESS_LEVEL = 6
COMPRESS_MIN_SIZE = 500
load_dotenv(find_dotenv())
COMPANY_EMAIL = "@futurice.com"
app = Flask(__name__, static_url_path='', static_folder='static')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.getcwd() + '/database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY")
sslify = SSLify(app)
db = SQLAlchemy(app)
compress = Compress()
compress.init_app(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.session_protection = "strong"
User, Location, Detection, TrainingDetection, Measurement, Device = get_models(db)
def get_name_from_email(email):
return email.split("@")[0].replace('.', ' ').title()
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
""" OAuth Session creation """
def get_google_auth(state=None, token=None):
if token:
return OAuth2Session(Auth.CLIENT_ID, token=token)
if state:
return OAuth2Session(
Auth.CLIENT_ID,
state=state,
redirect_uri=Auth.REDIRECT_URI)
oauth = OAuth2Session(
Auth.CLIENT_ID,
redirect_uri=Auth.REDIRECT_URI,
scope=Auth.SCOPE)
return oauth
""" App Routing """
def is_employee(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if current_user.email.endswith(COMPANY_EMAIL):
return f(*args, **kwargs)
else:
return render_template('denied.html')
return decorated_function
class Auth:
"""Google Project Credentials"""
CLIENT_ID = os.environ.get('CLIENT_ID', None)
CLIENT_SECRET = os.environ.get('CLIENT_SECRET', None)
HOST = os.environ.get('HOST', 'localhost:5000')
REDIRECT_URI = 'https://{host}/gCallback'.format(host=HOST)
AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
USER_INFO = 'https://www.googleapis.com/userinfo/v2/me'
SCOPE = ['email']
@app.route('/login')
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
google = get_google_auth()
auth_url, state = google.authorization_url(
Auth.AUTH_URI, access_type='offline')
session['oauth_state'] = state
return render_template('login.html', auth_url=auth_url)
@app.route('/gCallback')
def callback():
if current_user is not None and current_user.is_authenticated:
return redirect(url_for('index'))
if 'error' in request.args:
if request.args.get('error') == 'access_denied':
return 'You denied access.'
return 'Error encountered.'
if 'code' not in request.args and 'state' not in request.args:
return redirect(url_for('login'))
else:
google = get_google_auth(state=session['oauth_state'])
try:
token = google.fetch_token(
Auth.TOKEN_URI,
client_secret=Auth.CLIENT_SECRET,
authorization_response=request.url.replace("http://", "https://"))
except:
return 'HTTPError occurred.'
google = get_google_auth(token=token)
resp = google.get(Auth.USER_INFO)
if resp.status_code == 200:
user_data = resp.json()
email = user_data['email']
name = get_name_from_email(email)
user = User.query.filter_by(email=email).first()
if user is None:
user = User()
user.email = email
user.name = name
user.tokens = json.dumps(token)
user.avatar = user_data['picture']
db.session.add(user)
db.session.commit()
login_user(user)
return redirect(url_for('index'))
return 'Could not fetch your information.'
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('index'))