Exemple #1
0
def handle_registration(request):
    serializer = RegisterRequestSerializer(data=request.data)
    if not serializer.is_valid():
        raise CredoAPIException(str(serializer.errors))
    vd = serializer.validated_data

    user = None

    try:
        u = User.objects.get(email=vd['email'])
        if not u.is_active:
            user = u
            user.team = Team.objects.get_or_create(name=vd['team'])[0]
            user.display_name = vd['display_name']
            user.key = generate_token()
            user.username = vd['username']
            user.email_confirmation_token = generate_token()
            user.set_password(vd['password'])
            user.save()
            logger.info(
                'Updating user info and resending activation email to user {}'.
                format(user))
    except User.DoesNotExist:
        logger.info('Creating new user {} {}'.format(vd['username'],
                                                     vd['display_name']))

    if not user:
        try:
            user = User.objects.create_user(
                team=Team.objects.get_or_create(name=vd['team'])[0],
                display_name=vd['display_name'],
                key=generate_token(),
                password=vd['password'],
                username=vd['username'],
                email=vd['email'],
                is_active=False,
                email_confirmation_token=generate_token(),
            )
        except IntegrityError:
            logger.warning('User registration failed, IntegrityError', vd)
            raise RegistrationException(
                "User with given username or email already exists.")

    if user:
        logger.info('Sending registration email to {}'.format(user.email))
        try:
            send_registration_email(user.email, user.email_confirmation_token,
                                    user.username, user.display_name)
        except Exception as e:
            logger.exception(e)
            logger.error(
                'Failed to send confirmation email for user {} ({})'.format(
                    user, user.email))
Exemple #2
0
def handle_mapping_export(request):
    try:
        serializer = MappingExportRequestSerializer(data=request.data)
    except ParseError:
        raise CredoAPIException(
            "Could not parse request body as a valid JSON object")

    if not serializer.is_valid():
        raise CredoAPIException(str(serializer.errors))
    vd = serializer.validated_data

    job_id = generate_token()[:16]

    s3 = boto3.resource(
        "s3",
        aws_access_key_id=settings.S3_ACCESS_KEY_ID,
        aws_secret_access_key=settings.S3_SECRET_KEY,
        endpoint_url=settings.S3_ENDPOINT_URL,
    )

    url = s3.meta.client.generate_presigned_url(
        ClientMethod="get_object",
        ExpiresIn=settings.S3_EXPIRES_IN,
        Params={
            "Bucket": settings.S3_BUCKET,
            "Key": "mapping_export_{}.json".format(job_id),
        },
    )

    mapping_export.delay(job_id, vd["mapping_type"])

    logger.info("Exporting mapping by request from {}, type {}, id {}".format(
        request.user, vd["mapping_type"], job_id))

    return {"url": url}
Exemple #3
0
def handle_data_export(request):
    serializer = DataExportRequestSerializer(data=request.data)
    if not serializer.is_valid():
        raise CredoAPIException(str(serializer.errors))
    vd = serializer.validated_data

    job_id = generate_token()[:16]

    s3 = boto3.resource('s3',
                        aws_access_key_id=settings.S3_ACCESS_KEY_ID,
                        aws_secret_access_key=settings.S3_SECRET_KEY,
                        endpoint_url=settings.S3_ENDPOINT_URL)

    url = s3.meta.client.generate_presigned_url(
        ClientMethod='get_object',
        ExpiresIn=86400,  # 24h
        Params={
            'Bucket': 'credo_test',
            'Key': 'export_{}.json'.format(job_id)
        })

    os.system(
        'python manage.py s3_data_export --id {} --since {} --until {} --limit {} --type {}&'
        .format(job_id, vd['since'], vd['until'], vd['limit'],
                vd['data_type']))

    logger.info(
        'Exporting data by request from {}, type {}, since {}, until {}, limit {}, id {}'
        .format(request.user, vd['data_type'], vd['since'], vd['until'],
                vd['limit'], job_id))
    return {'url': url}
Exemple #4
0
def contest_create(request):
    form = ContestCreationForm(request.POST or None)
    if form.is_valid():
        cd = form.cleaned_data
        contest_id = generate_token()[:8]

        filter_parameters = {
            "avbrightness_max": cd["avbrightness_max"],
            "maxbrightness_min": cd["maxbrightness_min"],
        }

        start_time = cd["start_time"]

        start_time = start_time.replace(
            year=start_time.year,
            month=start_time.month,
            day=start_time.day,
            hour=start_time.hour,
            minute=start_time.minute,
            second=0,
            microsecond=0,
        )
        start_timestamp = (time.mktime(start_time.timetuple())) * 1000

        duration = cd["duration"] * 3600 * 1000  # Hours -> milliseconds

        id_blacklist = [
            u.id for u in User.objects.filter(
                username__in=[n.strip() for n in cd["blacklist"].split(",")])
        ]

        calculate_contest_results.delay(
            contest_id,
            cd["name"],
            cd["description"],
            start_timestamp,
            duration,
            cd["limit"],
            id_blacklist,
            filter_parameters,
        )

        return redirect("contest_view", contest_id=contest_id)
    return render(request, "credoweb/contest_create.html", {"form": form})