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