-
Notifications
You must be signed in to change notification settings - Fork 85
/
simple_webapp_using_sqlite.py
executable file
·222 lines (168 loc) · 5.74 KB
/
simple_webapp_using_sqlite.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
#!/usr/bin/env python
#
# Copyright (C) 2013 Federico Ceratto and others, see AUTHORS file.
# Released under GPLv3+ license, see LICENSE.txt
#
# Cork example web application
#
# The following users are already available:
# admin/admin, demo/demo
import bottle
from beaker.middleware import SessionMiddleware
from cork import Cork
from cork.backends import SQLiteBackend
import logging
logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG)
log = logging.getLogger(__name__)
bottle.debug(True)
def populate_backend():
b = SQLiteBackend('example.db', initialize=True)
b.connection.executescript("""
INSERT INTO users (username, email_addr, desc, role, hash, creation_date) VALUES
(
'admin',
'admin@localhost.local',
'admin test user',
'admin',
'cLzRnzbEwehP6ZzTREh3A4MXJyNo+TV8Hs4//EEbPbiDoo+dmNg22f2RJC282aSwgyWv/O6s3h42qrA6iHx8yfw=',
'2012-10-28 20:50:26.286723'
);
INSERT INTO roles (role, level) VALUES ('special', 200);
INSERT INTO roles (role, level) VALUES ('admin', 100);
INSERT INTO roles (role, level) VALUES ('editor', 60);
INSERT INTO roles (role, level) VALUES ('user', 50);
""")
return b
b = populate_backend()
aaa = Cork(backend=b, email_sender='federico.ceratto@gmail.com', smtp_url='smtp://smtp.magnet.ie')
app = bottle.app()
session_opts = {
'session.cookie_expires': True,
'session.encrypt_key': 'please use a random key and keep it secret!',
'session.httponly': True,
'session.timeout': 3600 * 24, # 1 day
'session.type': 'cookie',
'session.validate_key': True,
}
app = SessionMiddleware(app, session_opts)
# # Bottle methods # #
def postd():
return bottle.request.forms
def post_get(name, default=''):
return bottle.request.POST.get(name, default).strip()
@bottle.post('/login')
def login():
"""Authenticate users"""
username = post_get('username')
password = post_get('password')
aaa.login(username, password, success_redirect='/', fail_redirect='/login')
@bottle.route('/user_is_anonymous')
def user_is_anonymous():
if aaa.user_is_anonymous:
return 'True'
return 'False'
@bottle.route('/logout')
def logout():
aaa.logout(success_redirect='/login')
@bottle.post('/register')
def register():
"""Send out registration email"""
aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
return 'Please check your mailbox.'
@bottle.route('/validate_registration/:registration_code')
def validate_registration(registration_code):
"""Validate registration, create user account"""
aaa.validate_registration(registration_code)
return 'Thanks. <a href="/login">Go to login</a>'
@bottle.post('/reset_password')
def send_password_reset_email():
"""Send out password reset email"""
aaa.send_password_reset_email(
username=post_get('username'),
email_addr=post_get('email_address')
)
return 'Please check your mailbox.'
@bottle.route('/change_password/:reset_code')
@bottle.view('password_change_form')
def change_password(reset_code):
"""Show password change form"""
return dict(reset_code=reset_code)
@bottle.post('/change_password')
def change_password():
"""Change password"""
aaa.reset_password(post_get('reset_code'), post_get('password'))
return 'Thanks. <a href="/login">Go to login</a>'
@bottle.route('/')
def index():
"""Only authenticated users can see this"""
aaa.require(fail_redirect='/login')
return 'Welcome! <a href="/admin">Admin page</a> <a href="/logout">Logout</a>'
@bottle.route('/restricted_download')
def restricted_download():
"""Only authenticated users can download this file"""
aaa.require(fail_redirect='/login')
return bottle.static_file('static_file', root='.')
@bottle.route('/my_role')
def show_current_user_role():
"""Show current user role"""
session = bottle.request.environ.get('beaker.session')
print "Session from simple_webapp", repr(session)
aaa.require(fail_redirect='/login')
return aaa.current_user.role
# Admin-only pages
@bottle.route('/admin')
@bottle.view('admin_page')
def admin():
"""Only admin users can see this"""
aaa.require(role='admin', fail_redirect='/sorry_page')
return dict(
current_user=aaa.current_user,
users=aaa.list_users(),
roles=aaa.list_roles()
)
@bottle.post('/create_user')
def create_user():
try:
aaa.create_user(postd().username, postd().role, postd().password)
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
@bottle.post('/delete_user')
def delete_user():
try:
aaa.delete_user(post_get('username'))
return dict(ok=True, msg='')
except Exception, e:
print repr(e)
return dict(ok=False, msg=e.message)
@bottle.post('/create_role')
def create_role():
try:
aaa.create_role(post_get('role'), post_get('level'))
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
@bottle.post('/delete_role')
def delete_role():
try:
aaa.delete_role(post_get('role'))
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
# Static pages
@bottle.route('/login')
@bottle.view('login_form')
def login_form():
"""Serve login form"""
return {}
@bottle.route('/sorry_page')
def sorry_page():
"""Serve sorry page"""
return '<p>Sorry, you are not authorized to perform this action</p>'
# # Web application main # #
def main():
# Start the Bottle webapp
bottle.debug(True)
bottle.run(app=app, quiet=False, reloader=False)
if __name__ == "__main__":
main()