Skip to content
Snippets Groups Projects
views.py 2.23 KiB
import random
import string

from django import forms
from django.forms import fields
from django.core.exceptions import ValidationError
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.safestring import mark_safe

from shares.models import Share, SHARE_URL, SHARE_FILE
import hashlib
from netguru.settings import SECRET_KEY


def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode('utf-8') + SECRET_KEY.encode('utf-8')).hexdigest()


# Cut off O, I and S so that the user doesn't confuse them with 0, 1 and 5 respectively
CHARACTERS_TO_USE = string.ascii_uppercase.replace('O', '').replace('I', '').replace('S',
                                                                                     '') + string.digits


def random_password() -> str:
    """Generate a eight character reasonably safe passwordpy"""
    return ''.join(random.choice(CHARACTERS_TO_USE) for i in range(6))


class AddShareURLForm(forms.Form):
    url = fields.CharField(label='URL', required=False)
    file = fields.FileField(label='File', required=False)

    def clean(self):
        cleaned_data = super().clean()
        if not cleaned_data.get('url') and not cleaned_data.get('file'):
            raise ValidationError('You have to provide either an URL or a file!')
        return cleaned_data


@login_required
def add_share(request):
    data_added = None

    if request.method == 'POST':
        form = AddShareURLForm(request.POST, request.FILES)
        if form.is_valid():
            data_added = {'password': random_password()}
            pwd_hash = hash_password(data_added['password'])
            data = form.cleaned_data
            if data.get('url'):
                # Create a URL resource
                share = Share(creator=request.user,
                              resource=data['url'],
                              pwd_hash=pwd_hash,
                              share_type=SHARE_URL)
                share.save()
                data_added['url'] = mark_safe(f'https://{request.get_host()}/shares/{share.id}')
            else:
                pass
    else:
        form = AddShareURLForm()

    return render(request, 'share/add.html', {'form': form, 'added': data_added})