from flask import render_template, flash, redirect, session, url_for, request, g, abort from flask_login import login_user, logout_user, current_user, login_required from app import app, lm, tools, db from .forms import LoginForm, RegisterForm, UpdateForm, PwForm, SearchForm, DeleteForm, PortfolioForm, AlbumForm from .models import User, Portfolio, Album, AccessRight, Role, MyAnonymous from werkzeug.security import generate_password_hash, check_password_hash import datetime, os from config import SESSION_TIMEOUT class DBException(Exception): pass @app.before_request def before_request(): session.permanent = True app.permanent_session_lifetime = datetime.timedelta(minutes=SESSION_TIMEOUT) session.modified = True g.user = current_user g.searchForm = SearchForm(prefix="sf") g.deleteform = DeleteForm(prefix="df") @lm.user_loader def load_user(id): return User.query(id=id)[0] @app.route('/') @app.route('/index') def index(): user = g.user return render_template('index.html', title='Home', user=user) @app.route('/login', methods=['GET', 'POST']) def login(): if g.user is not None and g.user.is_authenticated: return redirect(request.referrer)#redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.query(username=form.username.data)[0] if user is None: flash('Unknown username. Please try again or register.') else: if check_password_hash(user.password, form.password.data): app.logger.info("Login: %s" % user) login_user(user, remember=False) g.user = user user.addObserver(db) next = request.args.get('next') if next is not None: if not tools.is_safe_url(next): return abort(400) req = next.rsplit('/', 1) app.logger.info("%s:%s" % (req[0], req[1])) if req[0] == '/user' and req[1] != user.name: next = "%s/%s" % (req[0], user.username) app.logger.info("Login: %s next: %s" % (user, next)) return redirect(next or url_for('index')) else: flash('Username or password is wrong. Please try again') return render_template('login.html', title='Sign In', form=form) @app.route('/logout') def logout(): logout_user() return redirect(url_for('index')) @app.route('/album/', methods =['GET', 'DELETE']) def getAlbum(id): if request.method == 'GET': return "

Get album # %s

" % id else: return 'Album #' + str(id) + " deleted" @app.route('/albums', methods =['GET']) def getAlbums(): user = current_user app.logger.info("user: %s" % user) query = tools.DBQuery() # if user.is_anonymous: # return "

(au)Get all albums: %s

" % dir(user) # else: u = load_user(user.get_id()) if u is None: u = MyAnonymous() a = query.get_albums_for_user(u) else: a = query.get_albums_for_user(u, True, True) albums = [] for album in a: # if not user.is_anonymous: acl = query.get_acl(user, album) # else: # acl = Role.read if acl is not None: albums.append({'album': album, 'acl': acl}) app.logger.info("albums: %s" % a) app.logger.info(tools.dump(albums)) return "

(nu)Get all albums

%s
" % albums @app.route('/album', methods =['GET', 'POST']) @login_required def album(): user = g.user form = AlbumForm(prefix="pf") if form.validate_on_submit(): u = load_user(user.get_id()) try: query = tools.DBQuery() portfolios = query.get_portfolios(u) new_album = Album(name=form.name.data, public=form.public.data, visible=form.visible.data, portfolio_id=portfolios[0].id) db.store(new_album) app.logger.warning("Created album: %s" % new_album) except DBException as ex: flash(ex) except Exception as ex: flash('Create album failed: %s' % ex) # except Exception as ex: # flash("Unknown error {0}".format(ex)) return redirect(request.referrer) return render_template('album.html', title='Create Album', user=user, form=form) @app.route('/portfolio/', methods =['GET', 'DELETE']) def getPortfolio(id): if request.method == 'GET': return "

Get portfolio # %s

" % id else: return 'Portfolio #' + str(id) + " deleted" @app.route('/portfolios', methods =['GET']) def getPortfolios(): return "

Get all portfolios

" @app.route('/portfolio', methods =['GET', 'POST']) @login_required def portfolio(): user = g.user form = PortfolioForm(prefix="pf") if form.validate_on_submit(): pass return render_template('portfolio.html', title='Create Portfolio', user=user, form=form) @app.route('/user/', methods=['GET', 'POST']) @login_required def user(username): form = UpdateForm(prefix="uf") pwform = PwForm(prefix="pf") deleteform = g.deleteform referrer = request.referrer if form.update.data and form.validate_on_submit(): try: uname=form.username.data email=form.email.data name=form.name.data user = User.query(username=username)[0] if uname != username: u = User.query(username=uname)[0] if u is not None: raise DBException("%s: Username exist" % uname) user.username = uname referrer = "/user/%s" % user.username if email != user.email: e = User.query(email=email)[0] if e is not None: raise DBException("%s: Email exist" % email) user.email = email if name != user.name: user.name = name except DBException as ex: user.rollback() flash("{0}".format(ex)) app.logger.warning("Update user failed: {0}".format(ex)) except Exception as ex: user.rollback() flash("Update user failed: {0}".format(ex)) app.logger.warning("Update user failed: {0}".format(ex)) # except Exception as ex: # db.rollback() # flash("Unknown error {0}".format(ex)) # app.logger.warning("Update user failed: Unknown error {0}".format(ex)) else: try: user.commit() login_user(user, remember=False) app.logger.warning("Updated user: %s" % user) flash("Userdata successfully updated") except Exception as ex: flash("Update user failed: {0}".format(ex)) # except Exception as ex: # flash("Unknown error {0}".format(ex)) return redirect(referrer) elif pwform.pwchange.data and pwform.validate_on_submit(): user = User.query(username=username)[0] if pwform.password.data == pwform.passwordchk.data and check_password_hash(user.password, pwform.passwordcur.data): hashed_password = generate_password_hash(pwform.password.data, method='sha256') user.password = hashed_password try: user.commit() login_user(user, remember=False) app.logger.warning("Updated user - password: %s" % user) flash("Password successfully changed") except Exception as ex: flash("Update user failed: {0}".format(ex)) # except Exception as ex: # flash("Unknown error {0}".format(ex)) else: flash('Current password does not match or password different from password check') return redirect(referrer) else: user = User.query(username=username)[0] if user is None: flash('User %s not found.' % username) return redirect(url_for('index')) app.logger.info("Show profile: %s" % user) query = tools.DBQuery() portfolios = query.get_portfolios(user) app.logger.info("Portfolios: {0}".format(portfolios)) private = [] for p in portfolios: albums = query.get_albums(p) #p.set_user_count(len(query.get_users(p))) p.set_user_count(1) a1 = [] for a in albums: a.set_user_count(len(query.get_users(a))) a1.append(a) pf = {'portfolio': p, 'albums': a1} private.append(pf) a = query.get_albums_for_user(user) app.logger.info("Albums: %s" % a) albums = [] for album in a: acl = query.get_acl(user, album) app.logger.info("Album: %s -> acl: %s" % (album, acl)) if acl is not None: albums.append({'album': album, 'acl': acl}) return render_template('user.html', title='Profile', user=user, form=form, pwform=pwform, deleteform=deleteform, private=private, albums=albums) @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): if form.password.data == form.passwordchk.data: try: username=form.username.data email=form.email.data u = User.query.filter_by(username=username).first() if u: raise DBException("%s: Username exist" % username) e = User.query.filter_by(email=email).first() if e: raise DBException("%s: Email exist" % email) hashed_password = generate_password_hash(form.password.data, method='sha256') new_user = User(name=form.name.data, username=form.username.data, email=form.email.data, password=hashed_password) except DBException as ex: flash(ex) except Exception as ex: flash('Create user failed: %s' % ex) # except Exception as ex: # flash("Unknown error {0}".format(ex)) else: try: portfolio = Portfolio(name = new_user.name, owner = new_user) #db.session.add(portfolio) new_user.portfolios.append(portfolio) #db.session.add(new_user) acl = AccessRight(right = Role.read, user = new_user) #db.session.add(acl) acl = AccessRight(right = Role.write, user = new_user) #db.session.add(acl) acl = AccessRight(right = Role.admin, user = new_user) #db.session.add(acl) #db.session.commit() app.logger.warning("Registered: %s" % new_user) flash("You have been registered with username: " + form.username.data + os.linesep) flash("Default Portfolio: " + portfolio.name) return redirect(url_for('login')) except Exception as ex: flash('Create user failed: %s' % ex) except Exception as ex: flash("Unknown error {0}".format(ex)) else: flash('Password did not match password check') return render_template('register.html', title='Register', form=form) @app.route('/resetpwd') def resetpwd(): return '

resetpwd

' @app.route('/search', methods=['POST']) def search(): form = g.searchForm if form.validate_on_submit(): token = form.token.data flash("Search: " + token) return redirect(request.referrer) @app.route('/admin') #@login_required def admin(): try: if g.user is not None and g.user.is_admin: app.logger.warning("Enter Admin area: %s" % g.user) return render_template('admin.html', title='Administration') except AttributeError: pass app.logger.critical("Tried to enter Admin area: %s" % g.user) return redirect(request.referrer)#redirect(url_for('index'))