-
Notifications
You must be signed in to change notification settings - Fork 0
/
myphyle.py
executable file
·1678 lines (1595 loc) · 70.1 KB
/
myphyle.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# vim: set syntax=none nospell:
# ############################################## #
# title: myphyle 2019-01
# author: [email protected]
# purpose: flat file web based table management
# created: 2019-01-01
# requires:
# python2 (only because it is easier to install if used woth apache on ubuntu)
# wraphtml.py
# bottle
# sqlalchemy
# sqlite3 (or another SQL alternativei but you will need to change the app_URI)
# bcrypt
# Notes:
# var_d is a variable of type(dict)
# var_l is a variable of type(list)
# status: WIP as of 2019-01-10
# todo: password encryption - bcrypt
# - delete action
# - orderby
# - filterby
# - col sort button
# - improve pg_size - use a range instead of counting rows
# - reports design
# - fix/improve sql_filter
# ############################################# #
# ####### Imports ##### #
import os
import sys
import datetime
import re
# import sqlite3
from wraphtml import WrapHtml
import bottle
from bottle import run, get, post, request, route, redirect
from beaker.middleware import SessionMiddleware
import beaker
from bcrypt import hashpw, gensalt
from sqlalchemy import Column, Integer, String, create_engine, Table, MetaData, text, schema, inspect, select, and_, desc
from sqlalchemy.orm import sessionmaker
# from doctopt import docopt
# next lines used for debugging
sys.path.append("/home/geoffm/dev/python/gmodules/")
from dbug import dbug # noqa: E402
import webbrowser
# ######################## #
# ### [CONFIG OPTIONS] ### #
# ######################## #
# Where is all starts - the sqlite3 database will be named using __file__ plus ".db"
# app_name: probably no need to change this but you can - currently uses this filename
app_name = os.path.splitext(os.path.basename(__file__))[0]
# home_d: Home dictionary entry - optional - displays top left of nav bar if provided
home_d = {"Home": "/companionway.net"}
# organization: used in copyright displayed on bottom left
organization = "companionway"
# app_dir: this dir is important and must exist - Keep this away from the webserver DOCROOT
# - it is where the database for this app will reside
db_dir = "/var/tmp"
# app_URI: this is the completion of where the db will be and what sql dialect will be used
app_URI = "sqlite:///" + db_dir + "/" + app_name + ".db"
# session_dir: is a work dir where session data is kept - keep this away from your webserver DOCROOT
session_dir = "/var/tmp"
# foot_center: displays in the center of the footer - can be whatever you want, including nothing ie: ""
foot_center = "Enjoy your day!"
# input_size: WIP
input_size = 40
app_title = "myPhyle"
pg_size = 20
# ########################## #
# ### EOB CONFIG OPTIONS ### #
# ########################## #
# #### establish user session opts #### #
session_opts = {
'session.type': 'file',
'session.cookie_expires': 30000,
'session.data_dir': session_dir,
'session.auto': True
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
# session = bottle.request.environ.get('beaker.session')
# #### EOB establish user session opts #### #
# ####### establish sqlalchemy app defaults ##### #
app_engine = create_engine(app_URI, echo=True)
app_meta = MetaData(app_engine, reflect=True)
app_conn = app_engine.connect()
# app_Session = sessionmaker(bind=app_engine)
# app_session = app_Session()
# ####### EOB establish sqlalchemy defaults ##### #
# #### establish globals #### #
app_var = {}
app_var['msg']=""
# ### Sandbox1 #### #
# # Declare create table Example
# # table = Table('Example',meta,
# Column('id',Integer, primary_key=True),
# Column('name',String))
# # Now Create all tables - specifically Example declared above
# app_meta.create_all()
# for _t in app_meta.tables:
# print("Table: ", _t)
# Now drop the table Example
# app_meta.tables['Example'].drop()
# #### to start over ####
# MAKE SURE YOU WANT TO DO THIS!!!!
# dbug("STARTING OVER - droping 3 essential tables!!!")
# dbug("app_meta.tables: " + str(app_meta.tables) + " len(app_meta.tables): " + str(len(app_meta.tables)))
# if len(app_meta.tables) > 0:
# for table in app_meta.tables:
# if table=='app_users': app_meta.tables['app_users'].drop()
# if table=='app_views': app_meta.tables['app_views'].drop()
# if table=='app_fcontrol': app_meta.tables['app_fcontrol'].drop()
########################
# # declare essential table object
# views = Table('app_views', app_meta,
# Column('id', Integer, primary_key=True),
# Column('db_uri', String),
# Column('tablename', VARCHAR(50), NOT NULL),
# # etc
# )
# table_name = views.name
# print("table_name: " + table_name)
# cols_l = views.columns.keys()
# print("cols_l: " + str(cols_l))
# # or another example
# cols_l = app_meta.tables['app_views'].columns.keys()
# print("cols_l: " + str(cols_l))db_uri
# now recreate fcontrol table
# ### EOF Sandbox1 #### #
# ########### App Tables #####################
# Structure our three essential app tables
# these need app_meta = MetaData(app_engine)?
USERS = Table(
'app_users', app_meta,
Column('id', Integer, primary_key=True),
Column('viewname', String(50), nullable=False),
Column('username', String(50), nullable=False),
Column('password', String(250), nullable=False),
Column('role', String),
Column('note', String(250)),
Column('created', String(50)),
Column('modified', String(50)),
extend_existing=True,
)
VIEWS = Table(
'app_views', app_meta,
Column('id', Integer, primary_key=True),
Column('viewname', String(50), nullable=False),
Column('uri', String(50), nullable=False),
Column('tablename', String(250), nullable=False),
Column('row_cols', String(250)),
Column('detail_cols', String(250)),
Column('orderby', String(250)),
Column('filterby', String(250)),
Column('note', String(250)),
Column('created', String(50)),
Column('modified', String(50)),
extend_existing=True,
)
FCONTROL = Table(
'app_fcontrol', app_meta,
Column('id', Integer, primary_key=True),
Column('viewname', String(50), nullable=False),
Column('fieldname', String(250), nullable=False),
Column('calc', String(250)),
Column('mask', String(250)),
Column('note', String(250)),
Column('created', String, default=datetime.datetime.now),
Column('modified', String, onupdate=datetime.datetime.now),
extend_existing=True,
)
# ######## EOB App Tables ########### #
# ####### Functions ############# #
# ########################
def table_exists(tablename, action="", engine=app_engine, meta=app_meta):
# ####################
"""
docstring, untested
action: create|drop|populate|key(test for primary_key)
requires: from sqlalchemy import inspect, create_engine
engine = create_engine(uri, options)
"""
if tablename not in engine.table_names():
# dbug("Fould the table! [" + tablename + "]")
# else:
# dbug("No can find tablename [" + tablename + "]")
return False
# assuming table exists...
# meta = MetaData(engine, reflect=True)
# dbug("Begin table_exists(" + str(tablename) + ", " + action + ")")
inspection = inspect(engine)
# dbug("All inspect(engine) tables: " + str(inspection.get_table_names()))
for inspect_table in inspection.get_table_names():
# dbug("Checking table [" + str(inspect_table) + "] from inspect(engine)... ")
if inspect_table == tablename:
# dbug("Found " + tablename + " table in engine table_names")
if action == 'drop':
# dbug("Dropping [" + str(tablename) + "] as requested.")
tablename.drop(engine)
if action == 'populate':
# dbug("Populating [" + str(tablename) + "] as requested.")
do_populate(tablename)
if action == 'key':
table_o = meta.tables[tablename]
id_l = [key.name for key in inspect(table_o).primary_key]
try:
dbug("id_l: " + str(id_l[0]))
except Exception, e:
dbug("Primary key not found with error: " + str(e))
return False
return True
# else:
# dbug("inspect_table: " + inspect_table + " does not match supplied tablename: " + tablename)
if action == 'create':
dbug("Creating all tables")
meta.create_all()
return True
dbug("Did not find " + str(tablename) + " table")
return False
# ##########################
def do_populate(tablename):
# #####################
"""
docstring
untested
"""
dbug("Begin do_populate(" + tablename + ")")
new_records = []
my_table = app_meta.tables[tablename]
# VIEWS
if tablename == 'app_views':
new_records.append(VIEWS.insert().values(
viewname='app_views',
uri=app_URI,
tablename=VIEWS.name,
row_cols='id, viewname, uri, row_cols',
note='Do not delete this record'))
new_records.append(VIEWS.insert().values(
viewname="app_users",
uri=app_URI,
tablename="app_users",
row_cols="id, viewname, uri, row_cols",
note="Do not delete this record"))
new_records.append(VIEWS.insert().values(
viewname="app_fcontrol",
uri=app_URI,
tablename="app_fcontrol",
row_cols="id, viewname, uri, row_cols",
note="Do not delete this record"))
# USERS
if tablename == 'app_users':
new_records.append(USERS.insert().values(
viewname="app_views",
username="admin",
password="plaintext",
role="admin",
note="Do not delete this record"))
new_records.append(USERS.insert().values(
viewname="app_users",
username="admin",
password="plaintext",
role="admin",
note="Do not delete this record"))
new_records.append(USERS.insert().values(
viewname="app_fcontrol",
username="admin",
password="plaintext",
role="admin",
note="Do not delete this record"))
# FCONTROL
if tablename == 'app_fcontrol':
new_records.append(FCONTROL.insert().values(
viewname='app_views',
fieldname='modified',
calc='SELECT NOW()',
note='Example of using fcontrol calc'))
# Execute each insert
# now add them via db_session
# WIP2 #
# ins_stmt = VIEWS.insert().values(viewname='tst',tablename='tst',uri='uri')
# result = conn.execute(ins_stmt)
# dbug("Just tried conn.execute(" + ins_stmt + ")")
for new_record in new_records:
dbug("Attempting to add: " +str( new_record))
result = app_conn.execute(new_record)
# view_session.add(new_record)
# view_session.commit()
# or ??
# view_session.flush()
# ###################
def tables_l(engine=app_engine):
# ###############
"""
input: engine # eg engine = create_engine('sqlite:////myfile.db') # , echo=True)
return: table list from the engine db
requires: from sqlalchemy import inspect
purpose: quick way to get a list of tables
"""
inspector = inspect(engine)
tables_l = inspector.get_table_names()
return tables_l
# EOB def tables_l(engine):
# ##################
def cols_l(table_o, engine=app_engine):
# ##############
"""
unusable????
input: meta table obj # eg meta = MetaData(engine); table = meta['mytable'] or mytable = Table('mytable', meta, ...;
return: list of col names
"""
# tobe tested
# inspector = inspect(engine)
# inspector.get_columns(tablename)
# or
# cols_l = [col.name for col in table_o.columns]
# or
cols_l = table_o.columns.keys()
return cols_l
# EOB def cols_l(table_o):
# ################################
def col_exists(table_o, col_name):
# ############################
"""
docstring
"""
cols_l = cols_l(table_o)
if col_name in cols_l:
return True
return False
# EOB def col_exists(table_o, col_name):
# ##################
def form_d(request):
# ##############
"""
input: is form request obj
return: is a dictionary pairing of form_name: form_value
note: lambdas to avoid errors in evaluating bottle.request.*
use:
form_data = form_d(request)
my_var = form_data['my_var']
"""
_dicts = [
lambda: request.json,
lambda: request.forms,
lambda: request.query,
lambda: request.files,
]
form_d = {}
for dict in _dicts:
try:
dict = dict()
except KeyError:
continue
if dict is not None and hasattr(dict, 'items'):
for key, val in dict.items():
form_d[key] = val
return form_d
# EOB def form_d(request):
# ############################################
def check_login(viewname, username, password):
# ########################################
"""
docstring
WIP
"""
dbug("Begin check_login(" + viewname + ", " + username + ", " + password + ")")
session = bottle.request.environ.get('beaker.session')
# dbug("session: " + str(session) + " we are starting check_login - we are nulling out session info")
dbug("session: " + str(session) + " we are starting check_login")
# session['username'] = ""
# session['viewname'] = ""
if session.has_key('username') and session.has_key('viewname'):
username = session['username']
viewname = session['viewname']
dbug("session already established with " + session['username'] + " for " + session['viewname'])
app_var['msg'] += "<br>You have an exisiting session with username: " + username + " and viewname: " + viewname
# ### this suggests that a previous authentication was established so...
return True
#else:
# # username = ""
# # viewname = ""
# dbug("We will now go check the database ... ")
# # dbug("... because [session] username [" + session['username'] + "] or viewname [" + session['viewname'] + "] is a problem")
# # assuming session info failed...
# # app_var['msg'] += "FAILURE error: with session username: " + username + " and session viewname: " + viewname
# # return False
# continue user check against app_users table
# ###
# ### methodology ###
# ### if username and viewname already exist
# ### then we have an active authenticated session - we should return True
# ### WIP need more here
# ###
users = app_meta.tables['app_users']
views = app_meta.tables['app_views']
dbug("got this far with username=" + username + " and viewname=" + viewname)
sel = select([users]).where(and_(users.c.username==username, users.c.viewname==viewname))
try:
res = app_conn.execute(sel)
cnt = row_count(res)
dbug("cnt: " + str(cnt))
# for row in res:
# dbug("row: " + str(row))
if cnt == 0:
dbug("No matching rows found in users table for user: " + username + " viewname: " + viewname)
app_var['msg'] += "<br>No matching rows found in users table for user: " + username + " viewname: " + viewname
except Exception, e:
dbug("FAILURE: error: [" + str(e) + "] No matching record found in users table for: " + username + " viewname: " + viewname)
res = app_conn.execute(sel) # you have to reset the result each time you need it
for row in res:
dbug("row: " + str(row))
if row['viewname'] == viewname and row['username'] == username:
# this double checks that the session username and session viewname exist in the users database
app_var['msg'] += "<br>There is a user entry [" + username + "] for the viewname [" + viewname + "] in the users table"
# dbug("just for grins hashed row['password']: " + hashpw(row['password'].encode('utf-8'), gensalt()))
if not row['password'].encode('utf-8').startswith("$2b$"):
dbug("Does NOT look like a hashed pw")
dbug("this must be a plain-text password")
# so now we need to hash it and save it WIP
hashed_password = hashpw(row['password'].encode('utf-8'), gensalt())
vals_d = {'password': hashed_password}
action_stmt = USERS.update().values(vals_d).where(and_(USERS.c.viewname == viewname, USERS.c.username == username))
result = app_conn.execute(action_stmt)
hashed_password = row['password'].encode('utf-8')
# sel was established just before the try: above
res = app_conn.execute(sel) # you have to reset the result each time you need it
else:
hashed_password = row['password'].encode('utf-8')
# dbug("hashed_password: " + hashed_password)
if row['password'] == password or hashpw(password, hashed_password) == hashed_password: # this is TEMPORARY AND NEEDS TO BE REMOVED! WIP
app_var['msg'] += "<br>The password matches"
# if row['viewname'] == viewname or row['username'] == username and hashpw(password,gensalt()) == row['password']:
# now make sure there is an entry in the app_views table for this viewname
# ### checking views table now (app_views) ###
dbug("Checking for viewname [" + viewname + "] in the views table")
try:
sel = select([views]).where(views.c.viewname==viewname)
result = app_conn.execute(sel)
cnt = row_count(result)
dbug("cnt: " + str(cnt))
if cnt == 0:
dbug("No records found ( cnt: " + str(cnt) + ") to match in viewname for: " + viewname)
app_var['msg'] += ("<p>No records found in views table for viewname: " + viewname + "</p>")
else:
app_var['msg'] += "<p>There is a viewname [" + viewname + "] record in the views table</p>"
app_var['msg'] += "<p>Successful login authentication</p>"
dbug("PASSED check_login() " )
# ############################
# ### PASSED check_login() ###
# ############################
return True
except Exception, e:
dbug("oops maybe no records matched views.viewname " + str(e))
app_var['msg'] += "<p>No record found in the views table for: " + viewname + "</p>"
return False
else:
app_var['msg'] += "<br>Password failed..."
# this is strickly for debugging
dbug("Password FAILED")
dbug("hmmm: row[viewname]=" + row['viewname'] + " viewname=" + viewname)
dbug("hmmm: row[username]=" + row['username'] + " username=" + username)
dbug("hmmm: row[password]=" + row['password'] + " password=" + password)
app_var['msg'] += "<br>Login check failed for username: " + username + " and viewname: " + viewname
dbug("returning false")
return False
# EOB def check_login(viewname, username, password):
# ########################
def row_d(cols_l, result):
# ####################
"""
docstring, unusable???
input: result = conn.execute(sel)
"""
row_d = [dict(zip(cols_l,row)) for row in result]
return row_d
# EOB def row_d(cols_l, result):
# ####################
def row_count(result):
# ################
"""
docstring
"""
# dbug("Begin row_count(result)")
rowcnt = 0
for record in result:
rowcnt += 1
# dbug("record: " + str(record))
# dbug("End row_count(" + str(result) + ") with rowcnt: " + str(rowcnt))
return rowcnt
# EOB def row_count(result) #
# ######### EOB Functions ########### #
# #### Sandbox2 #### #
# print("app_meta.tables.keys(): " + str(app_meta.tables.keys()))
# sys.exit()
# #### sanity check - make sure essential tables exist and are populated ### #
# if table is missing - create it and populate it
for table in app_meta.tables:
# print("DEBUG: checking for table: " + table)
if not table_exists(table):
# print("DEBUG: [" + table + "] table not found, creating and populating it...")
table_exists(table, 'create')
# ### #
# check to see if there are no records - populate the table
# dbug("Checking record number in table: " + table)
sel = VIEWS.select()
sel = app_meta.tables[table].select()
result = app_conn.execute(sel)
# dbug("attempted app_conn")
cnt = row_count(result)
if cnt == 0:
# dbug("cnt: " + str(cnt))
table_exists(table,'populate')
# else:
# dbug("We found a match for app_views and it has at least one record... continuing...")
# explore "text" module using from sqlalchemy import text
# data = ( { "id": 1, "title": "The Hobbit", "primary_author": "Tolkien" },
# { "id": 2, "title": "The Silmarillion", "primary_author": "Tolkien" },
# )
# statement = text("""INSERT INTO book(id, title, primary_author) VALUES(:id, :title, :primary_author)""")
# for line in data:
# con.execute(statement, **line)
# or use execute method
# with engine.connect() as con:
# rs = con.execute('SELECT * FROM book')
# for row in rs:
# print row
#
# ### EOB sanity check ### #
# views = app_meta.tables['app_views']
# cols_l = cols_l(views)
# # sel = selected_row = select([views]).where('viewname'=='app_views')
# sel = select([views]).where(views.c.viewname=='app_views')
# result = app_conn.execute(sel)
# print("row_d: " + str(row_d(cols_l, result)))
# #### EOB Sandbox2 #### #
def local_content(content):
"""
experimental
"""
local.content = content.replace("<br>","\n")
print("="*80)
print(local_content)
print("="*80)
# ############################## #
# ########### routes ########### #
# ############################## #
# ##########
@route('/sess')
def sess():
s = bottle.request.environ.get('beaker.session')
s['test'] = 'this string came from the session'
s.save()
bottle.redirect('/sess/out')
@route("/sess/out")
def sess_out():
s = bottle.request.environ.get('beaker.session')
return s['test']
@route('/')
def home():
# #####
"""
docstring
"""
session = bottle.request.environ.get('beaker.session')
print("session: " + str(session))
if not check_login('', '', ''):
redirect('/login')
session = bottle.request.environ.get('beaker.session')
viewname = session['viewname']
username = session['username']
redirect('/db/rows/' + viewname)
# ###############
@get('/login') # or @route('/login')
def login():
# ##########
"""
docstring
# global app_vars
# print("entering get(/login)...")
"""
# global LOCAL_ONLY
#if LOCAL_ONLY:
# global session
#else:
session = bottle.request.environ.get('beaker.session')
dbug("session: " + str(session))
if session.has_key('viewname'):
dbug("Found session viewname: " + session['viewname'])
viewname = session['viewname']
else:
dbug("Did not find a session[viewname]... ")
viewname = 'viewname'
if session.has_key('username'):
dbug("Found session viewname: " + session['viewname'])
username = session['username']
else:
username = ''
dbug("Near begining of /login with: viewname: " + viewname + " username: " + username)
app_var['msg'] = "" # clear/reset msg
# ### grab all the viewnames ### #
sel = VIEWS.select()
result = app_conn.execute(sel)
viewnames = []
for row in result:
viewnames.append(row['viewname'])
# ### grab all the usernames ### #
sel = USERS.select()
result = app_conn.execute(sel)
usernames = []
for row in result:
usernames.append(row['username'])
# ### start building the login screen ### #
content = "<center>"
content += '''
<!--
<div style="border: solid #009090; width: 300px; padding: 25px; margin: 25px;">
<div style="background-color: lightgrey; border: solid #0090F0; width: 300px; padding: 25px; margin: 25px;">
-->
<h2>Login</h2>
<h3>[or change view]</h3>
<!--
</div>
-->
<form action="login" method="POST" name="login">
<div style="border: solid #0090F0; width: 300px; padding: 5px 25px 5px 25px; margin: 25px;">
Please select your viewname:
<br>
'''
# select viewname from oviewnames #
content += '<select name="viewname" style="width: 200px;">\n'
for view in viewnames:
content += '<option value="' + view + '">' + view + '</option>\n'
content += '</select>\n'
# content += '<input type="text" name="viewname" value=' + viewname + '>\n'
# start username and password input screen #
content += '''
<br>
</div>
<br>\n
<div style="border: solid #0090F0; width: 300px; padding: 5px 25px 5px 25px; margin: 25px;">\n
Please fill-in your credentials:
<br>\n
'''
# select username from usernames #
content += '<select name="username" style="width: 200px;">\n'
for user in usernames:
content += '<option value="' + user + '">' + user + '</option>\n'
content += '</select>\n'
# content += '<input type="text" name="username" value=' + username + '>'
content += '''
<!-- <br><br> -->
<input type="password" name="password">
<br/>
</div>
<br/>
<button type="submit" > OK </button>
<button type="button" class="close"> Cancel </button>
</form>
<br />
'''
if app_var['msg'] != '':
content += "<br><div name=msg>Message: [" + str(app_var['msg']) + "]</div>"
content += "</center>\n"
# if argv[1] == '-p':
# local_content(content)
session.save()
title = app_title
html = WrapHtml(content=content, title=title, org="companionway", center="Enjoy!")
return html.render()
# return content
# ################
@post('/login') # or @route('/login', method='POST')
def do_login():
# ###########
"""
docstring
"""
content = "<center>"
title = __file__
viewname = request.forms.get('viewname')
username = request.forms.get('username')
password = request.forms.get('password')
session = bottle.request.environ.get('beaker.session')
if check_login(viewname, username, password):
session['username'] = username
session['viewname'] = viewname
dbug("session username has been set to : " + session['username'] + " and session viewname has been set to: " + session['viewname'])
session.save()
# content += "<p>Your login [" + username + "] for viewname [" + viewname + "] was correct.</p>"
# content += '<a href="/db/rows/' + viewname + '">View rows for viewname: ' + viewname + '</a>'
redirect('/db/rows/' + viewname)
else:
content += "<p>Login failed.</p>"
if app_var['msg'] != '':
content += "<div name=msg>Messages: " + app_var['msg'] + "</div>"
content += "<button><a href='/login'>Return to login page.</a></button>"
content += "<button><a , renderhref='/logout'>Goto to logout page.</a></button>"
content += "</center>"
# html = WrapHtml(content=content, title=title, right="Enjoy!", nav_d=nav_d)
html = WrapHtml(content=content, title=title, right="Enjoy!")
return html.render()
# ##########
@route('/logout')
def logout():
"""
WIP docstring
"""
user_session = bottle.request.environ.get('beaker.session')
if user_session['username']:
username = user_session['username']
dbug(" user_session[username]: " + user_session['username'])
# empty the session username and viewname
username = user_session['username'] = ''
viewname = user_session['viewname'] = ''
dbug(" user_session[username]: " + username)
content = "<p>Username: " + username + " has been logged out</p>"
content += "<p><button><a href=/login>Login Page</a></button>"
content += "<div name=msg>Message: " + app_var['msg'] + "</div>"
html = WrapHtml(content=content, title=title, right="Enjoy!")
return html.render()
# return content
# #######################################
@route('/db/rows/<viewname>', method='GET')
@route('/db/rows/<viewname>', method='POST')
def db_rows(viewname):
# ###################################
"""
input: viewname
output: content = table of viewname with action links
WIP !!
WIP make sure we are authorized?
"""
# dbug("Begin /db/rows/" + viewname )
session = bottle.request.environ.get('beaker.session')
# dbug("session: " + str(session))
title = "Display rows for table: " + viewname
form_data = form_d(request)
# dbug("form_data: " + str(form_data))
# ######### filterby ########## #
# boil this down to filterby
if form_data.has_key('fltr_col'):
fltr_col = form_data['fltr_col']
else:
fltr_col = "none"
#dbug("fltr_col: " + fltr_col)
if form_data.has_key('fltr_str'):
fltr_str = form_data['fltr_str']
filterby = " WHERE " + fltr_col + " LIKE '%" + fltr_str + "%' "
else:
fltr_str = "" # only here for dbug below
filterby = ""
dbug("fltr_col: " + str(fltr_col) + ' fltr_str: ' + str(fltr_str) + ' filterby: ' + filterby)
# ######### orderby ########## #
if form_data.has_key('orderby'):
orderby = form_data['orderby']
orderby = " ORDER BY " + orderby.replace("_"," ")
else:
orderby = ""
# dbug("orderby: " + orderby)
# ### start content ### #
content = "<center>"
# user session check
if session.has_key('username') and session.has_key('viewname'):
username = session['username']
views = app_meta.tables['app_views']
else:
content += "<br>No authorized session info for username and tablename"
content += "<br><a href=/login>Return to Login (change view)</a>"
html = WrapHtml(content, title=title)
return html.render()
users = app_meta.tables['app_users']
if viewname != session['viewname']:
# dbug("Viewname is not authorized")
redirect('/login')
else:
# dbug("Supplied viewname [" + viewname + "] is authorized as it matches the user session viewname [" + session['viewname'] + "]")
viewname = session['viewname']
authorized_table = "none"
# dbug("Attempting to get actual tablename from views table")
# sel = select([views]).where(views.c.viewname==viewname)
sel = select([VIEWS]).where(VIEWS.c.viewname==viewname)
result = app_conn.execute(sel)
# dbug("result: " + str(result))
# this all needs work WIP !!!
for row in result:
# dbug("row: " + str(row))
if row['viewname']==viewname:
# dbug("YES")
app_var['msg'] += "Found the viewname [" + viewname + "] in the views table"
else:
app_var['msg'] = "No records found for viewname: " + viewname + " in the views table."
redirect('/login')
# dbug("2nd time ...Authorized_table: " + authorized_table)
## WIP check this next one - it is experimental
# dbug("## WIP check this next one - it is experimental")
# dbug("----------- authorized_table -----------")
# dbug("authorized_table: " + authorized_table)
# fails: (only does first filter) sel = select([users]).where(users.c.username==username and users.c.viewname==viewname)
sel = select([users]).where(and_(users.c.username==username, users.c.viewname==viewname))
result = app_conn.execute(sel)
# dbug("so row_count = " + str(row_count(result)))
# dbug("result SHOULD BE: one record with users.c.username=" + username + " users.c.viewname=" + viewname)
for row in result:
# dbug("Double checkng authorization for this viewname: " + viewname + " is autorized")
# dbug("for row in result - row: " + str(row))
# dbug("row[viewname]: " + row['viewname'] + " and row[username]: " + row['username'])
# dbug("viewname: " + viewname + " and username: " + username)
# if row['viewname'] == viewname:
# dbug("well at least viewname matches")
# dbug("session[viewname]: " + session['viewname'])
# So grab pg_size while we have it
# pg_size = row['pg_size']
# else:
# dbug("viewname: " + viewname + " but row[viewname]: " + row['viewname'])
# dbug("session[viewname]: " + session['viewname'])
# if row['username'] == username:
# dbug("well at least username matches")
# dbug("session[username]: " + session['username'])
if row['viewname'] == viewname and row['username'] == username:
# dbug("viewname and username passed check out OK")
break
else:
app_var['msg'] += "We have a problem as viewname: " + viewname + " and username: " + username + " fail"
# dbug("sel: " + str(sel))
content += "<br><div name=msg>Message: " + str(app_var['msg']) + "</div>"
content += "<a href=/login>Return to login</a>"
return content
# redirect("/login")
# EOB user session check
# ####
# #### set view uri and table ### #
sel = select([views]).where(views.c.viewname==viewname)
result = app_conn.execute(sel) # hmmm, you have to re-run this after each manipulation of the result
row = result.fetchone()
# dbug("row: " + str(row) + " and row_cnt: " + str(row_count(result)))
view_URI = row['uri']
view_TABLE = row['tablename']
# dbug("view_URI: "+ view_URI + " view_TABLE: " + view_TABLE)
# now open the URI
try:
# view_engine = create_engine(view_URI, convert_unicode=True, echo=True)
view_engine = create_engine(view_URI, convert_unicode=True, echo=False)
view_meta = MetaData(view_engine)
view_meta.reflect()
view_conn = view_engine.connect()
except Exception, e:
# dbug("Exeception: " + str(e))
content += "<br>Please double check the URI and declared tablename for this view [" + viewname + "]"
content += "<br>Failed to connect using URI [" + view_URI + "] for viewname [" + viewname + "]"
content += "<br>Received error: " + str(e) + "</p>"
content += "<br><a href=/login>Return to Login (change view)</a>"
html = WrapHtml(content)
return html.render()
# view_Session = sessionmaker(bind=app_engine)
# view_session = view_Session()
# ###
table = view_meta.tables[view_TABLE] # this should be table_o
# lets make sure it exists and has a key
if table.name in view_engine.table_names():
# dbug("We found the table [" + table.name + "] in the database [" + view_URI + "]")
id_l = [key.name for key in inspect(table).primary_key]
try:
primary_key = str(id_l[0])
# dbug("id_l: " + str(id_l))
# dbug("primary_key: " + primary_key)
except Exception, e:
# dbug("Primary key failed... error: " + str(e))
app_var['msg'] += "<br>Failed to find primary key in table [" + table.name + "]"
content += "<br>Failed to find primary key in table [" + table.name + "]"
content += '<br><a href="/login">Return to login</a>'
# dbug("title: " + title)
nav_d = {"Logout": "/logout", "Login (change view)": "/login", "Admin ToDo": "/admin" }
html = WrapHtml(content=content, title=title, org=organization, center=foot_center, nav_d=nav_d)
return html.render()
else:
app_var['msg'] += '<br>Failed to find table [' + table.name + '] in database uri [' + view_URI + ']'
content += '<br><a href="/login">Return to login</a>'
html = WrapHtml(content=content, title=title, org=organization, center=foot_center, nav_d=nav_d)
return html.render()
# #### EOB set view uri and table ### #
cols_l = table.columns.keys()
sel = select([table])
result = view_conn.execute(sel)
rows_l = [dict(zip(cols_l,row)) for row in result]
# start content - add heading
content = "<center>\n"
content += '<div style="float: left;">User: ' + username + '</div>'
content += '<div style="float: right;"> Viewname: ' + viewname + ' Tablename: ' + table.name + '</div><br>\n'
content += '<br>'
content += '<div style="float: left;"><button><a href="/db/add/record">Add a new record</a></button><br></div>'
# ### build the SQL query ### #
content += '<div style="float: right;">'
# dbug("filterby: " + filterby + " orderby: " + orderby)
sql = "SELECT * FROM " + table.name
if filterby != "":
sql = sql + filterby
if orderby != "":
sql = sql + orderby
# dbug("sql: [" + sql + "] fltr_col: " + fltr_col + " filterby: " + filterby)
# ### start the form for filterby ### #
content += '<form name="filterby" action="/db/rows/' + viewname + '" method="POST">'
content += 'Quick Filter: '
content += '<select name="fltr_col" type"text" style="width: 100px;">' + '\n'
for item in cols_l:
if fltr_col == item:
# dbug("fltr_col: " + fltr_col + " item " + item)
content += '<option value="' + item + '" selected="selected">' + str(item) + '</option>' + '\n'
else:
# dbug("fltr_col: " + fltr_col + " item " + item)
content += '<option value="' + item + '">' + str(item) + '</option>' + '\n'
content += '</select>'
content += ' contains: '
content += '<input type="text" name="fltr_str" value="' + fltr_str + '" size="30">'
content += '<input value="Submit" type="submit" />'
content += '</form>'
content += '</div>'
# ### EOB form for filterby ### #
content += '<br> <br>'
# ### start table
cols_l = table.columns.keys()
# ### build table or rowa ### #
content += "<table border=1>\n"
content += "<tr>"
# table header cells
for col in cols_l:
# ### orderby links ### #
# check for and build orderby for each col
cur_orderby = "" # set it to "" because this col has no order
chg_orderby = "_ASC" # and it has no chg order either
if form_data.has_key('orderby'):
rcvd_orderby = form_data['orderby']
# got a request to change orderby so lets do that and place an indicator that is is currently active with cur_orderby
if col + '_ASC' == rcvd_orderby:
# dbug("Found _ASC in: " + rcvd_orderby + " sel should now include order " + col + " ASC")
cur_orderby = " (A)"
chg_orderby = "_DESC"
if col + '_DESC' == rcvd_orderby:
# dbug("Found _DESC in: " + rcvd_orderby + " sel should now include order " + col + " DESC")
cur_orderby = " (D)"