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
8 from config
import SESSION_TIMEOUT
10 class DBException(Exception):
15 session
.permanent
= True
16 app
.permanent_session_lifetime
= datetime
.timedelta(minutes
=SESSION_TIMEOUT
)
17 session
.modified
= True
19 g
.searchForm
= SearchForm(prefix
="sf")
20 g
.deleteform
= DeleteForm(prefix
="df")
24 return User
.query
.get(int(id))
30 return render_template('index.html',
34 @app.route('/login', methods
=['GET', 'POST'])
36 if g
.user
is not None and g
.user
.is_authenticated
:
37 return redirect(request
.referrer
)#redirect(url_for('index'))
39 if form
.validate_on_submit():
40 user
= User
.query
.filter_by(username
=form
.username
.data
).first()
42 flash('Unknown username. Please try again or register.')
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')
50 if not tools
.is_safe_url(next
):
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'))
59 flash('Username or password is wrong. Please try again')
60 return render_template('login.html',
67 return redirect(url_for('index'))
69 @app.route('/album/<int:id>', methods
=['GET', 'DELETE'])
71 if request
.method
== 'GET':
72 return "<h1>Get album # %s</h1>" % id
74 return 'Album #' + str(id) + " deleted"
76 @app.route('/albums', methods
=['GET'])
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)
84 u
= load_user(user
.get_id())
87 a
= query
.get_albums_for_user(u
)
89 a
= query
.get_albums_for_user(u
, True, True)
92 # if not user.is_anonymous:
93 acl
= query
.get_acl(user
, album
)
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
102 @app.route('/album', methods
=['GET', 'POST'])
106 form
= AlbumForm(prefix
="pf")
107 if form
.validate_on_submit():
108 u
= load_user(user
.get_id())
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
)
115 app
.logger
.warning("Created album: %s" % new_album
)
116 except DBException
as ex
:
117 db
.session
.rollback()
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',
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
136 return 'Portfolio #' + str(id) + " deleted"
138 @app.route('/portfolios', methods
=['GET'])
140 return "<h1>Get all portfolios</h1>"
142 @app.route('/portfolio', methods
=['GET', 'POST'])
146 form
= PortfolioForm(prefix
="pf")
147 if form
.validate_on_submit():
149 return render_template('portfolio.html',
150 title
='Create Portfolio',
154 @app.route('/user/<username>', methods
=['GET', 'POST'])
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():
163 uname
=form
.username
.data
164 email
=form
.email
.data
166 user
= User
.query
.filter_by(username
=username
).first()
167 if uname
!= username
:
168 u
= User
.query
.filter_by(username
=uname
).first()
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()
176 raise DBException("%s: Email exist" % email
)
178 if name
!= user
.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
))
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
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
))
222 flash('Current password does not match or password different from password check')
223 return redirect(referrer
)
225 user
= User
.query
.filter_by(username
=username
).first()
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
)
234 albums
= query
.get_albums(p
)
235 p
.set_user_count(len(query
.get_users(p
)))
238 a
.set_user_count(len(query
.get_users(a
)))
240 pf
= {'portfolio': p
, 'albums': a1
}
242 a
= query
.get_albums_for_user(user
)
243 app
.logger
.info("Albums: %s" % a
)
246 acl
= query
.get_acl(user
, album
)
247 app
.logger
.info("Album: %s -> acl: %s" % (album
, acl
))
249 albums
.append({'album': album
, 'acl': acl
})
250 return render_template('user.html',
255 deleteform
=deleteform
,
259 @app.route('/register', methods
=['GET', 'POST'])
261 form
= RegisterForm()
262 if form
.validate_on_submit():
263 if form
.password
.data
== form
.passwordchk
.data
:
265 username
=form
.username
.data
266 email
=form
.email
.data
267 u
= User
.query
.filter_by(username
=username
).first()
269 raise DBException("%s: Username exist" % username
)
270 e
= User
.query
.filter_by(email
=email
).first()
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()
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
))
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
)
292 acl
= AccessRight(right
= Role
.write
, user
= new_user
)
294 acl
= AccessRight(right
= Role
.admin
, user
= new_user
)
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
))
308 flash('Password did not match password check')
309 return render_template('register.html',
313 @app.route('/resetpwd')
315 return '<h1>resetpwd</h1>'
317 @app.route('/search', methods
=['POST'])
320 if form
.validate_on_submit():
321 token
= form
.token
.data
322 flash("Search: " + token
)
323 return redirect(request
.referrer
)
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:
335 app
.logger
.critical("Tried to enter Admin area: %s" % g
.user
)
336 return redirect(request
.referrer
)#redirect(url_for('index'))