]> git.datanom.net - pwp.git/blob - app/views.py
initial commit
[pwp.git] / app / views.py
1 from flask import render_template, flash, redirect, session, url_for, request, g, abort
2 from flask_login import login_user, logout_user, current_user, login_required
3 from app import app, lm, tools
4 from .forms import LoginForm, RegisterForm, UpdateForm, PwForm, SearchForm, DeleteForm, PortfolioForm, AlbumForm
5 from .models import User, Portfolio, Album, AccessRight, Role, MyAnonymous
6 from werkzeug.security import generate_password_hash, check_password_hash
7 import datetime, os
8 from config import SESSION_TIMEOUT
9
10 class DBException(Exception):
11 pass
12
13 @app.before_request
14 def before_request():
15 session.permanent = True
16 app.permanent_session_lifetime = datetime.timedelta(minutes=SESSION_TIMEOUT)
17 session.modified = True
18 g.user = current_user
19 g.searchForm = SearchForm(prefix="sf")
20 g.deleteform = DeleteForm(prefix="df")
21
22 @lm.user_loader
23 def load_user(id):
24 return User.query.get(int(id))
25
26 @app.route('/')
27 @app.route('/index')
28 def index():
29 user = g.user
30 return render_template('index.html',
31 title='Home',
32 user=user)
33
34 @app.route('/login', methods=['GET', 'POST'])
35 def login():
36 if g.user is not None and g.user.is_authenticated:
37 return redirect(request.referrer)#redirect(url_for('index'))
38 form = LoginForm()
39 if form.validate_on_submit():
40 user = User.query.filter_by(username=form.username.data).first()
41 if user is None:
42 flash('Unknown username. Please try again or register.')
43 else:
44 app.logger.info("db-pwd: %s form-pwd: %s" % (user.password, form.password.data))
45 if check_password_hash(user.password, form.password.data):
46 app.logger.info("Login: %s" % user)
47 login_user(user, remember=False)
48 next = request.args.get('next')
49 if next is not None:
50 if not tools.is_safe_url(next):
51 return abort(400)
52 req = next.rsplit('/', 1)
53 app.logger.info("%s:%s" % (req[0], req[1]))
54 if req[0] == '/user' and req[1] != user.name:
55 next = "%s/%s" % (req[0], user.username)
56 app.logger.info("Login: %s next: %s" % (user, next))
57 return redirect(next or url_for('index'))
58 else:
59 flash('Username or password is wrong. Please try again')
60 return render_template('login.html',
61 title='Sign In',
62 form=form)
63
64 @app.route('/logout')
65 def logout():
66 logout_user()
67 return redirect(url_for('index'))
68
69 @app.route('/album/<int:id>', methods =['GET', 'DELETE'])
70 def getAlbum(id):
71 if request.method == 'GET':
72 return "<h1>Get album # %s</h1>" % id
73 else:
74 return 'Album #' + str(id) + " deleted"
75
76 @app.route('/albums', methods =['GET'])
77 def getAlbums():
78 user = current_user
79 app.logger.info("user: %s" % user)
80 query = tools.DBQuery()
81 # if user.is_anonymous:
82 # return "<h1>(au)Get all albums: %s</h1>" % dir(user)
83 # else:
84 u = load_user(user.get_id())
85 if u is None:
86 u = MyAnonymous()
87 a = query.get_albums_for_user(u)
88 else:
89 a = query.get_albums_for_user(u, True, True)
90 albums = []
91 for album in a:
92 # if not user.is_anonymous:
93 acl = query.get_acl(user, album)
94 # else:
95 # acl = Role.read
96 if acl is not None:
97 albums.append({'album': album, 'acl': acl})
98 app.logger.info("albums: %s" % a)
99 app.logger.info(tools.dump(albums))
100 return "<h1>(nu)Get all albums</h1><pre>%s</pre>" % albums
101
102 @app.route('/album', methods =['GET', 'POST'])
103 @login_required
104 def album():
105 user = g.user
106 form = AlbumForm(prefix="pf")
107 if form.validate_on_submit():
108 u = load_user(user.get_id())
109 try:
110 query = tools.DBQuery()
111 portfolios = query.get_portfolios(u)
112 new_album = Album(name=form.name.data, public=form.public.data, visible=form.visible.data, portfolio_id=portfolios[0].id)
113 db.session.add(new_album)
114 db.session.commit()
115 app.logger.warning("Created album: %s" % new_album)
116 except DBException as ex:
117 db.session.rollback()
118 flash(ex)
119 except exc.IntegrityError as ex:
120 db.session.rollback()
121 flash('Create album failed: %s' % ex)
122 except Exception as ex:
123 db.session.rollback()
124 flash("Unknown error {0}".format(ex))
125 return redirect(request.referrer)
126 return render_template('album.html',
127 title='Create Album',
128 user=user,
129 form=form)
130
131 @app.route('/portfolio/<int:id>', methods =['GET', 'DELETE'])
132 def getPortfolio(id):
133 if request.method == 'GET':
134 return "<h1>Get portfolio # %s</h1>" % id
135 else:
136 return 'Portfolio #' + str(id) + " deleted"
137
138 @app.route('/portfolios', methods =['GET'])
139 def getPortfolios():
140 return "<h1>Get all portfolios</h1>"
141
142 @app.route('/portfolio', methods =['GET', 'POST'])
143 @login_required
144 def portfolio():
145 user = g.user
146 form = PortfolioForm(prefix="pf")
147 if form.validate_on_submit():
148 pass
149 return render_template('portfolio.html',
150 title='Create Portfolio',
151 user=user,
152 form=form)
153
154 @app.route('/user/<username>', methods=['GET', 'POST'])
155 @login_required
156 def user(username):
157 form = UpdateForm(prefix="uf")
158 pwform = PwForm(prefix="pf")
159 deleteform = g.deleteform
160 referrer = request.referrer
161 if form.update.data and form.validate_on_submit():
162 try:
163 uname=form.username.data
164 email=form.email.data
165 name=form.name.data
166 user = User.query.filter_by(username=username).first()
167 if uname != username:
168 u = User.query.filter_by(username=uname).first()
169 if u is not None:
170 raise DBException("%s: Username exist" % uname)
171 user.username = uname
172 referrer = "/user/%s" % user.username
173 if email != user.email:
174 e = User.query.filter_by(email=email).first()
175 if e is not None:
176 raise DBException("%s: Email exist" % email)
177 user.email = email
178 if name != user.name:
179 user.name = name
180 except DBException as ex:
181 db.session.rollback()
182 flash("{0}".format(ex))
183 app.logger.warning("Update user failed: {0}".format(ex))
184 except exc.IntegrityError as ex:
185 db.session.rollback()
186 flash("Update user failed: {0}".format(ex))
187 app.logger.warning("Update user failed: {0}".format(ex))
188 except Exception as ex:
189 db.session.rollback()
190 flash("Unknown error {0}".format(ex))
191 app.logger.warning("Update user failed: Unknown error {0}".format(ex))
192 else:
193 try:
194 db.session.commit()
195 login_user(user, remember=False)
196 app.logger.warning("Updated user: %s" % user)
197 flash("Userdata successfully updated")
198 except exc.IntegrityError as ex:
199 db.session.rollback()
200 flash("Update user failed: {0}".format(ex))
201 except Exception as ex:
202 db.session.rollback()
203 flash("Unknown error {0}".format(ex))
204 return redirect(referrer)
205 elif pwform.pwchange.data and pwform.validate_on_submit():
206 user = User.query.filter_by(username=username).first()
207 if pwform.password.data == pwform.passwordchk.data and check_password_hash(user.password, pwform.passwordcur.data):
208 hashed_password = generate_password_hash(pwform.password.data, method='sha256')
209 user.password = hashed_password
210 try:
211 db.session.commit()
212 login_user(user, remember=False)
213 app.logger.warning("Updated user - password: %s" % user)
214 flash("Password successfully changed")
215 except exc.IntegrityError as ex:
216 db.session.rollback()
217 flash("Update user failed: {0}".format(ex))
218 except Exception as ex:
219 db.session.rollback()
220 flash("Unknown error {0}".format(ex))
221 else:
222 flash('Current password does not match or password different from password check')
223 return redirect(referrer)
224 else:
225 user = User.query.filter_by(username=username).first()
226 if user is None:
227 flash('User %s not found.' % username)
228 return redirect(url_for('index'))
229 app.logger.info("Show profile: %s" % user)
230 query = tools.DBQuery()
231 portfolios = query.get_portfolios(user)
232 private = []
233 for p in portfolios:
234 albums = query.get_albums(p)
235 p.set_user_count(len(query.get_users(p)))
236 a1 = []
237 for a in albums:
238 a.set_user_count(len(query.get_users(a)))
239 a1.append(a)
240 pf = {'portfolio': p, 'albums': a1}
241 private.append(pf)
242 a = query.get_albums_for_user(user)
243 app.logger.info("Albums: %s" % a)
244 albums = []
245 for album in a:
246 acl = query.get_acl(user, album)
247 app.logger.info("Album: %s -> acl: %s" % (album, acl))
248 if acl is not None:
249 albums.append({'album': album, 'acl': acl})
250 return render_template('user.html',
251 title='Profile',
252 user=user,
253 form=form,
254 pwform=pwform,
255 deleteform=deleteform,
256 private=private,
257 albums=albums)
258
259 @app.route('/register', methods=['GET', 'POST'])
260 def register():
261 form = RegisterForm()
262 if form.validate_on_submit():
263 if form.password.data == form.passwordchk.data:
264 try:
265 username=form.username.data
266 email=form.email.data
267 u = User.query.filter_by(username=username).first()
268 if u:
269 raise DBException("%s: Username exist" % username)
270 e = User.query.filter_by(email=email).first()
271 if e:
272 raise DBException("%s: Email exist" % email)
273 hashed_password = generate_password_hash(form.password.data, method='sha256')
274 new_user = User(name=form.name.data, username=form.username.data, email=form.email.data, password=hashed_password)
275 except DBException as ex:
276 db.session.rollback()
277 flash(ex)
278 except exc.IntegrityError as ex:
279 db.session.rollback()
280 flash('Create user failed: %s' % ex)
281 except Exception as ex:
282 db.session.rollback()
283 flash("Unknown error {0}".format(ex))
284 else:
285 try:
286 portfolio = Portfolio(name = new_user.name, owner = new_user)
287 db.session.add(portfolio)
288 new_user.portfolios.append(portfolio)
289 db.session.add(new_user)
290 acl = AccessRight(right = Role.read, user = new_user)
291 db.session.add(acl)
292 acl = AccessRight(right = Role.write, user = new_user)
293 db.session.add(acl)
294 acl = AccessRight(right = Role.admin, user = new_user)
295 db.session.add(acl)
296 db.session.commit()
297 app.logger.warning("Registered: %s" % new_user)
298 flash("You have been registered with username: " + form.username.data + os.linesep)
299 flash("Default Portfolio: " + portfolio.name)
300 return redirect(url_for('login'))
301 except exc.IntegrityError as ex:
302 db.session.rollback()
303 flash('Create user failed: %s' % ex)
304 except Exception as ex:
305 db.session.rollback()
306 flash("Unknown error {0}".format(ex))
307 else:
308 flash('Password did not match password check')
309 return render_template('register.html',
310 title='Register',
311 form=form)
312
313 @app.route('/resetpwd')
314 def resetpwd():
315 return '<h1>resetpwd</h1>'
316
317 @app.route('/search', methods=['POST'])
318 def search():
319 form = g.searchForm
320 if form.validate_on_submit():
321 token = form.token.data
322 flash("Search: " + token)
323 return redirect(request.referrer)
324
325 @app.route('/admin')
326 #@login_required
327 def admin():
328 try:
329 if g.user is not None and g.user.is_admin:
330 app.logger.warning("Enter Admin area: %s" % g.user)
331 return render_template('admin.html',
332 title='Administration')
333 except AttributeError:
334 pass
335 app.logger.critical("Tried to enter Admin area: %s" % g.user)
336 return redirect(request.referrer)#redirect(url_for('index'))
337
338
This page took 0.275667 seconds and 6 git commands to generate.