-
Notifications
You must be signed in to change notification settings - Fork 27
/
app.py
196 lines (163 loc) · 6.31 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
import json, sqlite3, click, functools, os, hashlib,time, random, sys
from flask import Flask, current_app, g, session, redirect, render_template, url_for, request
### DATABASE FUNCTIONS ###
def connect_db():
return sqlite3.connect(app.database)
def init_db():
"""Initializes the database with our great SQL schema"""
conn = connect_db()
db = conn.cursor()
db.executescript("""
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS notes;
CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
assocUser INTEGER NOT NULL,
dateWritten DATETIME NOT NULL,
note TEXT NOT NULL,
publicID INTEGER NOT NULL
);
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
);
INSERT INTO users VALUES(null,"admin", "password");
INSERT INTO users VALUES(null,"bernardo", "omgMPC");
INSERT INTO notes VALUES(null,2,"1993-09-23 10:10:10","hello my friend",1234567890);
INSERT INTO notes VALUES(null,2,"1993-09-23 12:10:10","i want lunch pls",1234567891);
""")
### APPLICATION SETUP ###
app = Flask(__name__)
app.database = "db.sqlite3"
app.secret_key = os.urandom(32)
### ADMINISTRATOR'S PANEL ###
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if not session.get('logged_in'):
return redirect(url_for('login'))
return view(**kwargs)
return wrapped_view
@app.route("/")
def index():
if not session.get('logged_in'):
return render_template('index.html')
else:
return redirect(url_for('notes'))
@app.route("/notes/", methods=('GET', 'POST'))
@login_required
def notes():
importerror=""
#Posting a new note:
if request.method == 'POST':
if request.form['submit_button'] == 'add note':
note = request.form['noteinput']
db = connect_db()
c = db.cursor()
statement = """INSERT INTO notes(id,assocUser,dateWritten,note,publicID) VALUES(null,%s,'%s','%s',%s);""" %(session['userid'],time.strftime('%Y-%m-%d %H:%M:%S'),note,random.randrange(1000000000, 9999999999))
print(statement)
c.execute(statement)
db.commit()
db.close()
elif request.form['submit_button'] == 'import note':
noteid = request.form['noteid']
db = connect_db()
c = db.cursor()
statement = """SELECT * from NOTES where publicID = %s""" %noteid
c.execute(statement)
result = c.fetchall()
if(len(result)>0):
row = result[0]
statement = """INSERT INTO notes(id,assocUser,dateWritten,note,publicID) VALUES(null,%s,'%s','%s',%s);""" %(session['userid'],row[2],row[3],row[4])
c.execute(statement)
else:
importerror="No such note with that ID!"
db.commit()
db.close()
db = connect_db()
c = db.cursor()
statement = "SELECT * FROM notes WHERE assocUser = %s;" %session['userid']
print(statement)
c.execute(statement)
notes = c.fetchall()
print(notes)
return render_template('notes.html',notes=notes,importerror=importerror)
@app.route("/login/", methods=('GET', 'POST'))
def login():
error = ""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = connect_db()
c = db.cursor()
statement = "SELECT * FROM users WHERE username = '%s' AND password = '%s';" %(username, password)
c.execute(statement)
result = c.fetchall()
if len(result) > 0:
session.clear()
session['logged_in'] = True
session['userid'] = result[0][0]
session['username']=result[0][1]
return redirect(url_for('index'))
else:
error = "Wrong username or password!"
return render_template('login.html',error=error)
@app.route("/register/", methods=('GET', 'POST'))
def register():
errored = False
usererror = ""
passworderror = ""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = connect_db()
c = db.cursor()
pass_statement = """SELECT * FROM users WHERE password = '%s';""" %password
user_statement = """SELECT * FROM users WHERE username = '%s';""" %username
c.execute(pass_statement)
if(len(c.fetchall())>0):
errored = True
passworderror = "That password is already in use by someone else!"
c.execute(user_statement)
if(len(c.fetchall())>0):
errored = True
usererror = "That username is already in use by someone else!"
if(not errored):
statement = """INSERT INTO users(id,username,password) VALUES(null,'%s','%s');""" %(username,password)
print(statement)
c.execute(statement)
db.commit()
db.close()
return f"""<html>
<head>
<meta http-equiv="refresh" content="2;url=/" />
</head>
<body>
<h1>SUCCESS!!! Redirecting in 2 seconds...</h1>
</body>
</html>
"""
db.commit()
db.close()
return render_template('register.html',usererror=usererror,passworderror=passworderror)
@app.route("/logout/")
@login_required
def logout():
"""Logout: clears the session"""
session.clear()
return redirect(url_for('index'))
if __name__ == "__main__":
#create database if it doesn't exist yet
if not os.path.exists(app.database):
init_db()
runport = 5000
if(len(sys.argv)==2):
runport = sys.argv[1]
try:
app.run(host='0.0.0.0', port=runport) # runs on machine ip address to make it visible on netowrk
except:
print("Something went wrong. the usage of the server is either")
print("'python3 app.py' (to start on port 5000)")
print("or")
print("'sudo python3 app.py 80' (to run on any other port)")