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
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(id=id)[0]
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(username
=form
.username
.data
)[0]
42 flash('Unknown username. Please try again or register.')
44 if check_password_hash(user
.password
, form
.password
.data
):
45 app
.logger
.info("Login: %s" % user
)
46 login_user(user
, remember
=False)
49 next
= request
.args
.get('next')
51 if not tools
.is_safe_url(next
):
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'))
60 flash('Username or password is wrong. Please try again')
61 return render_template('login.html',
68 return redirect(url_for('index'))
70 @app.route('/album/<int:id>', methods
=['GET', 'DELETE'])
72 if request
.method
== 'GET':
73 return "<h1>Get album # %s</h1>" % id
75 return 'Album #' + str(id) + " deleted"
77 @app.route('/albums', methods
=['GET'])
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)
85 u
= load_user(user
.get_id())
88 a
= query
.get_albums_for_user(u
)
90 a
= query
.get_albums_for_user(u
, True, True)
93 # if not user.is_anonymous:
94 acl
= query
.get_acl(user
, album
)
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
103 @app.route('/album', methods
=['GET', 'POST'])
107 form
= AlbumForm(prefix
="pf")
108 if form
.validate_on_submit():
109 u
= load_user(user
.get_id())
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)
115 app
.logger
.warning("Created album: %s" % new_album
)
116 except DBException
as 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',
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
133 return 'Portfolio #' + str(id) + " deleted"
135 @app.route('/portfolios', methods
=['GET'])
137 return "<h1>Get all portfolios</h1>"
139 @app.route('/portfolio', methods
=['GET', 'POST'])
143 form
= PortfolioForm(prefix
="pf")
144 if form
.validate_on_submit():
146 return render_template('portfolio.html',
147 title
='Create Portfolio',
151 @app.route('/user/<username>', methods
=['GET', 'POST'])
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():
160 uname
=form
.username
.data
161 email
=form
.email
.data
163 user
= User
.query(username
=username
)[0]
164 if uname
!= username
:
165 u
= User
.query(username
=uname
)[0]
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]
173 raise DBException("%s: Email exist" % email
)
175 if name
!= user
.name
:
177 except DBException
as ex
:
179 flash("{0}".format(ex
))
180 app
.logger
.warning("Update user failed: {0}".format(ex
))
181 except Exception as ex
:
183 flash("Update user failed: {0}".format(ex
))
184 app
.logger
.warning("Update user failed: {0}".format(ex
))
185 # except Exception as ex:
187 # flash("Unknown error {0}".format(ex))
188 # app.logger.warning("Update user failed: Unknown error {0}".format(ex))
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
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))
215 flash('Current password does not match or password different from password check')
216 return redirect(referrer
)
218 user
= User
.query(username
=username
)[0]
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
))
228 albums
= query
.get_albums(p
)
229 #p.set_user_count(len(query.get_users(p)))
233 a
.set_user_count(len(query
.get_users(a
)))
235 pf
= {'portfolio': p
, 'albums': a1
}
237 a
= query
.get_albums_for_user(user
)
238 app
.logger
.info("Albums: %s" % a
)
241 acl
= query
.get_acl(user
, album
)
242 app
.logger
.info("Album: %s -> acl: %s" % (album
, acl
))
244 albums
.append({'album': album
, 'acl': acl
})
245 return render_template('user.html',
250 deleteform
=deleteform
,
254 @app.route('/register', methods
=['GET', 'POST'])
256 form
= RegisterForm()
257 if form
.validate_on_submit():
258 if form
.password
.data
== form
.passwordchk
.data
:
260 username
=form
.username
.data
261 email
=form
.email
.data
262 u
= User
.query
.filter_by(username
=username
).first()
264 raise DBException("%s: Username exist" % username
)
265 e
= User
.query
.filter_by(email
=email
).first()
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
:
272 except Exception as ex
:
273 flash('Create user failed: %s' % ex
)
274 # except Exception as ex:
275 # flash("Unknown error {0}".format(ex))
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
)
284 acl
= AccessRight(right
= Role
.write
, user
= new_user
)
286 acl
= AccessRight(right
= Role
.admin
, user
= new_user
)
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
))
298 flash('Password did not match password check')
299 return render_template('register.html',
303 @app.route('/resetpwd')
305 return '<h1>resetpwd</h1>'
307 @app.route('/search', methods
=['POST'])
310 if form
.validate_on_submit():
311 token
= form
.token
.data
312 flash("Search: " + token
)
313 return redirect(request
.referrer
)
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:
325 app
.logger
.critical("Tried to enter Admin area: %s" % g
.user
)
326 return redirect(request
.referrer
)#redirect(url_for('index'))