예제 #1
0
def console_add_response_suspicion(request, org, survey):
    """
    API view to add suspicion reason from a response.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            response_uid = request.POST['response_uid']
            text = request.POST['text']

            response = SurveyResponse.objects.get(survey_uid=survey.survey_uid, response_uid=response_uid)

            response.suspicion_add(
                type = SurveyResponse.SuspectReason.TYPE_USER_DEFINED,
                text = text,
                user_id = request.user.id
            )

            return ApiResponse(status=ApiResponse.ST_SUCCESS, message='Ok').gen_http_response()
        except KeyError:
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST, message='Missing parameters.').gen_http_response()
        except (DoesNotExist_mongo, IndexError, ValueError):
            return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED, message='Invalid parameters.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #2
0
def reset_password_plea_verify(request):
    """
    An API view to check 'forgot password' recovery code. This is used to tell user
    if the code he entered matched or not as he completes entering the code.

    **Type**: GET

    **Authors**: Gagandeep Singh
    """
    country_tel_code = '+91'  #TODO: Set default country_tel_code

    mobile_no = request.GET['username']
    verification_code = request.GET['verification_code']

    actual_username = RegisteredUser.construct_username(
        country_tel_code, mobile_no)

    try:
        passed = UserToken.verify_user_token(username=actual_username,
                                             purpose=UserToken.PUR_PASS_RESET,
                                             value=verification_code)

        if passed:
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='ok').gen_http_response()
        else:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message='Verification failed.').gen_http_response()

    except InvalidRegisteredUser:
        return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED,
                           message='Invalid account.').gen_http_response()
예제 #3
0
def console_account_settings_privinfo_update(request):
    """
    An API view to update registered user private information.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        form = PrivateInfoForm(request.POST)

        if form.is_valid():
            registered_user = request.user.registereduser

            all_ok, errors = form.save(str(registered_user.profile.pk))
            if all_ok:
                return ApiResponse(status=ApiResponse.ST_SUCCESS,
                                   message='ok').gen_http_response()
            else:
                return ApiResponse(status=ApiResponse.ST_PARTIAL_SUCCESS,
                                   message='Success with few ignored errors.',
                                   errors=errors).gen_http_response()
        else:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message='Incomplete submission.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #4
0
def console_survey_save(request, org, survey):
    """
    API view to save survey information.

    .. warning::
        Do not use this view to create new survey.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':

        try:
            from surveys.forms import SurveyEditForm
            form_survey = SurveyEditForm(request.POST, instance=survey)

            if form_survey.is_valid():
                if len(form_survey.changed_data):
                    form_survey.save()
                return ApiResponse(status=ApiResponse.ST_SUCCESS, message='Ok').gen_http_response()
            else:
                errors = dict(form_survey.errors)
                return ApiResponse(status=ApiResponse.ST_FAILED, message='Please correct marked errors.', errors=errors).gen_http_response()
        except Survey.DoesNotExist:
            return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED, message='Invalid survey.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #5
0
def console_bsp_feedback_create(request, org):
    """
    API view to create new BSP feedback form. User submit form data and
    new questionnaire is created.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        form_data = json.loads(request.POST['form_data'])
        translation = json.loads(request.POST['translations'])
        bsp_fdbk_form = BspFeedbackForm.objects.create(
            organization=org,
            title=form_data['title'],
            theme_skin=ThemeSkin.objects.get(
                theme__code=settings.DEFAULT_FORM_THEME['theme_code'],
                code=settings.DEFAULT_FORM_THEME['skin_code']),
            created_by=request.user)

        form_saved = ops.create_update_form(bsp_fdbk_form, form_data,
                                            translation)

        return ApiResponse(status=ApiResponse.ST_SUCCESS,
                           message='Ok',
                           is_ready=form_saved.is_ready,
                           form_id=form_saved.id).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #6
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_brand_create(request, org):
    """
    An API view to create a NEW brand. User fills a form and submit data.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        form_brand = BrandCreateForm(request.POST, request.FILES)

        if form_brand.is_valid():
            form_data = form_brand.cleaned_data

            ops.create_new_brand(form_data, org, request.user.registereduser)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_brand.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #7
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_create(request, org):
    """
    API view to create new BSP for submitted form.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        data = json.loads(request.POST.copy()['data'])
        form_bsp = BusinessServicePointForm(data)

        if form_bsp.is_valid():
            form_bsp.save(organization=org, created_by=request.user)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_bsp.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #8
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_organization_role_create(request, org):
    """
    An API view to create new role in the organization.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        # Set data
        data = {
            "name": request.POST['name'],
            "permissions": request.POST.getlist('permissions[]'),
            "organization": org.id
        }

        form_new_role = forms_account.OrganizationRoleForm(data)

        if form_new_role.is_valid():
            form_new_role.save(created_by=request.user)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_new_role.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #9
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_import_upload_excel(request, org):
    """
    API view to process uploaded file for BSP import.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':

        try:
            bsp_type = request.POST['bsp_type']
            file_excel = request.FILES['file_upload']

            count = dump_bsp_bulk_upload(file_excel, bsp_type, org,
                                         request.user)

            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok. {} bsp queued.'.format(
                                   count)).gen_http_response()
        except MultiValueDictKeyError:
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST,
                               message='One or more parameters are missing.'
                               ).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #10
0
def console_remove_response_suspicion(request, org, survey):
    """
    API view to remove suspicion reason from a response.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            response_uid = request.POST['response_uid']
            reason_id = request.POST['reason_id']

            response = SurveyResponse.objects.get(survey_uid=survey.survey_uid, response_uid=response_uid)

            success = response.suspicion_remove(reason_id)
            if not success:
                raise IndexError('Invalid reason id.')

            return ApiResponse(status=ApiResponse.ST_SUCCESS, message='Ok').gen_http_response()
        except KeyError:
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST, message='Missing parameters.').gen_http_response()
        except (DoesNotExist_mongo, IndexError, ValueError):
            return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED, message='Invalid parameters.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #11
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_org_submit_changes(request, org):
    """
    An API view to submit changes in organization. This view receives only changed fields and are
    updated immediately.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        # (b) Update information
        data = request.POST.copy()
        del data['c']
        try:
            operations.update_organization(request.user, org, data,
                                           request.FILES)
            return ApiResponse(
                status=ApiResponse.ST_SUCCESS,
                message='All updates made successfully').gen_http_response()
        except Exception as ex:
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message=ex.message).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #12
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_customize_type_create(request, org):
    """
    API view to create a bsp type customization.

    **Type**: GET

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        data = request.POST.copy()

        form_custm = BspTypeCustomizationForm(data)

        if form_custm.is_valid():
            form_custm.save(organization=org, created_by=request.user)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_custm.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #13
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_brand_save_changes(request, org):
    """
    An API view to save brand chnages. User fills a form and submit data.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        form_brand = BrandEditForm(request.POST, request.FILES)

        if form_brand.is_valid():
            form_brand.save()
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_brand.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #14
0
def console_survey_transit(request, org, survey):
    """
    API view to transit survey status.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':

        action = request.POST['action']
        try:
            # Check & make transition.
            if action == 'ready':
                survey.trans_ready()
            elif action == 'pause':
                survey.trans_pause()
            elif action == 'resume':
                survey.trans_resume()
            elif action == 'stop':
                survey.trans_stop()
            else:
                # Invalid transition
                return ApiResponse(status=ApiResponse.ST_BAD_REQUEST, message='Invalid action.').gen_http_response()

            survey.save()
            return ApiResponse(status=ApiResponse.ST_SUCCESS, message='Ok').gen_http_response()

        except TransitionNotAllowed:
            return ApiResponse(status=ApiResponse.ST_NOT_ALLOWED, message='You cannot perform this action.').gen_http_response()
        except Exception as ex:
            return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message=ex.message).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #15
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_import_remove(request, org):
    """
    Django view to remove BSP in imports in queue. Since user with permission
    ``add_businessservicepoint`` can add BSP, this view is protected by same permission,
    meaning if user can can BSP, he can also remove those in queue as well.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            list_ids = request.POST.getlist('list_ids[]')
            if not (isinstance(list_ids, list) and len(list_ids)):
                raise BadValueError("'list_ids' is not a list.")

            with transaction.atomic():
                count = ImportRecord.objects.filter(
                    pk__in=list_ids,
                    status__ne=ImportRecord.ST_PROCESSING).delete()

            partial = True if count != len(list_ids) else False

            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.',
                               count_deleted=count,
                               partial=partial).gen_http_response()
        except (MultiValueDictKeyError, BadValueError):
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST,
                               message='One or more parameters are missing.'
                               ).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #16
0
파일: views.py 프로젝트: gagan144/Feedvay
def api_search_org_bsp(request, org):
    """
    Custom API to search for organization BSP given query text. Query text must
    atleast 3 characters long.

    **Type**: GET

    **Filters**:

        - ``c``: (Mandatory) Organization UID
        - ``q``: Query text to be matched against name. Minimum of 3 characters
        - ``type``: (Optional) Type of BSP

    **Limit**: Maximum 10

    **Authors**: Gagandeep Singh
    """

    filters = {"organization_id": org.id}

    try:
        q = request.GET['q']
        if len(q) < 3:
            return ApiResponse(
                status=ApiResponse.ST_BAD_REQUEST,
                message="Query text 'q' must be 3 characters long."
            ).gen_http_response()
        filters['name'] = re.compile(q, re.IGNORECASE)

        type_bsp = request.GET.get('type', None)
        if type_bsp:
            filters['type'] = type_bsp
    except KeyError:
        return ApiResponse(status=ApiResponse.ST_BAD_REQUEST,
                           message="Missing parameters.").gen_http_response()

    result_aggr = BusinessServicePoint._get_collection().aggregate([{
        "$match":
        filters
    }, {
        "$project": {
            "_id": 0,
            "id": "$_id",
            "name": 1
        }
    }, {
        "$limit":
        10
    }])

    data = []
    for row in result_aggr:
        print row
        row['id'] = str(row['id'])
        data.append(row)

    return ApiResponse(status=ApiResponse.ST_SUCCESS,
                       message="ok",
                       objects=data).gen_http_response()
예제 #17
0
def console_account_settings_email_change(request):
    """
    An API view to change user email address.

    **Points**:
        1. Delete all previous email verification token if any.
        2. Create email verification token.
        3. Create json-web-token having new email address, registered user id.
        4. Form a verification link
        5. Send email owl to the new email address.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        reg_user = request.user.registereduser
        new_email = request.POST['new_email']

        with transaction.atomic():
            # Delete all previous email verification token
            UserToken.objects.filter(
                registered_user=reg_user,
                purpose=UserToken.PUR_EMAIL_VERIF).delete()

            # Create email verification token
            user_token = UserToken.objects.create(
                registered_user=reg_user, purpose=UserToken.PUR_EMAIL_VERIF)

            # Create json-web-token
            json_web_token = jwt.encode(
                {
                    'reg_user_id': reg_user.id,
                    'new_email': new_email,
                    'user_token_id': user_token.id
                },
                settings.JWT_SECRET_KEY,
                algorithm=settings.JWT_ALOG)

            # Create url
            url = "{}{}".format(
                settings.FEEDVAY_DOMAIN,
                reverse('accounts_verify_email', args=[json_web_token]))

            # Send email owl
            owls.EmailOwl.send_email_verification(reg_user, user_token, url,
                                                  new_email)

            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='ok').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #18
0
def get_user_details(request):
    """
    An API view to return basic details of :class:`accounts.models.RegisteredUser` given an username.

    **Response**:

        If user is found:

        .. code-block:: json

            {
                "status": "success",
                "message": "Ok",
                "data": {}
            }

        If user is **NOT** found:

        .. code-block:: json

            {
                "status": "failed",
                "message": "<some-message>",
            }

    **Type**: GET

    **Authors**: Gagandeep Singh
    """

    try:
        username = request.GET['username']

        try:
            reg_user = RegisteredUser.objects.get(user__username=username)

            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok',
                               data={
                                   "username": reg_user.user.username,
                                   "first_name": reg_user.user.first_name,
                                   "last_name": reg_user.user.last_name,
                                   "email": reg_user.user.email,
                               }).gen_http_response()
        except RegisteredUser.DoesNotExist:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message="User with username '{}' does not exists.".format(
                    username)).gen_http_response()

    except KeyError:
        return ApiResponse(status=ApiResponse.ST_BAD_REQUEST,
                           message="Please provide parameter 'username'."
                           ).gen_http_response()
예제 #19
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_organization_role_edit_save(request, org, org_role_id):
    """
    An API view to save role changes in the organization.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            filters = copy.deepcopy(
                request.permissions['accounts.organizationrole']
                ['data_access'])
            filters['organization_id'] = org.id
            filters['id'] = org_role_id

            # org_role = OrganizationRole.objects.get(organization_id=org.id, pk=org_role_id)
            org_role = OrganizationRole.objects.get(**filters)
        except (TypeError, OrganizationRole.DoesNotExist):
            # TypeError: If filters is None
            return ApiResponse(
                status=ApiResponse.ST_FORBIDDEN,
                message="You do not have permissions to change this role.")

        # Set data
        data = {
            "name": request.POST['name'],
            "permissions": request.POST.getlist('permissions[]'),
            "organization": org.id
        }

        form_new_role = forms_account.OrganizationRoleForm(data,
                                                           instance=org_role)

        if form_new_role.is_valid():
            form_new_role.save()
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_new_role.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #20
0
        def wrap(request, org, survey_uid=None, *args, **kwargs):
            # Get user
            reg_user = request.user.registereduser

            # Obtain survey_uid
            # (a) Check in url regex
            if survey_uid is None:
                # (b) Obtain from GET and (c) then from POST
                survey_uid = request.GET.get('survey_uid', request.POST.get('survey_uid', None) )

                if survey_uid is None:
                    raise Http404("Invalid link.")

            # Now check survey access permission
            try:
                if org is not None:
                    # Context: Organization
                    try:
                        filters = copy.deepcopy(request.permissions['surveys.survey']['data_access'])
                        filters['ownership'] = Survey.OWNER_ORGANIZATION
                        filters['organization_id'] = org.id
                        filters['survey_uid'] = survey_uid

                        survey = Survey.objects.get(**filters)
                    except TypeError:
                        # TypeError: If filters is None
                        if exception_type == 'api':
                            return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message="You do not have permissions to perform this action.").gen_http_response()
                        else:
                            return HttpResponseForbidden("You do not have permissions to access this page.")
                else:
                    # Context: Individual
                    filters = {
                        'ownership': Survey.OWNER_INDIVIDUAL,
                        'survey_uid': survey_uid,
                        'created_by_id': request.user.id
                    }
                    survey = Survey.objects.get(**filters)

                return func(request, org, survey, *args, **kwargs)

            except Survey.DoesNotExist:
                if exception_type == 'api':
                    return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message="You do not have permissions to perform this action.").gen_http_response()
                else:
                    return HttpResponseForbidden("You do not have permissions to access this page.")
예제 #21
0
def console_password_change(request):
    """
    An API view to change user password. The user fills a form and submit old & new password.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        form_chng = PasswordChangeForm(request.POST)

        if form_chng.is_valid():
            form_data = form_chng.cleaned_data

            # Here request.user must be 'RegisteredUser' since view has been protected by the
            # the decorator 'registered_user_only'
            user = request.user
            registered_user = request.user.registereduser

            # Confirm old password
            if user.check_password(form_data['old_password']):
                # Change password
                new_password = form_data['new_password']
                registered_user.set_password(new_password)

                # Prevent portal logout
                auth.update_session_auth_hash(request, user)

                return ApiResponse(status=ApiResponse.ST_SUCCESS,
                                   message='ok').gen_http_response()
            else:
                return ApiResponse(
                    status=ApiResponse.ST_UNAUTHORIZED,
                    message='Invalid password, please try again.'
                ).gen_http_response()
        else:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message='Incomplete submission.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #22
0
def console_survey_create(request, org):
    """
    API view to create new survey.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    reg_user = request.user.registereduser

    if request.method.lower() == 'post':
        try:
            from surveys.forms import SurveyCreateForm
            post_data = request.POST.copy()

            if org:
                # Context: Organization
                post_data['type'] = Survey.TYPE_SIMPLE      # TODO: Allow complex
                post_data['ownership'] = Survey.OWNER_ORGANIZATION
                post_data['organization'] = org.id
            else:
                # Context: Individual
                post_data['type'] = Survey.TYPE_SIMPLE
                post_data['ownership'] = Survey.OWNER_INDIVIDUAL

            form_survey = SurveyCreateForm(post_data)

            if form_survey.is_valid():
                new_survey = form_survey.save(created_by=reg_user.user)
                return ApiResponse(
                    status=ApiResponse.ST_SUCCESS,
                    message='Ok',
                    survey_uid=new_survey.survey_uid,
                    survey_type=new_survey.type
                ).gen_http_response()
            else:
                errors = dict(form_survey.errors)
                return ApiResponse(status=ApiResponse.ST_FAILED, message='Please correct marked errors.', errors=errors).gen_http_response()
        except Survey.DoesNotExist:
            return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED, message='Invalid survey.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #23
0
def submit_survey_response(request):
    """
    View to submit a response for survey phase. This view receives response
    submitted by the user and is queued for processing.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        token = request.POST['token']

        response_data = request.POST['response']

        try:
            response_json = json.loads(response_data)

            # Get Survey
            survey = Survey.objects.get(survey_uid=response_json['survey_uid'])
            phase = survey.phases.get(id=response_json['phase_id'])

            resp_queue = ResponseQueue.objects.create(
                context = ResponseQueue.CT_SURVEY_RESPONSE,
                data    = response_data,
            )

            return ApiResponse(status=ApiResponse.ST_SUCCESS, message='Response queued for processing.').gen_http_response()

        except ValueError:
            # No JSON object could be decoded
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST, message="Badly formed 'response' structure.").gen_http_response()
        except KeyError as ex:
            # response_json does not contain some require data
            return ApiResponse(status=ApiResponse.ST_BAD_REQUEST, message=ex.message).gen_http_response()
        except (Survey.DoesNotExist, SurveyPhase.DoesNotExist) as ex:
            # Survey or Survey phase does not exists
            return ApiResponse(status=ApiResponse.ST_FAILED, message='Invalid survey or survey phase.').gen_http_response()

    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN, message='Use post.').gen_http_response()
예제 #24
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_member_invite(request, org):
    """
    API view to add/invite a new member in the organization. User submit his form to this
    view.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        country_tel_code = '+91'  #TODO: Set default country_tel_code

        # Set data
        data = request.POST.copy()
        data['organization'] = org.id
        data['country_tel_code'] = country_tel_code
        if request.POST.get('roles[]', None):
            data['roles'] = request.POST.getlist('roles[]')
            del data['roles[]']
        if request.POST.get('permissions[]', None):
            data['permissions'] = request.POST.getlist('permissions[]')
            del data['permissions[]']

        del data['c']
        data = data.dict()

        form_new_mem = forms_clients.AddInviteMemberForm(data)

        if form_new_mem.is_valid():
            form_new_mem.save(created_by=request.user)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_new_mem.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #25
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_edit_save(request, org, bsp_id):
    """
    API view to save edited bsp information.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            filters = copy.deepcopy(
                request.permissions['market.businessservicepoint']
                ['data_access'])
            filters['organization_id'] = org.id
            filters['pk'] = bsp_id

            bsp = BusinessServicePoint.objects.get(**filters)
        except (TypeError, DoesNotExist_mongo):
            # TypeError: If filters is None
            return ApiResponse(
                status=ApiResponse.ST_FORBIDDEN,
                message=
                "You do not have permissions to edit this Business or Service Point."
            ).gen_http_response()

        data = json.loads(request.POST.copy()['data'])
        form_bsp = BusinessServicePointForm(data, instance=bsp)

        if form_bsp.is_valid():
            form_bsp.save()
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_bsp.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #26
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_customize_type_edit_save(request, org, cust_id):
    """
    API view to save edited bsp type customization.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            filters = copy.deepcopy(
                request.permissions['market.bsptypecustomization']
                ['data_access'])
            filters['organization_id'] = org.id
            filters['id'] = cust_id

            cust_bsp = BspTypeCustomization.objects.get(**filters)
        except (TypeError, BspTypeCustomization.DoesNotExist):
            # TypeError: If filters is None
            return ApiResponse(
                status=ApiResponse.ST_FORBIDDEN,
                message="You do not have permissions to edit this customization."
            ).gen_http_response()

        data = request.POST.copy()
        form_custm = BspTypeCustomizationForm(data, instance=cust_bsp)

        if form_custm.is_valid():
            form_custm.save()
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_custm.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #27
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_bsp_customize_type_remove(request, org, cust_id):
    """
    API view to delete a bsp type customization.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            filters = copy.deepcopy(
                request.permissions['market.bsptypecustomization']
                ['data_access'])

            filters['organization_id'] = org.id
            filters['id'] = cust_id

            cust_bsp = BspTypeCustomization.objects.get(**filters)
        except (TypeError, BspTypeCustomization.DoesNotExist):
            # TypeError: If filters is None
            return ApiResponse(
                status=ApiResponse.ST_FORBIDDEN,
                message=
                "You do not have permissions to remove this customization."
            ).gen_http_response()

        confirm = int(request.POST.get('confirm', 0))

        if not confirm:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message='Please confirm your action.').gen_http_response()
        else:
            cust_bsp.delete()
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #28
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_member_edit_save(request, org, org_mem_id):
    """
    API view to save changes for a member in the organization. User submit his form to this
    view.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':

        # Set data
        data = request.POST.copy()
        data['org_mem'] = org_mem_id
        if request.POST.get('roles[]', None):
            data['roles'] = request.POST.getlist('roles[]')
            del data['roles[]']
        if request.POST.get('permissions[]', None):
            data['permissions'] = request.POST.getlist('permissions[]')
            del data['permissions[]']

        del data['c']
        data = data.dict()

        form_edit_mem = forms_clients.EditMemberForm(data)

        if form_edit_mem.is_valid():
            form_edit_mem.save(created_by=request.user)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
        else:
            errors = dict(form_edit_mem.errors)
            return ApiResponse(status=ApiResponse.ST_FAILED,
                               message='Please correct marked errors.',
                               errors=errors).gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #29
0
파일: views.py 프로젝트: gagan144/Feedvay
def console_member_remove(request, org, org_mem_id):
    """
    API view to remove a member of the organization.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """
    if request.method.lower() == 'post':
        try:
            filters = copy.deepcopy(
                request.permissions['clients.organizationmember']
                ['data_access'])

            filters['organization_id'] = org.id
            filters['id'] = org_mem_id
            filters['deleted'] = False

            org_mem = OrganizationMember.objects.get(**filters)
        except (TypeError, OrganizationRole.DoesNotExist):
            # TypeError: If filters is None
            return ApiResponse(
                status=ApiResponse.ST_FORBIDDEN,
                message="You do not have permissions to remove this member.")

        confirm = int(request.POST.get('confirm', 0))

        if not confirm:
            return ApiResponse(
                status=ApiResponse.ST_FAILED,
                message='Please confirm your action.').gen_http_response()
        else:
            org_mem.mark_deleted(confirm=True)
            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='Ok.').gen_http_response()
    else:
        # GET Forbidden
        return ApiResponse(status=ApiResponse.ST_FORBIDDEN,
                           message='Use post.').gen_http_response()
예제 #30
0
def registration_resend_code(request):
    """
    View to re-send verification code during registration process.

        - No limitation on number of request is set for now.
        - Call to this view is only valid for registered user who's status is `verification_pending`.

    **Type**: POST

    **Authors**: Gagandeep Singh
    """

    if request.method.lower() == 'post':
        reg_user_id = request.POST['id']

        try:
            reg_user = RegisteredUser.objects.get(
                id=reg_user_id, status=RegisteredUser.ST_VERIFICATION_PENDING)

            # Create verification code token
            user_token, is_utoken_new = UserToken.objects.update_or_create(
                registered_user=reg_user,
                purpose=UserToken.PUR_REG_VERF,
                defaults={"created_on": timezone.now()})

            owls.SmsOwl.send_reg_verification(reg_user.user.username,
                                              user_token,
                                              reg_user.user.username)

            return ApiResponse(status=ApiResponse.ST_SUCCESS,
                               message='ok').gen_http_response()

        except RegisteredUser.DoesNotExist:
            return ApiResponse(status=ApiResponse.ST_UNAUTHORIZED,
                               message='Invalid username').gen_http_response()
    else:
        # Forbidden GET
        return HttpResponseForbidden('Forbidden! Use post.')