forked from argupta98/Python-Webapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
220 lines (181 loc) · 5.97 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
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
210
211
212
213
214
215
216
217
218
219
220
"""
Created on Thu Dec 14 16:12:43 2017
@author: Arjun
"""
#imports
from flask import Flask, render_template, json, request, session, redirect
from werkzeug import generate_password_hash, check_password_hash
from flask.ext.mysql import MySQL
#initialize the flask and SQL Objects
app = Flask(__name__)
mysql = MySQL()
#initializa secret key
app.secret_key='This is my secret key'
#configure MYSQL
app.config['MYSQL_DATABASE_USER'] = 'Arjun'
app.config['MYSQL_DATABASE_PASSWORD'] = '1377Hello!'
app.config['MYSQL_DATABASE_DB'] = 'BucketList'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
#helper function
def check_password(acc_pass, provided_pass):
#provided_pass = generate_password_hash(provided_pass)
if provided_pass==acc_pass:
return True
return False
#define methods for routes (what to do and display)
@app.route("/")
def main():
return render_template('index.html')
@app.route("/main")
def return_main():
return render_template('index.html')
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/showSignIn')
def showSignIn():
return render_template('signin.html')
@app.route('/wishlist')
def wishlist():
return render_template('wishlist.html')
@app.route('/userHome')
def showUserHome():
#check that someone has logged in correctly
if session.get("user"):
return render_template('userHome.html', username=session.get("user")[1])
else:
return render_template('error.html', error = "Invalid User Credentials")
@app.route('/logout')
def logout():
session.pop('user', None)
return redirect('/')
@app.route('/validateLogin', methods=['POST'])
def validate():
try:
_username = request.form['inputEmail']
_password = request.form['inputPassword']
print("Username:", _username, "\n Password:", _password)
#create MySQL Connection
conn = mysql.connect()
#create a cursor to query the stored procedure
cursor = conn.cursor()
print("successfully connected to mysql!")
#get users with this username (should only be one)
cursor.callproc('sp_validateLogin', (_username,))
users = cursor.fetchall()
print("called process")
#acctually validate these users
if len(users)>0:
if check_password(users[0][3], _password):
session['user']=users[0]
return redirect('/userHome')
else:
return render_template('error.html', error="incorrect username or password")
else:
return render_template('error.html', error= "incorrect username or password")
except Exception as ex:
print("Error getting username and password, Error:", ex)
return render_template('error.html', error = 'Missing Email Adress or Password')
finally:
#disconnect from mysql database
cursor.close()
conn.close()
@app.route('/signUp', methods=['POST'])
def signUp():
"""
method to deal with creating a new user in the MySQL Database
"""
print("signing up user...")
#create MySQL Connection
conn = mysql.connect()
#create a cursor to query the stored procedure
cursor = conn.cursor()
try:
#read in values from frontend
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
#Make sure we got all the values
if _name and _email and _password:
print("Email:", _email, "\n", "Name:", _name, "\n", "Password:", _password)
#hash passowrd for security
_hashed_password = generate_password_hash(_password)
print("Hashed Password:", _hashed_password)
#call jQuery to make a POST request to the DB with the info
cursor.callproc('sp_createUser', (_name, _email, _password))
print("Successfully called sp_createUser")
#check if the POST request was successful
data = cursor.fetchall()
if len(data)==0:
conn.commit()
print('signup successful!')
return 'User created successfuly!'
else:
print('error')
return str(data[0])
else:
print('fields not submitted')
return 'Enter the required fields'
except Exception as ex:
print('got an exception: ', ex)
return json.dumps({'error':str(ex)})
finally:
print('ending...')
cursor.close()
conn.close()
@app.route('/addWish',methods=['POST'])
def addWish():
print("in addWIsh")
try:
if session.get('user'):
_title = request.form['inputTitle']
_description = request.form['inputDescription']
_user = session.get('user')[0]
print("title:",_title,"\n description:",_description,"\n user:",_user)
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_addWish',(_title,_description,_user))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
print("finished executing addWish")
return redirect('/userHome')
else:
return render_template('error.html',error = 'An error occurred!')
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
print("in exception for AddWish")
return render_template('error.html',error = str(e))
finally:
cursor.close()
conn.close()
@app.route('/getWish')
def getWish():
conn = mysql.connect()
cursor = conn.cursor()
try:
if session.get('user'):
_user = session.get('user')[0]
print(_user)
cursor.callproc('sp_GetWishByUser',(_user,))
wishes = cursor.fetchall()
wishes_dict = []
for wish in wishes:
wish_dict = {
'Id': wish[0],
'Title': wish[1],
'Description': wish[2],
'Date': wish[4]}
wishes_dict.append(wish_dict)
return json.dumps(wishes_dict)
else:
return render_template('error.html', error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html', error = str(e))
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run()