]> git.datanom.net - pwp.git/blame - app/views.py
Half way through migration away from sqlalchemy
[pwp.git] / app / views.py
CommitLineData
e5424f29
MR
1from flask import render_template, flash, redirect, session, url_for, request, g, abort
2from flask_login import login_user, logout_user, current_user, login_required
fc01a3eb 3from app import app, lm, tools, db
e5424f29
MR
4from .forms import LoginForm, RegisterForm, UpdateForm, PwForm, SearchForm, DeleteForm, PortfolioForm, AlbumForm
5from .models import User, Portfolio, Album, AccessRight, Role, MyAnonymous
6from werkzeug.security import generate_password_hash, check_password_hash
7import datetime, os
8from config import SESSION_TIMEOUT
9
10class DBException(Exception):
11 pass
12
13@app.before_request
14def 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
23def load_user(id):
fc01a3eb 24 return User.query(id=id)[0]
e5424f29
MR
25
26@app.route('/')
27@app.route('/index')
28def 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'])
35def 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():
fc01a3eb 40 user = User.query(username=form.username.data)[0]
e5424f29
MR
41 if user is None:
42 flash('Unknown username. Please try again or register.')
43 else:
e5424f29
MR
44 if check_password_hash(user.password, form.password.data):
45 app.logger.info("Login: %s" % user)
46 login_user(user, remember=False)
fc01a3eb
MR
47 g.user = user
48 user.addObserver(db)
e5424f29
MR
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')
66def logout():
67 logout_user()
68 return redirect(url_for('index'))
69
70@app.route('/album/<int:id>', methods =['GET', 'DELETE'])
71def 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'])
78def 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
105def 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)
fc01a3eb 114 db.store(new_album)
e5424f29
MR
115 app.logger.warning("Created album: %s" % new_album)
116 except DBException as ex:
e5424f29 117 flash(ex)
e5424f29 118 except Exception as ex:
fc01a3eb
MR
119 flash('Create album failed: %s' % ex)
120# except Exception as ex:
121# flash("Unknown error {0}".format(ex))
e5424f29
MR
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'])
129def 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'])
136def getPortfolios():
137 return "<h1>Get all portfolios</h1>"
138
139@app.route('/portfolio', methods =['GET', 'POST'])
140@login_required
141def 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
153def 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
fc01a3eb 163 user = User.query(username=username)[0]
e5424f29 164 if uname != username:
fc01a3eb 165 u = User.query(username=uname)[0]
e5424f29
MR
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:
fc01a3eb 171 e = User.query(email=email)[0]
e5424f29
MR
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:
fc01a3eb 178 user.rollback()
e5424f29
MR
179 flash("{0}".format(ex))
180 app.logger.warning("Update user failed: {0}".format(ex))
fc01a3eb
MR
181 except Exception as ex:
182 user.rollback()
e5424f29
MR
183 flash("Update user failed: {0}".format(ex))
184 app.logger.warning("Update user failed: {0}".format(ex))
fc01a3eb
MR
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))
e5424f29
MR
189 else:
190 try:
fc01a3eb 191 user.commit()
e5424f29
MR
192 login_user(user, remember=False)
193 app.logger.warning("Updated user: %s" % user)
194 flash("Userdata successfully updated")
e5424f29 195 except Exception as ex:
fc01a3eb
MR
196 flash("Update user failed: {0}".format(ex))
197# except Exception as ex:
198# flash("Unknown error {0}".format(ex))
e5424f29
MR
199 return redirect(referrer)
200 elif pwform.pwchange.data and pwform.validate_on_submit():
fc01a3eb 201 user = User.query(username=username)[0]
e5424f29
MR
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:
fc01a3eb 206 user.commit()
e5424f29
MR
207 login_user(user, remember=False)
208 app.logger.warning("Updated user - password: %s" % user)
209 flash("Password successfully changed")
e5424f29 210 except Exception as ex:
fc01a3eb
MR
211 flash("Update user failed: {0}".format(ex))
212# except Exception as ex:
213# flash("Unknown error {0}".format(ex))
e5424f29
MR
214 else:
215 flash('Current password does not match or password different from password check')
216 return redirect(referrer)
217 else:
fc01a3eb 218 user = User.query(username=username)[0]
e5424f29
MR
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)
fc01a3eb 225 app.logger.info("Portfolios: {0}".format(portfolios))
e5424f29
MR
226 private = []
227 for p in portfolios:
228 albums = query.get_albums(p)
fc01a3eb
MR
229 #p.set_user_count(len(query.get_users(p)))
230 p.set_user_count(1)
e5424f29
MR
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'])
255def 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:
e5424f29 271 flash(ex)
e5424f29 272 except Exception as ex:
fc01a3eb
MR
273 flash('Create user failed: %s' % ex)
274# except Exception as ex:
275# flash("Unknown error {0}".format(ex))
e5424f29
MR
276 else:
277 try:
278 portfolio = Portfolio(name = new_user.name, owner = new_user)
fc01a3eb 279 #db.session.add(portfolio)
e5424f29 280 new_user.portfolios.append(portfolio)
fc01a3eb 281 #db.session.add(new_user)
e5424f29 282 acl = AccessRight(right = Role.read, user = new_user)
fc01a3eb 283 #db.session.add(acl)
e5424f29 284 acl = AccessRight(right = Role.write, user = new_user)
fc01a3eb 285 #db.session.add(acl)
e5424f29 286 acl = AccessRight(right = Role.admin, user = new_user)
fc01a3eb
MR
287 #db.session.add(acl)
288 #db.session.commit()
e5424f29
MR
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'))
fc01a3eb 293 except Exception as ex:
e5424f29
MR
294 flash('Create user failed: %s' % ex)
295 except Exception as ex:
e5424f29
MR
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')
304def resetpwd():
305 return '<h1>resetpwd</h1>'
306
307@app.route('/search', methods=['POST'])
308def 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
317def 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.11756 seconds and 5 git commands to generate.