Пример #1
0
def login():
    form = LoginForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            email = request.form.get('email')
            password = request.form.get('password')

            fotogal_user = FotogalUser()

            if fotogal_user.exists(email=email) and fotogal_user.check_passwd(
                    email=email, passwd=password):
                user_id = fotogal_user.get_id(email=email)
                username = fotogal_user.get_username(id=user_id)

                auth_cookie = FotogalAuthCookie()

                (
                    cookie_name,
                    cookie_value,
                    expire_ts,
                ) = auth_cookie.create(user_id)

                if cookie_value and expire_ts:
                    cookie_secure = current_app.config.get(
                        'AUTH_COOKIE_SECURE')
                    cookie_httponly = current_app.config.get(
                        'AUTH_COOKIE_HTTPONLY')

                    # Save session values after login
                    session['user_id'] = user_id
                    session['username'] = username

                    resp = make_response(redirect(url_for('main.index')))
                    # set_cookie(key, value='', max_age=None, expires=None, path='/',
                    # domain=None, secure=False, httponly=False, samesite=None)
                    # TODO: samesite
                    resp.set_cookie(cookie_name, value=cookie_value, max_age=expire_ts, \
                        secure=cookie_secure, httponly=cookie_httponly)

                    return resp

                else:
                    # TODO: generate a log message for this error.
                    redirect(url_for('auth.login'))

            else:
                flask_flash(u'Nome de usuário ou Senha inválido(s)!', 'error')

        else:
            flask_flash(u'Erro ao processar o formulário!', 'error')

    return render_template('login.html', form=form)
Пример #2
0
def home():
    if request.method == 'POST':
        if 'submit' in request.form:
            # Download selected cards
            to_download = tuple(
                int(id) for id in request.form.getlist('download'))
            cards = Card.query.filter(Card.id.in_(to_download)).all()
            retval = ''
            for card in cards:
                audio_filename = 'flashcard{}.mp3'.format(
                    card.id) if card.audio else '#####.mp3'
                retval += (card.pinyin + '\n' + '[sound:' + audio_filename +
                           ']\n' + card.phrase + '\n' + card.translation +
                           '\n\n')
            return Response(retval,
                            mimetype="text/plain",
                            headers={
                                "Content-disposition":
                                "attachment; filename=flashcards.txt"
                            })
        # Else, download audio file
        for key in request.form.keys():
            try:
                id = int(key)
            except ValueError:
                pass
            else:
                card = Card.query.filter_by(id=id).first()
                if card is None:
                    continue
                filename = 'flashcard{}.mp3'.format(
                    card.id) if card.audio else '#####.mp3'
                return Response(card.audio,
                                mimetype='audio/mpeg',
                                headers={
                                    'Content-disposition':
                                    'attachment; filename=' + filename
                                })
        flask_flash('No audio file found: no valid card id given')
    cards = Card.query.filter_by(user_id=current_user.id,
                                 pending=False).all()[::-1]
    in_progress = Card.query.filter_by(user_id=current_user.id,
                                       pending=True).all()
    return render_template('home.html', cards=cards, in_progress=in_progress)
Пример #3
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        remember = len(request.form.getlist('remember-me')) > 0
        error = None
        user = User.query.filter_by(username=username).first()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user.password, password):
            error = 'Incorrect password.'

        if error is None:
            login_user(user, remember=remember)
            return redirect(url_for('home'))

        flask_flash(error)

    return render_template('login.html')
Пример #4
0
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif User.query.filter_by(username=username).first() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            User.new(username, generate_password_hash(password))
            return redirect(url_for('login'))

        flask_flash(error)

    return render_template('register.html')
Пример #5
0
def create():
    if request.method == 'POST':
        phrase = request.form['phrase']
        is_sentence = len(request.form.getlist('is-sentence')) > 0
        error = None

        if not phrase:
            error = 'Phrase is required'

        if error is None:
            q = Queue(connection=conn)
            card = Card.new(current_user, phrase)
            credentials = [
                current_user.chinesepod_username,
                current_user.chinesepod_password
            ]
            q.enqueue(make_card, card.id, is_sentence, credentials)
            return redirect(url_for('home'))

        flask_flash(error)

    return render_template('create.html')
Пример #6
0
def credentials():
    if request.method == 'POST':
        chinesepod_username = request.form['chinesepod-username']
        chinesepod_password = request.form['chinesepod-password']
        error = None

        if not chinesepod_username:
            error = 'Chinesepod username is required'
        elif not chinesepod_password:
            error = 'Chinesepod password is required'

        s = Scraper(credentials=(chinesepod_username, chinesepod_password))
        if not s.verify_chinesepod_credentials():
            error = 'Invalid credentials'

        if error is None:
            current_user.update_chinesepod_credentials(chinesepod_username,
                                                       chinesepod_password)

        flask_flash(error or 'Credentials updated successfully')

    return render_template('credentials.html')
Пример #7
0
def edit_profile_passwd(username):
    fotogal_user = FotogalUser()

    if fotogal_user.exists(username=username):
        user_id = session.get('user_id', None)
        session_username = session.get('username', None)

        if session_username != username:
            flask_abort(404)

        profile_dict = fotogal_user.get_profile_props(id=user_id)

        form = ProfilePasswdForm()

        if request.method == 'GET':
            return render_template('edit_profile_passwd.html',
                                   form=form,
                                   username=username,
                                   profile_dict=profile_dict)

        else:
            if form.validate_on_submit():
                old_passwd = request.form.get('old_password', '')
                new_passwd = request.form.get('new_password', '')

                if old_passwd != new_passwd and fotogal_user.check_passwd(
                        id=user_id, passwd=old_passwd):
                    was_updated = fotogal_user.update_passwd(id=user_id,
                                                             passwd=new_passwd)

                    if was_updated:
                        flask_flash(u'Sua senha foi atualizada com sucesso!',
                                    'success')
                    else:
                        flask_flash(u'Erro ao atualizar a sua senha!', 'error')

                else:
                    flask_flash(u'Erro ao atualizar a sua senha!', 'error')

            else:
                flask_flash(u'Erro ao atualizar a sua senha!', 'error')

            return redirect(
                url_for('main.edit_profile_passwd', username=username))
    else:
        flask_abort(404)
Пример #8
0
def flash(obj):
    """
    Wraps flask.flash() providing handlers for more input types.
    str: flask.flash(obj)
    dict: for key in obj: for err in obj[key]: flash(err)
    list: for item in obj: flash(item)
    """

    if isinstance(obj, str):
        flask_flash(obj)
    elif isinstance(obj, dict):
        for key in obj:
            for err in obj[key]:
                flask_flash(err)
    elif isinstance(obj, list):
        for item in obj:
            flask_flash(item)
    else:
        raise ValueError(obj)
Пример #9
0
def flash(message, level='info', category='message'):
    flask_flash({'msg': message, 'level': level}, category=category)
Пример #10
0
def flash(message: str, category: str = 'info'):
    flask_flash(message, category=category)
Пример #11
0
def edit_profile(username):
    fotogal_user = FotogalUser()

    if fotogal_user.exists(username=username):
        user_id = session.get('user_id', None)
        session_username = session.get('username', None)

        if session_username != username:
            flask_abort(404)

        form = ProfileForm()

        if request.method == 'GET':
            profile_dict = fotogal_user.get_profile_props(id=user_id)

            form.full_name.data = profile_dict['full_name']
            form.username.data = profile_dict['username']
            form.email.data = profile_dict['email']
            form.gender.data = profile_dict['user_data']['gender']
            form.website.data = profile_dict['user_data']['website']
            form.bio.data = profile_dict['user_data']['bio']
            form.is_private.data = profile_dict['is_private']

            return render_template(
                'edit_profile.html',
                form=form,
                username=username,
                profile_img_url=profile_dict['profile_image_url'])

        else:
            if form.validate_on_submit():
                profile_dict = {
                    'full_name': '',
                    'is_private': '',
                    'user_data': {
                        'website': '',
                        'bio': '',
                        'gender': ''
                    }
                }

                for k, v in profile_dict.items():
                    if k == 'user_data':
                        for k, v in profile_dict['user_data'].items():
                            profile_dict['user_data'][k] = request.form.get(
                                k, '')
                    else:
                        profile_dict[k] = request.form.get(k, '')

                if profile_dict['is_private'] == 'y':
                    profile_dict['is_private'] = True
                else:
                    profile_dict['is_private'] = False

                was_updated = fotogal_user.update_profile_props(
                    id=user_id, profile_dict=profile_dict)

                if was_updated:
                    flask_flash(u'Dados atualizados com sucesso!', 'success')
                else:
                    flask_flash(u'Erro ao atualizar os dados do usuário!',
                                'error')

            else:
                flask_flash(u'Erro ao atualizar os dados do usuário!', 'error')

            return redirect(url_for('main.edit_profile', username=username))

    else:
        flask_abort(404)
Пример #12
0
def register():
    """User registration form.

    """
    form = RegistrationForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            email = request.form.get('email', '')
            full_name = request.form.get('full_name', '')
            username = request.form.get('username', '')
            password = request.form.get('password', '')

            fotogal_user = FotogalUser()

            if fotogal_user.exists(email=email) or fotogal_user.exists(
                    username=username):
                flask_flash(u'E-mail/Nome de usuário já cadastrado(s)!',
                            'error')
            else:
                created_ts = utils.return_now_ts()

                new_user_dict = {
                    'email': email,
                    'full_name': full_name,
                    'username': username,
                    'password': password,
                    'follow_list': [],
                    'follow_sent_list': [],
                    'follow_you_list': [],
                    'follow_received_list': [],
                    'created_ts': created_ts,
                    'is_private': False,
                    'is_professional_account': False,
                    'profile_image_url': '',
                    'user_data': {
                        'birthday_ts': 0,
                        'website': '',
                        'bio': '',
                        'gender': '',
                        'phone_number': ''
                    }
                }

                new_user_id = fotogal_user.add_new_user(new_user_dict)

                if new_user_id:
                    auth_cookie = FotogalAuthCookie()

                    (
                        cookie_name,
                        cookie_value,
                        expire_ts,
                    ) = auth_cookie.create(new_user_id)

                    cookie_secure = current_app.config.get(
                        'AUTH_COOKIE_SECURE')
                    cookie_httponly = current_app.config.get(
                        'AUTH_COOKIE_HTTPONLY')

                    resp = make_response(
                        redirect(url_for('main.initial_suggestions')))
                    resp.set_cookie(cookie_name, cookie_value, max_age=expire_ts, \
                        secure=cookie_secure, httponly=cookie_httponly)

                    return resp

                else:
                    # error in creating a new user.
                    flask_flash(u'Erro ao processar o formulário!', 'error')

        else:
            flask_flash(u'Erro ao processar o formulário!', 'error')

    return render_template('register.html', form=form)