server.py 6.18 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
import misc
Vladislav Rykov's avatar
Vladislav Rykov committed
5
import dao.user.user as ud
6
7
8
9
10
11


APP_KEY_LEN = 8


server = Flask(__name__, template_folder='templates/')
Vladislav Rykov's avatar
Vladislav Rykov committed
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
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 = """
Vladislav Rykov's avatar
Vladislav Rykov committed
95
        CREATE TABLE devs_%s (
96
97
98
99
100
101
102
103
104
            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()
Vladislav Rykov's avatar
Vladislav Rykov committed
105
        print('Devs table created')
106
    except (Exception, psycopg2.DatabaseError) as error:
Vladislav Rykov's avatar
Vladislav Rykov committed
107
        print('Error creating devs table: ', error)
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
        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('/')
145
def index():
Vladislav Rykov's avatar
Vladislav Rykov committed
146
    if 'name' in session and len(session['name']) > 0:
147
        apps = get_apps(session['name'].encode('utf-8'))
Vladislav Rykov's avatar
Vladislav Rykov committed
148
        print('apps: ', apps)
149
150
        return render_template('index.html', apps=apps)

151
152
    return render_template('index.html')

153
154
155


@server.route('/signup', methods=['GET', 'POST'])
156
157
158
159
160
def signup():
    if request.method == 'GET':
        return render_template('signup.html')
    else: 
        username = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
161
        password = request.form['password'].encode('utf-8')
162
163
164
165
166

        if (username == '' or password == ''):
            feedback = 'Username or password fields cannot be empty'
            return render_template('signup.html', feedback=feedback)
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
167
168
169
170
            uh = ud.UserDao()
            res = uh.create(username, password)
            if (not res[0]):
                return render_template('signup.html', feedback=res[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
171
172
            else:
                session['name'] = username
173
        
Vladislav Rykov's avatar
Vladislav Rykov committed
174
                return redirect(url_for('index'))
175

176
177
178


@server.route('/login', methods=['GET', 'POST'])
Vladislav Rykov's avatar
Vladislav Rykov committed
179
def login():
Vladislav Rykov's avatar
Vladislav Rykov committed
180
181
182
183
    if request.method == 'GET':
        return render_template('login.html')
    else: 
        username = request.form['username']
Vladislav Rykov's avatar
Vladislav Rykov committed
184
        password = request.form['password'].encode('utf-8')
Vladislav Rykov's avatar
Vladislav Rykov committed
185
186
187
188
189

        if (username == '' or password == ''):
            feedback = 'Username or password fields cannot be empty'
            return render_template('login.html', feedback=feedback)
        else:
Vladislav Rykov's avatar
Vladislav Rykov committed
190
191
192
193
            uh = ud.UserDao()
            res = uh.get(username, password)
            if (not res[0]):
                return render_template('login.html', feedback=msg[1])
Vladislav Rykov's avatar
Vladislav Rykov committed
194
195
            else:
                session['name'] = username
Vladislav Rykov's avatar
Vladislav Rykov committed
196
        
Vladislav Rykov's avatar
Vladislav Rykov committed
197
198
199
                return redirect(url_for('index'))


200
201

@server.route('/logout')
Vladislav Rykov's avatar
Vladislav Rykov committed
202
203
204
def logout():
    session.clear()
    return redirect(url_for('index'))
Vladislav Rykov's avatar
Vladislav Rykov committed
205
206


207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

@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'])
Vladislav Rykov's avatar
Vladislav Rykov committed
227
228
229
230
231
232
233
234
            if not res[0]:
                return render_template('new-app.html', feedback=res[1])

            res = new_app_devs(request.form['appname'])
            if not res[0]:
                rm_app(request.form['appname'])
                return render_template('new-app.html', feedback=res[1])
            
235
            if not res[0] or not rer[0]:
Vladislav Rykov's avatar
Vladislav Rykov committed
236
                return render_template('new-app.html', feedback=str(res[1])+'|'+str(rer[1]))
237
238
239
            else:
                return redirect(url_for('index'))

240
241

if __name__ == '__main__':
242
243
244
245
    server.secret_key = 'sdjfklsjf^$654sd^#sPH'
    server.run(debug = True, host='0.0.0.0')