<commit_before># -*- coding: utf-8 -*-

"""
byceps.blueprints.user.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 <NAME>
"""

from datetime import datetime

from flask import abort, g, request, session, url_for

from ...config import get_site_mode, SiteMode
from ...database import db
from ...mail import mail
from ...util.framework import create_blueprint, flash_error, flash_success
from ...util.image import create_thumbnail, Dimensions, \
    guess_type as guess_image_type, read_dimensions
from ...util.templating import templated
from ...util import upload
from ...util.views import redirect_to, respond_no_content

from ..authorization.models import Role
from ..terms.models import Consent, ConsentContext

from .forms import AvatarImageUpdateForm, CreateForm, LoginForm
from .models import NewsletterSubscription, NewsletterSubscriptionState, User, \
    VerificationToken, VerificationTokenPurpose


MAXIMUM_AVATAR_IMAGE_DIMENSIONS = Dimensions(110, 150)


blueprint = create_blueprint('user', __name__)


@blueprint.before_app_request
def before_request():
    g.current_user = UserSession.get_user()


@blueprint.route('/<id>')
@templated
def view(id):
    """Show a user's profile."""
    user = find_user_by_id(id)
    return {'user': user}


@blueprint.route('/create')
@templated
def create_form(errorneous_form=None):
    """Show a form to create a user."""
    form = errorneous_form if errorneous_form else CreateForm()
    return {'form': form}


@blueprint.route('/', methods=['POST'])
def create():
    """Create a user."""
    form = CreateForm(request.form)
    if not form.validate():
        return create_form(form)

    screen_name = form.screen_name.data
    email_address = form.email_address.data.lower()
    password = form.password.data
    consent_to_terms = form.consent_to_terms.data
    subscribe_to_newsletter = form.subscribe_to_newsletter.data

    if is_screen_name_already_assigned(screen_name):
        flash_error(
            'Dieser Benutzername ist bereits einem Benutzerkonto zugeordnet.')
        return create_form(form)

    if is_email_address_already_assigned(email_address):
        flash_error(
            'Diese E-Mail-Adresse ist bereits einem Benutzerkonto zugeordnet.')
        return create_form(form)

    user = User.create(screen_name, email_address, password)
    db.session.add(user)

    verification_token = VerificationToken(
        user, VerificationTokenPurpose.email_address_confirmation)
    db.session.add(verification_token)

    terms_consent = Consent(user, ConsentContext.account_creation)
    db.session.add(terms_consent)

    newsletter_subscription_state = NewsletterSubscriptionState.requested \
        if subscribe_to_newsletter \
        else NewsletterSubscriptionState.declined
    newsletter_subscription = NewsletterSubscription(user, newsletter_subscription_state)
    db.session.add(newsletter_subscription)

    board_user_role = Role.query.get('board_user')
    user.roles.add(board_user_role)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        flash_error('Das Benutzerkonto für "{}" konnte nicht angelegt werden.',
                    user.screen_name)
        return create_form(form)

    db.session.commit()

    confirmation_url = url_for('.confirm_email_address',
                               user_id=user.id,
                               token=verification_token.token,
                               _external=True)
    send_email_address_confirmation_email(confirmation_url)

    flash_success('Das Benutzerkonto für "{}" wurde angelegt.',
                  user.screen_name)
    return redirect_to('.view', id=user.id)


def is_screen_name_already_assigned(screen_name):
    return do_users_matching_filter_exist(User.screen_name, screen_name)


def is_email_address_already_assigned(email_address):
    return do_users_matching_filter_exist(User.email_address, email_address)


def do_users_matching_filter_exist(model_attribute, search_value):
    """Return `True` if any users match the filter.

    Comparison is done case-insensitively.
    """
    user_count = User.query \<commit_msg>Fixed method call.<commit_after># -*- coding: utf-8 -*-

"""
byceps.blueprints.user.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2014 <NAME>
"""

from datetime import datetime

from flask import abort, g, request, session, url_for

from ...config import get_site_mode, SiteMode
from ...database import db
from ...mail import mail
from ...util.framework import create_blueprint, flash_error, flash_success
from ...util.image import create_thumbnail, Dimensions, \
    guess_type as guess_image_type, read_dimensions
from ...util.templating import templated
from ...util import upload
from ...util.views import redirect_to, respond_no_content

from ..authorization.models import Role
from ..terms.models import Consent, ConsentContext

from .forms import AvatarImageUpdateForm, CreateForm, LoginForm
from .models import NewsletterSubscription, NewsletterSubscriptionState, User, \
    VerificationToken, VerificationTokenPurpose


MAXIMUM_AVATAR_IMAGE_DIMENSIONS = Dimensions(110, 150)


blueprint = create_blueprint('user', __name__)


@blueprint.before_app_request
def before_request():
    g.current_user = UserSession.get_user()


@blueprint.route('/<id>')
@templated
def view(id):
    """Show a user's profile."""
    user = find_user_by_id(id)
    return {'user': user}


@blueprint.route('/create')
@templated
def create_form(errorneous_form=None):
    """Show a form to create a user."""
    form = errorneous_form if errorneous_form else CreateForm()
    return {'form': form}


@blueprint.route('/', methods=['POST'])
def create():
    """Create a user."""
    form = CreateForm(request.form)
    if not form.validate():
        return create_form(form)

    screen_name = form.screen_name.data
    email_address = form.email_address.data.lower()
    password = form.password.data
    consent_to_terms = form.consent_to_terms.data
    subscribe_to_newsletter = form.subscribe_to_newsletter.data

    if is_screen_name_already_assigned(screen_name):
        flash_error(
            'Dieser Benutzername ist bereits einem Benutzerkonto zugeordnet.')
        return create_form(form)

    if is_email_address_already_assigned(email_address):
        flash_error(
            'Diese E-Mail-Adresse ist bereits einem Benutzerkonto zugeordnet.')
        return create_form(form)

    user = User.create(screen_name, email_address, password)
    db.session.add(user)

    verification_token = VerificationToken(
        user, VerificationTokenPurpose.email_address_confirmation)
    db.session.add(verification_token)

    terms_consent = Consent(user, ConsentContext.account_creation)
    db.session.add(terms_consent)

    newsletter_subscription_state = NewsletterSubscriptionState.requested \
        if subscribe_to_newsletter \
        else NewsletterSubscriptionState.declined
    newsletter_subscription = NewsletterSubscription(user, newsletter_subscription_state)
    db.session.add(newsletter_subscription)

    board_user_role = Role.query.get('board_user')
    user.roles.add(board_user_role)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        flash_error('Das Benutzerkonto für "{}" konnte nicht angelegt werden.',
                    user.screen_name)
        return create_form(form)

    db.session.commit()

    send_email_address_confirmation_email(user, verification_token)

    flash_success('Das Benutzerkonto für "{}" wurde angelegt.',
                  user.screen_name)
    return redirect_to('.view', id=user.id)


def is_screen_name_already_assigned(screen_name):
    return do_users_matching_filter_exist(User.screen_name, screen_name)


def is_email_address_already_assigned(email_address):
    return do_users_matching_filter_exist(User.email_address, email_address)


def do_users_matching_filter_exist(model_attribute, search_value):
    """Return `True` if any users match the filter.

    Comparison is done case-insensitively.
    """
    user_count = User.query \
{'fraction_non_alphanumeric': 0.0982274741506647, 'fraction_numerical': 0.003692762186115214, 'mean_word_length': 3.951249238269348, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '808165', 'n_tokens_mistral': 2499, 'n_tokens_neox': 2414, 'n_words': 522}