Example #1
0
def add_delete_category(request, user):
    """
    @api {post} /authe/profile/category/add_delete/ Add or delete category of user
    @apiName add_delete_category
    @apiGroup Auth
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {Number} category_id ID of category
    @apiSuccess {Json} result Json representation of polls.
    """
    try:
        try:
            category = Category.objects.get(id=request.POST["category_id"])
        except:
            return http.code_response(code=codes.CATEGORY_NOT_FOUND,
                                      message=messages.CATEGORY_NOT_FOUND)
        user_category, created = UserCategory.objects.get_or_create(
            user=user, category=category)
        if not created:
            user_category.is_active = not user_category.is_active
            user_category.save()
        return http.ok_response()
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #2
0
def sms_register(request):
    """
    @api {post} /authe/sms_register/ Sms Registration method
    @apiName sms_register
    @apiGroup Authe
    @apiHeader {String} Csrf-Token CSRF token.
    @apiParam {String} phone Phone of user.
    @apiParam {Number} age Age of user [optional].
    @apiSuccess {Object} Json with code
    """
    phone = request.POST["phone"].lower()
    # Validation phone number
    try:
        phone_object = phonenumbers.parse(phone, None)
        if not phonenumbers.is_valid_number(phone_object):
            return http.code_response(code=codes.PHONE_INCORRECT,
                                      message=messages.PHONE_INCORRECT)
    except:
        return http.code_response(code=codes.PHONE_INCORRECT,
                                  message=messages.PHONE_INCORRECT)

    if User.objects.filter(phone=phone, is_active=True).exists():
        return http.code_response(code=codes.PHONE_USED,
                                  message=messages.PHONE_USED)
    else:
        code = password.generate_sms_code()
        Activation.objects.generate(username=phone, code=code)
        tasks.send_message(phone,
                           settings.SMS_ACTIVATION_TEXT.format(password=code))
    return http.ok_response()
Example #3
0
def sms_resend(request):
    """
    @api {post} /authe/sms_resend/ Sms resend method
    @apiName sms_resend
    @apiGroup Authe
    @apiHeader {String} Csrf-Token CSRF token.
    @apiParam {String} phone Phone of user.
    @apiSuccess {Object} Json with code
    """
    try:
        phone = request.POST["phone"].lower()
        # Validation phone number
        try:
            phone_object = phonenumbers.parse(phone, None)
            if not phonenumbers.is_valid_number(phone_object):
                return http.code_response(code=codes.PHONE_INCORRECT,
                                          message=messages.PHONE_INCORRECT)
        except:
            return http.code_response(code=codes.PHONE_INCORRECT,
                                      message=messages.PHONE_INCORRECT)
        code = password.generate_sms_code()
        Activation.objects.generate(username=phone, code=code)
        tasks.send_message(phone,
                           settings.SMS_ACTIVATION_TEXT.format(password=code))
        return http.ok_response()
    except Exception as e:
        logger.error(e)
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #4
0
def reset_password(request):
    """
    @api {post} /api/authe/reset/ Reset password method
    @apiName reset_password
    @apiGroup Authe
    @apiHeader {String} Csrf-Token CSRF token.
    @apiParam {String} username Email of user CHOSEN ON REGISTRATION.
    @apiSuccess {Object} result Json with code.
    """
    try:
        try:
            validate_email(request.POST["username"])
        except:
            return http.code_response(code=codes.INVALID_USERNAME,
                                      message=messages.INVALID_USERNAME)
        try:
            user = User.objects.get(email=request.POST['username'])
        except:
            return http.code_response(code=codes.USERNAME_NOT_FOUND,
                                      message=messages.USER_NOT_FOUND_EMAIL)
        token = str(user.id) + password.generate_password(length=30)
        ResetPasswordRequest.objects.create(user=user, token=token)
        try:
            user.email_reset_password(token=token)
        except Exception as e:
            logger.error(e)
            return http.code_response(code=codes.EMAIL_SERVICE_ERROR,
                                      message=messages.EMAIL_SERVICE_ERROR)
        return http.ok_response()
    except Exception as e:
        logger.error(e)
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #5
0
def change_password(request, user):
    """
    @api {post} /authe/change_password/ Change password method
    @apiName change_password
    @apiGroup Authe
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {String} current_password Current password of user.
    @apiParam {String} new_password New password of user.
    @apiSuccess {Object} result Json with response code.
    """
    try:
        current_password = request.POST.get('current_password', '')
        new_password = request.POST.get('new_password', '')
        if not user.check_password(current_password):
            return http.code_response(
                code=codes.INCORRECT_CURRENT_PASSWORD,
                message=messages.INCORRECT_CURRENT_PASSWORD)
        if len(new_password) < settings.PASSWORD_LENGTH:
            return http.code_response(
                code=codes.PASSWORD_LENGTH_ERROR,
                message=messages.PASSWORD_LENGTH_ERROR.format(
                    len(new_password)))
        user.set_password(new_password)
        user.save()
        return http.ok_response()
    except Exception as e:
        logger.error(e)
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #6
0
def update_push(request, user):
    for param_name in request.POST.getlist('param_names'):
        if param_name.startswith('baccarat'):
            game_type = param_name[len('baccarat') + 1:] + "_push"
            user_limit = BaccaratUserLimit.objects.get_default(user)
            setattr(user_limit, game_type, request.POST["value"].lower() == "true")
            user_limit.save()
        if param_name.startswith('poker'):
            game_type = param_name[len('poker') + 1:] + "_push"
            user_limit = PokerUserLimit.objects.get_default(user)
            setattr(user_limit, game_type, request.POST["value"].lower() == "true")
            user_limit.save()
        if param_name.startswith('wheel'):
            game_type = param_name[len('wheel') + 1:] + "_push"
            user_limit = WheelUserLimit.objects.get_default(user)
            setattr(user_limit, game_type, request.POST["value"].lower() == "true")
            user_limit.save()
        if param_name.startswith('warbets'):
            game_type = param_name[len('warbets') + 1:] + "_push"
            user_limit = WarbetsUserLimit.objects.get_default(user)
            setattr(user_limit, game_type, request.POST["value"].lower() == "true")
            user_limit.save()
        if param_name.startswith('dice_duel'):
            game_type = param_name[len('dice_duel') + 1:] + "_push"
            user_limit = DiceDuelUserLimit.objects.get_default(user)
            setattr(user_limit, game_type, request.POST["value"].lower() == "true")
            user_limit.save()
    return http.ok_response()
Example #7
0
def logout(request, user, token_string):
    """
    """
    try:
        if token.delete_token(token_string):
            return http.ok_response()
        else:
            return http.code_response(code=codes.TOKEN_INVALID,
                                      message=messages.TOKEN_INVALID)
    except Exception as e:
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #8
0
def poll_approve(request, user):
    """
    @api {post} /moderators/polls/approve/ Poll approve method
    @apiName poll_approve
    @apiGroup Moderators
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {String} poll_id id of poll.
    @apiParam {String} status status of poll.
    @apiSuccess {Object} result http ok response.
    """
    try:
        try:
            poll = Poll.objects.get(id=request.POST["poll_id"])
        except:
            return http.code_response(code=codes.POLL_NOT_FOUND,
                                      message=messages.POLL_NOT_FOUND)
        try:
            status = int(request.POST["status"])
        except:
            return http.code_response(code=codes.INVALID_POLL_STATUS,
                                      message=messages.INVALID_POLL_STATUS)

        if status in [
                Constants.UNKNOWN, Constants.APPROVED, Constants.REJECTED
        ]:
            poll.status = status
            poll.save()
            return http.ok_response()
        elif status == 10:
            poll.is_delete = True
            poll.save()
            return http.ok_response()
        else:
            return http.code_response(code=codes.INVALID_POLL_STATUS,
                                      message=messages.INVALID_POLL_STATUS)
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #9
0
def update_token(request, user):
    if User.objects.filter(push_token=request.POST["push_token"]).exclude(pk=user.pk).exists():
        other = User.objects.filter(push_token=request.POST["push_token"]).exclude(pk=user.pk)[0]
        try:
            email.delay(settings.ADMINS_LIST,
                    u"ВНИМАНИЕ! Дублирующий push #{}".format(user.phone),
                    u"ВНИМАНИЕ! Дублирующий push у {} с {}".format(user.phone, other.phone))
        except:
            pass
    User.objects.filter(push_token=request.POST["push_token"]).update(push_token="")
    user.push_token = request.POST["push_token"]
    user.save()
    return http.ok_response()
Example #10
0
def create_cases(request):
    try:
        cases = request.POST.getlist("cases[]", [])
        print(cases)
        if len(cases) == 0:
            return http.code_response(code=codes.NO_CASES,
                                      message=messages.NO_CASES)

        new_cases = []
        for case in cases:
            case = json.loads(case)
            full_name = case["full_name"]
            iin = case["iin"]
            address = case["address"]
            address_residential = case["address_residential"]
            contacts = case["contacts"]
            status = case["status"]
            place_of_work = case["place_of_work"]
            occupation = case["occupation"]
            income = case["income"]
            health_condition = case["health_condition"]
            description = case["description"]
            new_case = None
            if full_name and iin and address and address_residential and \
                contacts and status and place_of_work and occupation and \
                income and health_condition and description:
                new_case, _ = Case.objects.get_or_create(
                    full_name=full_name,
                    iin=iin,
                    address=address,
                    address_residential=address_residential,
                    contacts=contacts,
                    status=status,
                    place_of_work=place_of_work,
                    occupation=occupation,
                    income=income,
                    health_condition=health_condition,
                    description=description)
            else:
                return http.code_response(
                    code=codes.MISSING_REQUIRED_PARAMS,
                    message=messages.MISSING_REQUIRED_PARAMS)
            print(new_case)

            parent_case = new_cases[0].id if len(
                new_cases) > 0 else new_case.id
            new_case.parent_case = parent_case
            new_case.save()
            new_cases.append(new_case)

        return http.ok_response()
Example #11
0
def logout(request, user, token_string):
    """
    @api {post} /authe/logout/ Logout method
    @apiName logout
    @apiGroup Authe
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiSuccess {Object} result Json with response code.
    """
    try:
        if token.delete_token(token_string):
            return http.ok_response()
        else:
            return http.code_response(code=codes.TOKEN_INVALID,
                                      message=messages.TOKEN_INVALID)
    except Exception as e:
        logger.error(e)
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #12
0
def update_user_categories(request, user):
    """
    @api {post} /authe/profile/categories/ Add or delete categories of user
    @apiName update_user_categories
    @apiGroup Auth
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {Number} category_ids[] IDs of categories
    @apiSuccess {Json} result Json representation of polls.
    """
    try:
        category_ids = request.POST.getlist("category_ids[]")
        if len(category_ids) != Category.objects.filter(
                id__in=category_ids, is_active=True).count():
            return http.code_response(code=codes.CATEGORIES_DOESNT_MATCH,
                                      message=messages.CATEGORIES_DOESNT_MATCH)
        UserCategory.objects.add_categories(user, category_ids)
        return http.ok_response()
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #13
0
def delete_article(request, user):
    """
    @api {post} /moderators/articles/delete/ Delete articles
    @apiName delete_articles
    @apiGroup Moderators
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {Number} article_id ID of article to delete
    @apiSuccess {Json} result Json representation of poll.
    """
    try:
        try:
            article = Article.objects.get(id=request.POST["article_id"])
        except:
            return http.code_response(code=codes.BAD_REQUEST,
                                      message=messages.POLL_NOT_FOUND)
        article.is_active = False
        article.save()
        return http.ok_response()
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #14
0
def category_delete(request, user):
    """
    @api {post} /moderators/category/delete/ Category delete method
    @apiName category_delete
    @apiGroup Moderators
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {Number} category_id Id of category.
    @apiSuccess {Json} result http ok response.
    """
    try:
        try:
            category = Category.objects.get(id=request.POST['category_id'])
        except:
            return http.code_response(code=codes.CATEGORY_NOT_FOUND,
                                      message=messages.CATEGORY_NOT_FOUND)
        children = category.get_descendants(include_self=True)
        children.update(is_active=False)
        return http.ok_response()
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #15
0
def category_update(request, user):
    """
    @api {post} /moderators/category/update/ Category update method
    @apiName category_update
    @apiGroup Moderators
    @apiHeader {String} Csrf-Token CSRF token.
    @apiHeader {String} Auth-Token Authentication token.
    @apiParam {Number} category_id ID of category.
    @apiParam {String} category_name Name of category.
    @apiParam {Number} parent_id Parent of category.
    @apiSuccess {Json} result Json representation of category.
    """
    try:
        try:
            category = Category.objects.get(
                id=int(request.POST['category_id']))
        except:
            return http.code_response(code=codes.CATEGORY_NOT_FOUND,
                                      message=messages.CATEGORY_NOT_FOUND)
        if request.POST.get("parent_id", ""):
            try:
                parent = Category.objects.get(
                    id=int(request.POST['parent_id']))
            except:
                return http.code_response(code=codes.CATEGORY_NOT_FOUND,
                                          message=messages.CATEGORY_NOT_FOUND)
            category.parent = parent
        if request.POST.get("category_name", ""):
            try:
                category.name = request.POST['category_name']
            except:
                return http.code_response(code=codes.CATEGORY_NOT_FOUND,
                                          message=messages.CATEGORY_NOT_FOUND)
        category.save()
        return http.ok_response()
    except Exception as exc:
        logger.error(exc)
        return http.code_response(codes.SERVER_ERROR, message=str(exc))
Example #16
0
                if result.get("comment_text") is not None:
                    comment_text = result["comment_text"]
                if result.get("timestamp") is not None:
                    timestamp = result["timestamp"]
                if result.get("is_done") is not None:
                    is_done = result["is_done"]
                user_department = UserDepartment.objects.get(user=user)
                comment, _ = Comment.objects.get_or_create(user=user,
                                                           text=comment_text,
                                                           timestamp=timestamp)
                result_case, _ = ResultCase.objects.get_or_create(
                    case=current_case,
                    user_department=user_department,
                    comment=comment,
                    is_done=is_done,
                    timestamp=timestamp)
                print(result_case)

            if user.user_type == COMMISSION_HEAD and case.get(
                    "is_approved") is not None:
                current_case.is_approved = case["is_approved"]

            print(current_case)
            current_case.save()
            new_cases.append(current_case)

        return http.ok_response()

    except Exception as e:
        return http.code_response(codes.SERVER_ERROR, message=str(e))
Example #17
0
def send_feedback(request, user):
    Feedback.objects.create(message=request.POST["message"], user=user)
    email.delay(settings.ADMINS_LIST, u'Запрос в службу поддержки {}'.format(user.phone), request.POST["message"])
    return http.ok_response()
Example #18
0
def reset(request, user):
    BaccaratUserLimit.objects.reset(user)
    PokerUserLimit.objects.reset(user)
    WarbetsUserLimit.objects.reset(user)
    WheelUserLimit.objects.reset(user)
    return http.ok_response()