-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.py
209 lines (169 loc) · 6.5 KB
/
run.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from flask import (Flask, render_template, redirect, request, flash,
session, jsonify)
from templates.__init__ import app
from templates.begin.views import hello_blueprint
from werkzeug.datastructures import ImmutableMultiDict
import math
import time
import json
import random
import string
import datetime
import threading
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import (update, asc, desc)
from model import User, Contact, AlertSet, Alert, CheckIn, ReqCheck, connect_to_db, db
import requests
import logging
from flask_cors import CORS, cross_origin
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///besafe'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy()
db.app = app
db.init_app(app)
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"
CORS(app)
session=session
################################################################
# @app.route('/callback')
# def callback_handling():
# # Handles response from token endpoint
# auth0.authorize_access_token()
# resp = auth0.get('userinfo')
# userinfo = resp.json()
# # Store the user information in flask session.
# session['jwt_payload'] = userinfo
# session['profile'] = {
# 'user_id': userinfo['sub'],
# 'name': userinfo['name'],
# 'picture': userinfo['picture'],
# 'email': userinfo['email']
# }
# #Sets the 'current_user' value in the session to the user's e-mail
# session['current_user'] = userinfo['email']
# #User Table is Queried to see if User already exists in dB
# user = User.query.filter_by(email=userinfo['email']).all()
# #If the user isn't in the dBase, they are added
# if user == []:
# new_user = User(name=userinfo['name'], email=userinfo['email'], username=userinfo['nickname'], fname=userinfo['given_name'], lname=userinfo['family_name'], created_at=datetime.datetime.now())
# db.session.add(new_user)
# #The dBase changes are committed
# db.session.commit()
# #Redirects to the User Profile
# return redirect('/')
@app.route('/login', methods=['OPTIONS'])
def login_options():
return '200'
@app.route('/login', methods=['POST'])
def login_handling():
# Handles response from token endpoint
if 'current_user' in session:
return "User Already logged In"
else:
print(request.json)
name = request.json['user']['name']
username = request.json['user']['nickname']
email = request.json['user']['email']
auth0_id = str(request.json['user']['sub'])
print('auth0: ', auth0_id)
#Sets the 'current_user' value in the session to the user's e-mail
session['current_user'] = auth0_id
print('Session: ', session)
#User Table is Queried to see if User already exists in dB
user = User.query.filter_by(auth0_id=auth0_id).all()
#If the user isn't in the dBase, they are added
if user == []:
new_user = User(name=name, email=email, username=username, auth0_id=auth0_id, created_at=datetime.datetime.now())
db.session.add(new_user)
db.session.commit()
print('session3', session)
return "New User Success"
else:
user = user[0]
print('Python User: ', user)
print('Python User2: ', user)
# #The dBase changes are committed
db.session.commit()
print('session', session)
contacts = Contact.query.filter_by(user_id=user.user_id).all()
# contacts2 = []
# user2 = {}
# for key, value in user:
# user2[key] = value
# for contact in contacts:
# c = {}
# for key, value in contact:
# c[key] = value
# contacts2.append(c)
user_id = json.dumps({'user_id': user.user_id})
print('Response to server and type: ', user_id, type(user_id))
# print('all_info: ', all_info)
#Redirects to the User Profile
return user_id
@app.route("/contacts", methods=['OPTIONS'])
def user_contacts_options():
return '200'
@app.route("/contacts", methods=['POST'])
def user_contacts():
"""Renders the User's 'contacts' Page"""
print('Request.json for Contacts', request.json)
user_id = int(request.json['user_id']['user_id'])
print('User_id: ', user_id)
contacts = Contact.query.filter_by(user_id=user_id).order_by(asc(Contact.contact_id)).all()
output = []
for c in contacts:
output.append(c.as_dict())
print ("Contacts Output: ", output)
print ("Contacts Called All Contacts: ", contacts)
contacts = json.dumps(output)
return contacts
@app.route("/del_contact/<contact_id>", methods=['OPTIONS'])
def delete_contact_options():
return '200'
@app.route("/del_contact/<contact_id>", methods=['GET'])
def delete_contact(contact_id):
"""Deletes a user's contact from the dBase"""
#Queries the contact in question, deletes it from the dBase, and commits
contact = Contact.query.filter_by(contact_id=contact_id).one()
db.session.delete(contact)
db.session.commit()
return "Contact Deleted"
@app.route("/edit_contact/<contact_id>", methods=["POST"])
@cross_origin()
def edit_contact(contact_id):
"""Edit's a contact's info"""
#Creates variables from the form on the contacts page
print("Edit Contact request.json: ", request.json)
name = request.json['name']
phone = request.json['phone']
email = request.json['email']
user_id = request.json['user_id']
contact_id = request.json['contact_id']
if contact_id != 'new':
((db.session.query(Contact).filter_by(contact_id=contact_id)).update(
{'name':name, 'email':email, 'phone':phone}))
contact = Contact.query.filter_by(contact_id=contact_id).one()
db.session.commit()
else:
new_contact = Contact(user_id=user_id, name=name, email=email, phone=phone)
db.session.add(new_contact)
db.session.commit()
contact = Contact.query.order_by(Contact.contact_id.desc()).first()
print("Edit Contact Output: ", contact)
output = json.dumps({'new_contact_id': contact.contact_id})
return output
@app.route("/logout", methods=['OPTIONS'])
def logout_options():
return '200'
@app.route("/logout", methods=['GET'])
def logout():
"""Logs user out and deletes them from the session (Tested)"""
# Clear session stored data
session.clear
# Redirect user to logout endpoint
return "Logged Out"
#################################################################
if __name__ == '__main__':
app.config.from_object('configurations.DevelopmentConfig')
app.run()