server.py 7.19 KB
Newer Older
1
2
from flask import Flask, render_template, request, redirect, url_for, session
import psycopg2
Vladislav Rykov's avatar
Vladislav Rykov committed
3
import bcrypt
4
5
6
7
8
9
10
import misc


APP_KEY_LEN = 8


server = Flask(__name__, template_folder='templates/')
Vladislav Rykov's avatar
Vladislav Rykov committed
11

12
13
14
15
16
17
18
19
20
21
22
23
24


def new_user(name, password):
    suc = (True, 'User added')
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        INSERT INTO
            users
        VALUES
            (%s, %s)
        """
Vladislav Rykov's avatar
Vladislav Rykov committed
25
26
27
28
29
30
31
32
33
34
35
36
37
        cur.execute(query, (name, bcrypt.hashpw(password, bcrypt.gensalt())))
        conn.commit()
        print('User added')
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error adding a user: ', error)
        suc = (False, error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return suc

38
39


Vladislav Rykov's avatar
Vladislav Rykov committed
40
41
42
43
44
45
def chk_user(name, password):
    suc = (True, 'Success')
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
Vladislav Rykov's avatar
Vladislav Rykov committed
46
        SELECT * FROM
Vladislav Rykov's avatar
Vladislav Rykov committed
47
            users
Vladislav Rykov's avatar
Vladislav Rykov committed
48
49
        WHERE 
            name = %s
Vladislav Rykov's avatar
Vladislav Rykov committed
50
        """
Vladislav Rykov's avatar
Vladislav Rykov committed
51
52
53
54
55
56
57
58
        cur.execute(query, (name,))
        user = cur.fetchall()[0]
        
        if user[1].encode('utf-8') == bcrypt.hashpw(password, user[1].encode('utf-8')):
            session['name'] = user[0]
            print('User logged in')
        else:
            suc = (False, 'Password or username do not match')
59
    except (Exception, psycopg2.DatabaseError) as error:
Vladislav Rykov's avatar
Vladislav Rykov committed
60
        print('Error querying a user: ', error)
61
62
63
64
65
66
67
68
69
        suc = (False, error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return suc


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

def get_apps(username):
    res = []
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        SELECT * FROM
            applications
        WHERE 
            username = %s
        """
        cur.execute(query, (username,))
        res = cur.fetchall()
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error querying applications: ', error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return res



def get_app(appkey):
    res = []
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        SELECT * FROM
            applications
        WHERE 
            app_key = %s
        """
        cur.execute(query, (appkey,))
        res = cur.fetchall()
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error querying applications: ', error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return res




def new_app(name, desc):
    suc = (True, 'App created')
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        INSERT INTO
            applications
        VALUES
            (%s, %s, %s, %s)
        """
        cur.execute(query, (name, misc.rand_str(APP_KEY_LEN), session['name'], desc))
        conn.commit()
        print('App created')
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error creating app: ', error)
        suc = (False, error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return suc



def new_app_devs(appkey):
    suc = (True, 'app_devs created')
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        CREATE TABLE dev_%s (
            name VARCHAR(30) NOT NULL,
            dev_id NUMERIC(3) PRIMARY KEY,
            app_key VARCHAR(80),
            description VARCHAR(200)
            FOREIGN KEY (app_key) REFERENCES applications(app_key)
        );
        """
        cur.execute(query, (appkey,))
        conn.commit()
        print('Dev table created')
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error creating app: ', error)
        suc = (False, error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return suc





def get_devs(appkey):
    res = []
    try:
        conn = psycopg2.connect('dbname=gateway')
        cur  = conn.cursor()
        query = """
        SELECT * FROM
            devs-%s
        """
        cur.execute(query, (appkey,))
        res = cur.fetchall()
    except (Exception, psycopg2.DatabaseError) as error:
        print('Error querying applications: ', error)
    finally:
        if (conn):
            cur.close()
            conn.close()
        
    return res





@server.route('/')
202
def index():
203
204
205
206
207
    if len(session['name']) > 0:
        apps = get_apps(session['name'].encode('utf-8'))
        print(apps)
        return render_template('index.html', apps=apps)

208
209
    return render_template('index.html')

210
211
212


@server.route('/signup', methods=['GET', 'POST'])
213
214
215
216
217
def signup():
    if request.method == 'GET':
        return render_template('signup.html')
    else: 
        username = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
218
        password = request.form['password'].encode('utf-8')
219
220
221
222
223
224
225
226

        if (username == '' or password == ''):
            feedback = 'Username or password fields cannot be empty'
            return render_template('signup.html', feedback=feedback)
        else:
            res, msg = new_user(username, password)
            if (not res):
                return render_template('signup.html', feedback=msg)
Vladislav Rykov's avatar
Vladislav Rykov committed
227
228
            else:
                session['name'] = username
229
        
Vladislav Rykov's avatar
Vladislav Rykov committed
230
                return redirect(url_for('index'))
231

232
233
234


@server.route('/login', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
235
def login():
Vladislav Rykov's avatar
Vladislav Rykov committed
236
237
238
239
    if request.method == 'GET':
        return render_template('login.html')
    else: 
        username = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
240
        password = request.form['password'].encode('utf-8')
Vladislav Rykov's avatar
Vladislav Rykov committed
241
242
243
244
245
246
247

        if (username == '' or password == ''):
            feedback = 'Username or password fields cannot be empty'
            return render_template('login.html', feedback=feedback)
        else:
            res, msg = chk_user(username, password)
            if (not res):
Vladislav Rykov's avatar
Vladislav Rykov committed
248
249
250
                return render_template('login.html', feedback=msg)
            else:
                session['name'] = username
Vladislav Rykov's avatar
Vladislav Rykov committed
251
        
Vladislav Rykov's avatar
Vladislav Rykov committed
252
253
254
                return redirect(url_for('index'))


255
256

@server.route('/logout')
Vladislav Rykov's avatar
Vladislav Rykov committed
257
258
259
def logout():
    session.clear()
    return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
260
261


262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

@server.route('/new-app')
def new_application():
    return render_template('new-app.html')



@server.route('/app', methods=['GET', 'POST'])
def app():
    if request.method == 'GET':
        app = get_app(request.form['appkey'])
        devs = get_devs(app[1])
        
        return render_template('app.html', app=app, devs=devs)
    else:
        if request.form['appname'] == '':
            error = 'Application name cannot be empty.'
            return render_template('new-app.html', feedback=error)
        else:
            res = new_app(request.form['appname'], request.form['appdesc'])
            rer = new_app_devs(request.form['appname'])
            if not res[0] or not rer[0]:
                return render_template('new-app.html', feedback=res[1]+'|'+rer[1])
            else:
                return redirect(url_for('index'))

288
289

if __name__ == '__main__':
290
291
292
293
    server.secret_key = 'sdjfklsjf^$654sd^#sPH'
    server.run(debug = True, host='0.0.0.0')