Exemplo n.º 1
0
    def form_valid(self, form):
        vocation = form.cleaned_data.get('vocation')
        sex = form.cleaned_data.get('sex')
        sort_by = form.cleaned_data.get('sortby')
        sort_mode = form.cleaned_data.get('order')

        vocation_id = ChoiceTextToID(vocation, GetSetting('VOCATION_INFO'))
        sex_id = ChoiceTextToID(sex, GetSetting('SEX_INFO'))

        sort_by_prefix = '-' if sort_mode == 'desc' else ''

        players = Player.objects.all()

        if vocation_id:
            players = players.filter(vocation=vocation_id)

        if sex_id:
            players = players.filter(sex=sex_id)

        if sort_by:
            order_options = [sort_by_prefix + sort_by]

            if sort_by != 'name':
                order_options.append('name')
        else:
            order_options = GetSetting('STATS_DEFAULT_ORDER')

        players = players.order_by(*order_options)

        return self.render_view(form, players)
Exemplo n.º 2
0
def get_password_help_text():
    return _(
        'Password needs to be from {min} to {max} characters length.\n'
        'It can\'t be too common or contain only numbers.'
    ).format(
        min=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max=GetSetting('INPUT_PASSWORD_MAX_LENGTH')
    )
Exemplo n.º 3
0
def get_name_help_text():
    return _(
        'Account name needs to be from {min} to {max} characters length.\n'
        'Allowed characters are: a-z, A-Z, 0-9.'
    ).format(
        min=GetSetting('INPUT_USERNAME_MIN_LENGTH'),
        max=GetSetting('INPUT_USERNAME_MAX_LENGTH')
    )
Exemplo n.º 4
0
class EmailVerificationForm(CustomModelForm):
    autofocus_post_clean = False

    class Meta:
        model = Account
        fields = ['name', 'activation_key']

    name = CharField(
        required=False,
        min_length=GetSetting('INPUT_USERNAME_MIN_LENGTH'),
        max_length=GetSetting('INPUT_USERNAME_MAX_LENGTH'),
        widget=forms.HiddenInput(),
    )

    activation_key = CharField(
        autofocus=True,
        label=_('Verification key'),
        help_text=_(
            'Verification key can be found in email box after account creation.'
        ),
        placeholder=_('Copy your verification key here'),
        min_length=64,
        max_length=64,
        widget=forms.TextInput(),
    )

    def save(self, commit=True):
        self.instance.set_email_activated()
        return self.instance

    def clean(self):
        super(EmailVerificationForm, self).clean()

        name = self.cleaned_data.get('name')
        activation_key = self.cleaned_data.get('activation_key')

        try:
            account = Account.objects.get_by_natural_key(name)
        except Account.DoesNotExist:
            self.add_error(None,
                           _('Account doesn\'t exist, verification failed.'))
        else:
            if account.email_activated:
                self.add_error(None, _('Your email is already activated.'))
            elif not account.email_activation_key or not account.email_key_expires:
                self.add_error(None, _('Your email can\'t be activated.'))
            elif timezone.now() > account.email_key_expires:
                self.add_error(None, _('Email verification time expired.'))
            elif account.email_activation_key != activation_key:
                self.add_error(None, _('Verification key is wrong.'))
            else:
                self.instance = account

        return self.cleaned_data
Exemplo n.º 5
0
class LoginForm(AutoFocusFormMixin, forms.Form):

    next = CharField(
        required=False,
        max_length=255,
        widget=forms.HiddenInput(),
    )

    username = CharField(
        autofocus=True,
        min_length=GetSetting('INPUT_USERNAME_MIN_LENGTH'),
        max_length=GetSetting('INPUT_USERNAME_MAX_LENGTH'),
        label=_('Username'),
        placeholder=_('Type your username here'),
        widget=forms.TextInput(),
    )

    password = CharField(
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        label=_('Password'),
        placeholder=_('Type your password here'),
        widget=forms.PasswordInput(),
    )

    def clean(self):
        super(LoginForm, self).clean()

        if self.is_valid():
            username = self.cleaned_data.get('username')
            password = self.cleaned_data.get('password')

            try:
                account = Account.objects.get_by_natural_key(username)
            except Account.DoesNotExist:
                self.add_form_error(
                    _('Account with that name does not exist.'), 'username')
            else:
                if not account.user.check_password(password):
                    self.add_form_error(_('Password does not match.'),
                                        'password')
                elif not account.user.is_active:
                    self.add_form_error(
                        _('This account is blocked or deleted.'))
                else:
                    self.account = account

        return self.cleaned_data
Exemplo n.º 6
0
class CreateForm(forms.ModelForm):
    class Meta:
        model = Player
        fields = ['name', 'sex', 'vocation', 'town_id']
        widgets = {
            'sex': RadioSelect(),
            'vocation': RadioSelect(),
            'town_id': RadioSelect(),
        }

    name = CharField(
        autofocus=True,
        min_length=GetSetting('CHARACTER_NAME_MIN_LENGTH'),
        max_length=GetSetting('CHARACTER_NAME_MAX_LENGTH'),
        validators=[
            RegexValidator(GetSetting('CHARACTER_NAME_REGEX'),
                           _('Character name contains illegal characters.'),
                           'invalid-name')
        ],
    )

    def clean(self):
        data = super(CreateForm, self).clean()

        if not self.is_valid():
            return data

        name = data.get('name')

        if not self.account.can_add_character():
            self.add_error(None, _('You can\'t create more characters.'))
            return data

        fixed_name = character_name_fixer(name)

        if name != fixed_name:
            self.add_error(
                'name',
                _('Character name was corrected.\n'
                  'You can continue if that is okey.'))
            self.corrected_name = fixed_name
            return data

        if Player.objects.name_exists(fixed_name):
            self.add_error('name', _('That name is already being used.'))
            return data

        return data
Exemplo n.º 7
0
 def __call__(self, request):
     from bs4 import BeautifulSoup
     response = self.get_response(request)
     if isinstance(response, TemplateResponse):
         text = response.content.decode()
         soup = BeautifulSoup(text, GetSetting('BEAUTIFULSOUP_PARSER'))
         prettyHTML = soup.prettify()
         response.content = prettyHTML.encode()
     return response
Exemplo n.º 8
0
    def get(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            return self.form_valid(form)

        # gdy nie został naciśnięty przycisk filtrowania
        # lub próbujemy podać ręcznie niewłaściwe dane

        players = Player.objects.order_by(*GetSetting('STATS_DEFAULT_ORDER'))
        return self.render_view(form, players)
Exemplo n.º 9
0
    def get(self, request, *args, **kwargs):
        account = request.user.account

        kwargs.update({
            'account': account,
            'players': account.players.all(),
            'players_count': account.players.count(),
            'can_add_player': account.can_add_character(),
            'players_max': GetSetting('MAX_PLAYERS_PER_ACCOUNT'),
        })

        return super(ProfileView, self).get(request, *args, **kwargs)
Exemplo n.º 10
0
    def render_view(self, form, players):
        # ustawiamy limit wyświetlanych rekordów
        total_players = players.count()
        players = players[:GetSetting('STATS_RECORDS_LIMIT', 20)]
        players_count = players.count()

        return self.render_to_response(
            self.get_context_data(
                form=form,
                players=players,
                players_count=players_count,
                total_players=total_players,
            )
        )
Exemplo n.º 11
0
class RegisterForm(CustomModelForm):
    autofocus_post_clean = True

    class Meta:
        model = Account
        fields = ['name', 'password', 'password_repeat', 'email']

    name = CharField(
        autofocus=True,
        label=_('Account name'),
        placeholder=_('Type your account name here'),
        help_text=Account._meta.get_field('name').help_text,
        min_length=GetSetting('INPUT_USERNAME_MIN_LENGTH'),
        max_length=GetSetting('INPUT_USERNAME_MAX_LENGTH'),
        widget=TextInput(),
    )

    password = CharField(
        label=_('Password'),
        placeholder=_('Type your password here'),
        help_text=Account._meta.get_field('password').help_text,
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        widget=PasswordInput(),
    )

    password_repeat = CharField(
        label=_('Repeat password'),
        placeholder=_('Repeat your password here'),
        help_text=_('This password needs to match above.'),
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        widget=PasswordInput(),
    )

    email = EmailField(
        label=_('Email address'),
        placeholder=_('Type your email address here'),
        help_text=Account._meta.get_field('email').help_text,
        widget=EmailInput(),
    )

    def save(self, commit=True):
        self.instance = Account.objects.create_account(
            name=self.cleaned_data.get('name'),
            password=self.cleaned_data.get('password'),
            email=self.cleaned_data.get('email'))
        return self.instance

    def clean(self):
        super(RegisterForm, self).clean()

        password = self.cleaned_data.get('password')
        password_repeat = self.cleaned_data.get('password_repeat')

        try:
            validate_password(password)
        except ValidationError as e:
            self.add_error('password', e.messages)

        if password != password_repeat:
            self.add_error('password_repeat',
                           _('You didn\'t repeat your password correctly.'))

        return self.cleaned_data
Exemplo n.º 12
0
class PasswordChangeForm(CustomModelForm):
    autofocus_post_clean = False

    class Meta:
        model = Account
        fields = ['current_password', 'new_password', 'new_password_repeat']

    current_password = CharField(
        autofocus=True,
        label=_('Current password'),
        placeholder=_('Type your current password here'),
        help_text=_(
            'For security reasons you need to type your current password.'),
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        widget=forms.PasswordInput(),
    )

    new_password = CharField(
        label=_('New password'),
        placeholder=_('Type your new password here'),
        help_text=get_password_help_text(),
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        widget=forms.PasswordInput(),
    )

    new_password_repeat = CharField(
        label=_('Repeat new password'),
        placeholder=_('Repeat your new password here'),
        help_text=_('This password needs to match above.'),
        min_length=GetSetting('INPUT_PASSWORD_MIN_LENGTH'),
        max_length=GetSetting('INPUT_PASSWORD_MAX_LENGTH'),
        widget=forms.PasswordInput(),
    )

    def save(self, commit=True):
        self.instance.change_password(self.cleaned_data.get('new_password'))
        return self.instance

    def clean(self):
        super(PasswordChangeForm, self).clean()

        current_password = self.cleaned_data.get('current_password')
        new_password = self.cleaned_data.get('new_password')
        new_password_repeat = self.cleaned_data.get('new_password_repeat')

        if not self.instance.check_password(current_password):
            self.add_error('current_password',
                           _('Your current password is other.'))

        try:
            validate_password(new_password)
        except ValidationError as e:
            self.add_error('new_password', e.messages)

        if new_password != new_password_repeat:
            self.add_error('new_password_repeat',
                           _('You didn\'t repeat new password correctly.'))

        return self.cleaned_data
Exemplo n.º 13
0
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rpgsite.settings")

application = get_wsgi_application()

from rpgsite.tools import GetSetting

if GetSetting('CREATE_ROOT_ON_INIT', True):
    from apps.accounts.models import Account
    from rpgsite.tools import LogError, LogInfo
    if not Account.objects.name_exists('admin'):
        try:
            account = Account.objects.create_admin(
                name = 'admin',
                password = '******',
                email = '*****@*****.**',
            )
            account.players.create(
                name = 'Caday',
                group_id = '3', # God
                lookbody = 101,
                lookfeet = 94,
                lookhead = 82,
Exemplo n.º 14
0
class Account(models.Model):

    objects = AccountManager()

    user = models.OneToOneField('auth.User', models.CASCADE, related_name='account')

    name = models.CharField(
        _('name'),
        max_length = 32,
        unique = True,
        help_text = get_name_help_text(),
        validators = [
            RegexValidator(
                regex = GetSetting('INPUT_USERNAME_REGEX'),
                message = _('Account name may contain only english letters and digits.')
            ),
            MinLengthValidator(GetSetting('INPUT_USERNAME_MIN_LENGTH')),
            MaxLengthValidator(GetSetting('INPUT_USERNAME_MAX_LENGTH'))
        ],
        error_messages = {
            'unique': _("An account with that name already exists."),
        },
    )

    password = models.CharField(
        _('hashed password'),
        max_length = 40,
        help_text = get_password_help_text(),
    )

    email = models.EmailField(
        _('email address'),
        max_length = 255,
        help_text = _('This email address will be used for account recovery.'),
    )

    creation = models.IntegerField(
        _('creation timestamp'),
        default = GetCurrentTimestamp,
        editable = False,
    )

    def get_creation_display(self):
        return datetime.fromtimestamp(self.creation)

    get_creation_display.short_description = _('date created')

    access = models.IntegerField(
        _('access level'),
        default = 1,
        choices = (
            (1, _('Normal')),
            (2, _('Tutor')),
            (3, _('Senior Tutor')),
            (4, _('Gamemaster')),
            (5, _('God')),
        ),
        help_text = _('This field describes the access level of an account.'),
        db_column = 'type',
    )

    secret = models.CharField(
        _('secret auth token'),
        blank = True,
        null = True,
        max_length = 16,
        help_text = _('Secret token used by a game server to authenticate accounts.'),
    )

    premdays = models.IntegerField(
        _('premium days'),
        default = 0,
        help_text = _('Number of premium days left.'),
    )

    lastday = models.PositiveIntegerField(
        _('last premium day'),
        default = 0,
        help_text = _('This field is a helper for premium days calculations.'),
    )

    class Meta:
        managed = False
        db_table = 'accounts'

    def __str__(self):
        return self.name

    @staticmethod
    def make_password_sha1(raw_password):
        return hashlib.sha1(raw_password.encode('utf-8')).hexdigest()

    def change_password(self, raw_password):
        self.set_password(raw_password)
        self.save()
        self.user.set_password(raw_password)
        self.user.save()

    def check_password(self, raw_password):
        return self.user.check_password(raw_password)

    def set_password(self, raw_password):
        self.password = Account.make_password_sha1(raw_password)

    def can_add_character(self):
        return self.players.count() < GetSetting('MAX_PLAYERS_PER_ACCOUNT')
Exemplo n.º 15
0
 def can_add_character(self):
     return self.players.count() < GetSetting('MAX_PLAYERS_PER_ACCOUNT')
Exemplo n.º 16
0
 def filter(self, record):
     return GetSetting('LOG_ENABLED', True)