def get(self, request, id, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission(request.user, size, index) size = index + size instance = self.model.objects.get(id=id, is_deleted=False) if not instance.has_legal_issue: if not instance.approved: if request.user == instance.creator or (not request.user.is_anonymous and request.user.is_staff): pass else: raise self.model.DoesNotExist serialize_data = self.get_serializer(instance.interviewcomment_set.filter( is_deleted=False, approved=True ).all(), many=True) data = serialize_data.data data = sorted(data, key=lambda x: x['vote_count'], reverse=True) else: data = [] return responses.SuccessResponse(data[index:size], index=index, total=len(data)).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request, backend, *args, **kwargs): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): token = serialized_data.data['token'] if backend.lower() == 'google': try: resp_user = id_token.verify_oauth2_token(token, google_requests.Request(), settings.GOOGLE_OAUTH_ID) except Exception as e: return responses.ErrorResponse(message='Error in google open auth', dev_error=str(e), status=400).send() if resp_user['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise authnz_exceptions.CustomException(detail=_('Google Wrong issuer.')) if not resp_user.get('email') or not resp_user.get('given_name') or \ not resp_user.get('family_name') or not resp_user.get('picture'): raise authnz_exceptions.CustomException( detail=_('Scope need to have email, given name, family, picture')) email = resp_user['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = transactions.open_auth_user_creator(email, resp_user['given_name'], resp_user['family_name'], resp_user['picture']) else: raise authnz_exceptions.CustomException(detail=_('Wrong backend')) if user.is_active: payload = jwt_payload_handler(user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=user) else: raise authnz_exceptions.CustomException( detail=_('Your user account is deactivated, contact us for more information.')) return responses.SuccessResponse(jwt_token).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(profile__email=email, profile__email_confirmed=True) except User.DoesNotExist: raise authnz_exceptions.CustomException( detail=_('Email is invalid or not confirmed')) if user.check_password(serialized_data.data['password']): if user.is_active: payload = jwt_payload_handler( user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler( jwt_encode_handler(payload), user=user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException( detail=_('This user is inactive, contact us.')) else: raise authnz_exceptions.CustomException( detail=_('Email or Password is invalid.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = None if user and user.profile.email_confirmed: raise authnz_exceptions.CustomException( detail=_('This email is registered before.')) elif user: permissions.check_send_email_permission(email) user.set_password(serialized_data.data['password']) user.save() utilities.send_email_confirm(user, request) return responses.SuccessResponse().send() else: password = serialized_data.data['password'] user = transactions.register_user_with_email_and_password( email, password) utilities.send_email_confirm(user, request) return responses.SuccessResponse( message=_('Check your email box.')).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): if request.user.check_password( serialized_data.data['old_password']): if request.user.is_active: transactions.change_user_password( request.user, serialized_data.data['password']) payload = jwt_payload_handler( request.user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler( jwt_encode_handler(payload), user=request.user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException( detail=_('This user is deactivated, contact us.')) else: raise authnz_exceptions.CustomException( detail=_('Old Password is invalid.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, uidb64, token): try: try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and utilities.account_activation_token.check_token( user, token): user.profile.email_confirmed = True user.profile.save() utilities.telegram_notify('New user: {}'.format(user.username)) return render( request, 'mail_confirmed.html', { 'domain': get_current_site(request).domain, 'name': user.username }) else: return render(request, 'mail_confirm_invalid.html', {'domain': get_current_site(request).domain}) except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except Exception as e: return responses.ErrorResponse(message=str(e)).send()
def post(self, request): try: serialize_data = self.serializer_class(data=request.data) if serialize_data.is_valid(raise_exception=True): email = serialize_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist: raise authnz_exceptions.CustomException(detail=_('Email does not exist.')) if user.is_active and user.email: forgot_password_token = cache.get('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) if not forgot_password_token: permissions.check_send_email_permission(email) forgot_password_token = utilities.forgot_password_delete_account_token_generator() utilities.send_password_forget_token_email(user, request, forgot_password_token) cache.set('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN), forgot_password_token, timeout=settings.TIMEOUT_FORGOT_PASSWORD_TOKEN) return responses.SuccessResponse(message=_('Check Your email for token.')).send() else: raise authnz_exceptions.CustomException(detail=_('We sent an token recently please try later')) elif not user.is_active: raise authnz_exceptions.CustomException(detail=_('This account is inactive.')) else: raise authnz_exceptions.CustomException(detail=_('This account has no email.')) except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except Exception as e: return responses.ErrorResponse(message=str(e)).send()
def post(self, request, *args, **kwargs): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): self.perform_create(serialize_data) return responses.SuccessResponse(serialize_data.data).send() except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, is_deleted=False) if instance.approved or request.user == instance.company.user: instance.view.add(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() else: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, is_deleted=False) if instance.approved or request.user == instance.creator or (not request.user.is_anonymous and request.user.is_staff): if self.model in [CompanyReview, Question, Interview]: if not isinstance(request.user, AnonymousUser): # view of company review, question instance.view.add(request.user) instance.total_view += 1 instance.save() serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() else: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def put(self, request): try: serialize_data = self.get_serializer(request.user, data=request.data) if serialize_data.is_valid(raise_exception=True): try: self.perform_update(serialize_data) except Exception as e: raise e serialize_data = self.get_serializer(request.user) return responses.SuccessResponse(serialize_data.data).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except Exception as e: return responses.ErrorResponse(message=str(e)).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): nick_name = serialized_data.data['nick_name'] if request.user.profile.nick_name == nick_name: return responses.SuccessResponse().send() if Profile.objects.filter(nick_name__iexact=nick_name): raise authnz_exceptions.CustomException(detail=_('This nick name exists')) else: return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def put(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id) permissions.check_perm_company_owner_update(request, instance) serialize_data = self.get_serializer(instance, data=request.data) if serialize_data.is_valid(raise_exception=True): self.perform_update(serialize_data) data = self.get_serializer(instance) return responses.SuccessResponse(data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=400).send() except CustomException as c: return responses.ErrorResponse(message=c.detail, status=c.status_code).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request, backend, *args, **kwargs): try: if request.user.profile.email and request.user.profile.email_confirmed: return responses.ErrorResponse( message=_('This email used before.')).send() serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): token = serialized_data.data['token'] if backend.lower() == 'google': try: resp_user = id_token.verify_oauth2_token( token, google_requests.Request(), settings.GOOGLE_OAUTH_ID) except Exception as e: return responses.ErrorResponse( message='Error in google open auth', dev_error=str(e), status=400).send() if resp_user['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise authnz_exceptions.CustomException( detail=_('Google Wrong issuer.')) if not resp_user.get('email') or not resp_user.get('given_name') or \ not resp_user.get('family_name') or not resp_user.get('picture'): raise authnz_exceptions.CustomException(detail=_( 'Scope need to have email, given name, family, picture' )) email = resp_user['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = None if user: raise authnz_exceptions.CustomException( detail=_('This email was used before.')) else: request.user.profile.email = email request.user.profile.email_confirmed = True request.user.save() else: raise authnz_exceptions.CustomException( detail=_('Wrong backend')) return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): if serialize_data.data['key'] == settings.BOT_APPROVE_KEY: if serialize_data.data['type'] == 'review': review = CompanyReview.objects.get( id=serialize_data.data['id']) elif serialize_data.data['type'] == 'interview': review = Interview.objects.get( id=serialize_data.data['id']) else: raise CustomException( detail='Instance does not Found.', code=404) review.approved = True review.save() cache.delete(settings.LAST_REVIEWS) cache.delete(settings.LAST_INTERVIEWS) if serialize_data.data['type'] == 'review': review_link = '{}/review/{}'.format( settings.WEB_BASE_PATH, review.id) utilities.telegram_notify_channel( 'تجربه کاری {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}' .format(review.title, review.company.name, review_link, '#' + review.company.city.city_slug, '#review')) review.company.handle_company_review_statics() elif serialize_data.data['type'] == 'interview': review_link = '{}/interview/{}'.format( settings.WEB_BASE_PATH, review.id) utilities.telegram_notify_channel( 'تجربه مصاحبه {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}' .format(review.title, review.company.name, review_link, '#' + review.company.city.city_slug, '#interview')) review.company.handle_company_interview_statics() return responses.SuccessResponse().send() else: raise CustomException(detail='Instance does not Found.', code=404) except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def get(self, request, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') result = self.model.objects.filter(**arguments) if self.model in MODELS_HAVE_IS_DELETED: result = result.filter(is_deleted=False) if self.model == CompanyReview or self.model == Interview: result = result.filter(approved=True) if sort: result = result.order_by(sort) if self.model in [City, Pros, Cons]: result = result.order_by('-priority') result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def post(self, request): try: serialize_data = self.serializer_class(data=request.data) if serialize_data.is_valid(raise_exception=True): email = serialize_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist: raise authnz_exceptions.CustomException(detail=_('Email does not exist.')) if user.is_active: forgot_password_token = cache.get('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) if forgot_password_token == serialize_data.data['token']: transactions.change_user_password(user, serialize_data.data['password']) cache.delete('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) payload = jwt_payload_handler(user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=user) return responses.SuccessResponse(jwt_token).send() elif not forgot_password_token: raise authnz_exceptions.CustomException(detail=_('Token timeout.')) else: raise authnz_exceptions.CustomException(detail=_('We sent a new token recently please try it.')) else: raise authnz_exceptions.CustomException(detail=_('Your account is inactive.')) except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') result = self.model.objects.filter(**arguments) if sort: result = result.order_by(sort) result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def get(self, request, *args, **kwargs): try: interview_list = self.model.objects.filter(creator=request.user) data = self.get_serializer(interview_list, many=True) return responses.SuccessResponse(data.data).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, question_slug, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') question = self.model.objects.get(question_slug=question_slug, is_deleted=False) if not isinstance(request.user, AnonymousUser): question.view.add(request.user) question.total_view += 1 question.save() result = question.answer_set result = result.filter(is_deleted=False) if sort: result = result.order_by(sort) result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def get(self, request, *args, **kwargs): try: main_url = '{}/'.format(request.build_absolute_uri('/')[:-1].strip("/")) create_data(main_url) # for debug data = {} return responses.SuccessResponse(data).send() except Exception as e: return responses.ErrorResponse(message=str(e), status=400).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id) instance.down_vote.remove(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=400).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(email=email) except User.DoesNotExist as e: user = None if user: raise authnz_exceptions.CustomException(detail=_('This email is registered before.')) else: password = serialized_data.data['password'] user = transactions.register_user_with_email_and_password(email, password) return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request): try: if request.user.is_active: payload = jwt_payload_handler(request.user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=request.user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException(detail=_('This user is inactive, contact us.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request, *args, **kwargs): serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(): try: src = Company.objects.get(id=serialize_data.validated_data["src"], is_deleted=False) except Company.DoesNotExist as e: return responses.ErrorResponse(message="Src company does not exist", status=400).send() try: des = Company.objects.get(id=serialize_data.validated_data["des"], is_deleted=False) except Company.DoesNotExist as e: return responses.ErrorResponse(message="Des company does not exist", status=400).send() with transaction.atomic(): # review for review in src.companyreview_set.all(): review.company = des review.save() # interview for interview in src.interview_set.all(): interview.company = des interview.save() # question for question in src.question_set.all(): question.company = des question.save() src.is_deleted = True src.save() des.handle_company_review_statics() des.handle_company_interview_statics() return responses.SuccessResponse({}, status=200).send() return responses.ErrorResponse(message="not valid data", status=400).send()
def post(self, request, *args, **kwargs): serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(): file = file_check_name(request.user.username, serialize_data.validated_data['file'], serialize_data.validated_data['slug']) data = {'file_path': file} return responses.SuccessResponse(data, status=200).send() else: dev_error = serialize_data.errors message = 'Failed to upload {}'.format(serialize_data.data['file'].name) show_type = settings.MESSAGE_SHOW_TYPE['TOAST'] return responses.ErrorResponse(message=message, dev_error=dev_error, show_type=show_type, status=400).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, approved=True) if self.model in [CompanyReview, Question, Interview]: if not isinstance( request.user, AnonymousUser): # view of company review, question instance.view.add(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def post(self, request): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): if serialize_data.data["key"] == settings.BOT_APPROVE_KEY: instance_map = { "review": CompanyReview, "interview": Interview, "question": Question, "answer": Answer, "review_comment": ReviewComment, "interview_comment": InterviewComment, } if serialize_data.data["type"] in instance_map.keys(): try: instance = instance_map[serialize_data.data["type"]].objects.get( id=serialize_data.data["id"] ) except ( CompanyReview.DoesNotExist, Interview.DoesNotExist, Question.DoesNotExist, Answer.DoesNotExist, ReviewComment.DoesNotExist, InterviewComment.DoesNotExist ) as e: raise CustomException(detail="Instance does not Found.", code=404) else: raise CustomException(detail="Instance type does not exist.") instance.approved = serialize_data.data["approved"] instance.save() if serialize_data.data["type"] in ["review", "interview"]: cache.delete(settings.LAST_REVIEWS) cache.delete(settings.LAST_INTERVIEWS) if check_notify_to_telegram_channel(serialize_data.data): if serialize_data.data["type"] == "review": review_link = "{}/review/{}".format(settings.WEB_BASE_PATH, instance.id) utilities.telegram_notify_channel( "تجربه کاری {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}".format( instance.title, instance.company.name, review_link, "#" + instance.company.city.city_slug, "#review")) instance.company.handle_company_review_statics() elif serialize_data.data["type"] == "interview": review_link = "{}/interview/{}".format(settings.WEB_BASE_PATH, instance.id) utilities.telegram_notify_channel( "تجربه مصاحبه {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}".format( instance.title, instance.company.name, review_link, "#"+instance.company.city.city_slug, "#interview")) instance.company.handle_company_interview_statics() if not instance.approved: instance_type = serialize_data.data["type"] fa_map = { "review": "تجربه کاری", "interview": "تجربه مصاحبه", "question": "سوال", "answer": "پاسخ", "review_comment": "نظر", "interview_comment": "نظر", } company = get_compnay(instance, instance_type) send_notice_instance_rejected( instance.creator, fa_map[instance_type], company ) return responses.SuccessResponse().send() else: raise CustomException(detail="Instance does not Found.", code=404) except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()