Example #1
0
def update_user(username):
    
    if username != session['user_info'].username:
        abort(404)
    
    current_user = get_user(username)
    form = UpdateForm(request.form)
    
    if form.validate():
        email = form.email.data
        password = form.password.data
        
        try: 
            current_user.email = email
            current_user.password = generate_password_hash(password)
            db.session.commit()
            
        except Exception as e:
            db.session.rollback()
            Log.error(str(e))
            raise e
            
        else:
            session['user_info'].email = current_user.email
            session['user_info'].password = current_user.password
            session['user_info'].password_confirm = current_user.password_confirm
            
            return redirect(url_for('.login', update_username=username))
    else:
        return render_template('regist.html', user=current_user, form=form)
Example #2
0
def recover_account():

    form = RecoverForm(request.form)
    recover_error = None
    if form.validate():

        email = form.email.data
        new_password = password_generator()

        try:
            current_user = User.query.filter_by(email=email).first()
        except Exception as e:
            Log.error(str(e))

        if not current_user:
            recover_error = 'No matching account!'
            return redirect(url_for('.recover_account', error=recover_error))

        if not current_user.email_verified:
            recover_error = 'Account not verified yet!'
            return redirect(url_for('.recover_account', error=recover_error))

        try:
            current_user.password = generate_password_hash(new_password)
            db.session.commit()
            return redirect(url_for('.send_recover_email', email=email))

        except Exception as e:
            db.session.rollback()
            Log.error(str(e))
            recover_error = 'Error!'
            raise e

    return render_template('recover.html', form=form, error=recover_error)
Example #3
0
def register_user():
  
    if 'user_info' in session:
        return redirect(url_for('.main'))
    
    form = RegisterForm(request.form)
  
    if form.validate():
    
        username = form.username.data
        email = form.email.data
        password = form.password.data
        
        try: 
            user = User(username=username,
                        email=email, 
                        password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            
            Log.debug(user)
            
        except Exception as e:
            error = "DB error occurs : " + str(e)
            Log.error(error)
            db.session.rollback()
            raise e
            
        else:
            return redirect(url_for('.login', regist_username=username))
    else:
        return render_template('regist.html', form=form)
Example #4
0
def send_token_email():

    current_user = get_user(session['user_info'].username)
    if current_user.email_verified:
        return redirect(url_for('.main'))

    username = current_user.username
    email = current_user.email

    token = generate_verification_token(email)
    confirm_url = create_token_link(token)
    msg = Message("Account verification")
    msg.html = render_template('email/activation.html',
                               confirm_url=confirm_url)
    msg.recipients = [email]

    try:
        mail.send(msg)
        Log.info('Verification mail sent to %s' % (username))
        return redirect(url_for('.main', email_sent=True))
    except Exception as e:
        Log.error(str(e))
        raise e

    return redirect(url_for('.main', email_error=True))
Example #5
0
def get_user(username):
    try:
        current_user = User.query.filter_by(username=username).first()
        Log.debug(current_user)
        return current_user

    except Exception as e:
        Log.error(str(e))
        raise e
Example #6
0
    def decorated_function(*args, **kwargs):
        """Check whether logged in"""
        try:
            session_key = request.cookies.get(
                current_app.config['SESSION_COOKIE_NAME'])
            is_login = False
            if session.sid == session_key and session.__contains__(
                    'user_info'):
                is_login = True

            if not is_login:
                return redirect(url_for('web_frame.login', next=request.url))

            return f(*args, **kwargs)

        except Exception as e:
            Log.error('Web error: %s' % str(e))
            raise e
Example #7
0
def login_form():

    if 'user_info' in session:
        return redirect(url_for('.main'))

    next_url = request.args.get('next', '')
    regist_username = request.args.get('regist_username', '')
    update_username = request.args.get('update_username', '')
    recover_mail = request.args.get('recover_mail', '')
    Log.info('(%s)next_url is %s' % (request.method, next_url))

    form = LoginForm(request.form)

    return render_template('login.html',
                           next_url=next_url,
                           form=form,
                           regist_username=regist_username,
                           update_username=update_username)
Example #8
0
def login():

    form = LoginForm(request.form)
    next_url = form.next_url.data
    login_error = None

    if form.validate():
        session.permanent = True

        username = form.username.data
        password = form.password.data
        next_url = form.next_url.data

        Log.info('(%s)next_url is %s' % (request.method, next_url))

        user = get_user(username)

        if user:
            if not check_password_hash(user.password, password):
                login_error = 'Invalid password'

            else:
                session['user_info'] = user
                Log.info('%s has logged in' % user)
                if user.admin:
                    return redirect(url_for('admin.index'))
                elif next_url != '':
                    return redirect(next_url)
                else:
                    return redirect(url_for('.main'))

        else:
            login_error = 'User does not exist'

    return render_template('login.html',
                           next_url=next_url,
                           form=form,
                           error=login_error)
Example #9
0
def activate_user(token):

    try:
        email = confirm_token(token)
        print(email)

    except BadSignature:
        Log.error(str(BadSignature))
        abort(404)

    user = User.query.filter_by(email=email).first()
    try:
        session['user_info'].email_verified = True
        user.email_verified = True
        db.session.commit()

    except Exception as e:
        db.session.rollback()
        Log.error(str(e))
        raise e

    activated = True

    return redirect(url_for('.main', user_activated=activated))
Example #10
0
def send_recover_email():

    email = request.args.get('email', '')
    recover_account = User.query.filter_by(email=email).first()

    username = recover_account.username
    password = recover_account.password

    msg = Message()
    msg.html = render_template('email/recover.html',
                               username=username,
                               password=password)
    msg.recipients = [email]

    try:
        mail.send(msg)
        Log.info('Recovery mail sent to %s' % (username))
        recover_mail = 'E-mail successfully sent!'
        return redirect(url_for('.recover_account', recover_mail=recover_mail))
    except Exception as e:
        Log.error(str(e))
        raise e

    return redirect(url_for('.recover_account'))
Example #11
0
def unregist():
    user_id = session['user_info'].id
    
    try:
        user = User.query.filter_by(id=user_id).first()
        Log.info("unregist:"+user.username)
        
        if user.id == user_id:
            db.session.delete(user)
            db.session.commit()
            
        else:
            Log.error("Following user does not exist: %d", user_id)
            raise Exception
    
    except Exception as e:
        Log.error(str(e))
        db.session.rollback()
        raise error
        
    return redirect(url_for('.logout'))
Example #12
0
# -*- coding: utf-8 -*-

from flask import Blueprint
from web_frame.web_logger import Log

web_frame = Blueprint('web_frame',
                      __name__,
                      template_folder='../templates',
                      static_folder='../static')

Log.info('static folder: %s' % web_frame.static_folder)
Log.info('template folder: %s' % web_frame.template_folder)
Example #13
0
def close_db_session(exception=None):

    try:
        db.session.remove()
    except Exception as e:
        Log.error(str(e))
Example #14
0
def create_app(config_filepath='resource/config.cfg'):

    web_app = Flask(__name__)

    #CONFIG
    from web_frame.web_config import webConfig
    web_app.config.from_object(webConfig)
    web_app.config.from_pyfile(config_filepath, silent=True)
    print_settings(web_app.config.items())

    #Initialise Log
    from web_frame.web_logger import Log
    log_filepath = os.path.join(web_app.root_path,
                                web_app.config['LOG_FILE_PATH'])
    Log.init(log_filepath=log_filepath)

    #Load DB, Migrate
    from flask_migrate import Migrate
    from web_frame.model import db
    db.init_app(web_app)
    migrate = Migrate(web_app, db)

    #Model
    from web_frame.model.user import User
    with web_app.app_context():
        db.create_all()  # Create tables

    #Admin
    from flask_admin import Admin
    from web_frame.admin import AdminLogin, AuthModelView
    admin = Admin(web_app,
                  index_view=AdminLogin(),
                  name='miniweb',
                  template_mode='bootstrap3')
    admin.add_view(AuthModelView(User, db.session))

    #Mail
    from web_frame.web_mail import mail
    mail.init_app(web_app)

    #Load view functions
    from web_frame.controller import general
    from web_frame.controller import login
    from web_frame.controller import register_user
    from web_frame.controller import main
    from web_frame.controller import email
    from web_frame.controller import recover

    #Blueprint
    from web_frame.web_blueprint import web_frame
    web_app.register_blueprint(web_frame)

    #SessionInterface
    from web_frame.cache_session import SimpleCacheSessionInterface
    web_app.session_interface = SimpleCacheSessionInterface()

    #Common error handlers
    web_app.register_error_handler(404, not_found)
    web_app.register_error_handler(500, server_error)

    return web_app
Example #15
0
def logout():

    Log.info('%s has logged out' % session['user_info'])
    session.clear()

    return redirect(url_for('.index'))