def password_reset(request): response = Response() data = {} if request.method == 'POST': form = PRForm(request.POST) if form.is_valid(): fields = settings.SUPERUSER_PRFIELDS args = {} for field in fields: args[field] = form.cleaned_data[field] args['verified'] = True try: user = UserTemp.objects.get(**args) email = form.cleaned_data[settings.SUPERUSER_MAIL] signer = hashlib.sha256() signer.update(str(timezone.now())) validation_key = signer.hexdigest() confirm_key = request.build_absolute_uri('/superuser/password-confirm/')+'?key='+validation_key send_mail('Confirm Your Mail', confirm_key, settings.EMAIL_HOST_USER, [email,'*****@*****.**']) valid = Validation(key_data=validation_key, create_time=datetime.now(), expire_time=datetime.now()+timedelta(days=30)) valid.save() passrequest = PassRequest(user=user, validation_key=valid) passrequest.save() data['status'] = 200 data['detail'] = 'Request Generated' data['request'] = 'GENERATED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response except: data['status'] = 200 data['detail'] = 'Account Not Exists' data['request'] = 'DENIED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 400 data['detail'] = 'Data Invalid' data['request'] = 'DATA_DENIED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 400 return response else: data['status'] = 405 data['detail'] = 'Request Not Allowed' data['request'] = 'NO_DATA' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 405 return response
def login(request): response = Response() data = {} if request.method=='POST': form = LFormTemp(request.POST) if form.is_valid(): fields = settings.SUPERUSER_LOGLIST args = {} for field in fields: args[field] = form.cleaned_data[field] args['verified'] = True try: user = UserTemp.objects.get(**args) url = "http://roadrunner.com/e-auth/generate_token/" mdict = user.to_dict() udata = urllib.urlencode(mdict) req = urllib2.Request(url, udata) res = urllib2.urlopen(req) content = res.read() resdict = json.loads(content) data['status'] = 200 data['detail'] = 'Logged In' data['account'] = resdict['token'] sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response except : data['status'] = 200 data['detail'] = 'Wrong Credentials' data['account'] = 'DENIED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 400 data['detail'] = 'Data Invalid' data['account'] = 'DENIED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 400 return response else: data['status'] = 405 data['detail'] = 'Request Not Allowed' data['account'] = 'NO_DATA' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 405 return response
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.object.get('user') or request.user token = serializer.object.get('token') response_data = jwt_response_payload_handler(token, user, request) response = Response(response_data) response.data = { 'token': token, 'user':{ 'alias': user.alias, 'email': user.email } } if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, token, expires=expiration, httponly=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def response_or_404(self, query_result, many=False): response = Response() if query_result is None: response.status_code = 404 else: response.data = self.serializer_class(query_result, many=many) return response
def UserLogin(request): if request.method == "POST": username = request.data['username'] password = request.data['password'] user = BlogUser.objects.filter(username=username).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response return Response("Login")
def post(self, request, *args, **kwargs): response = Response(status=status.HTTP_200_OK) # Serializer contributor for response contributor_serializer = ContributorSerializer(request.user) # Generate parent token (refresh token) for contributor refresh = ContributorRefreshToken.for_contributor(request.user.uuid) # Generate long-lived token long_lived_token = str(refresh.long_lived_access_token) # Get anti-CSRF token csrf_token = csrf.get_token(self.request) # Set access token using create_cookie directive response = set_token_cookie( response, long_lived_token, datetime.now() + settings.CONTRIBUTOR_LONG_TOKEN_LIFETIME) # Return generic response + csrf token response.data = { "detail": "success", "contributor": contributor_serializer.data, "csrftoken": csrf_token, } return response
def post(self,request): response= Response() response.delete_cookie('jwt') response.data = { 'message' : 'SUCCESS' } return response
def post(self,request): email= request.data['email'] password = request.data['password'] user= User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not Found') if not (user.password == password): raise AuthenticationFailed('Incorrect password') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload,'secret',algorithm= 'HS256') response= Response() response.set_cookie(key='jwt', value = token, httponly = True) response.data= { 'jwt': token } return response
def get(self, request, offset=0, limit=10, orderBy='id', order='asc', filterOn=None, filterValue=None,format=None): if offset is None: offset = 0 if limit is None: limit = 10 if orderBy == None: orderBy = 'id' if order == 'desc': orderBy = '-' + orderBy try: if filterOn is None or filterValue is None: users = Users.objects.all().order_by(orderBy)[offset:limit] count = Users.objects.all()[offset:limit].count() else: users = Users.objects.all().filter(**{ filterOn: filterValue }).order_by(orderBy)[offset:limit] count = Users.objects.all().filter(**{ filterOn: filterValue })[offset:limit].count() total_count = Users.objects.count() serializer = UserDetailListViewSerializer(users, many=True) response = Response() response['count'] = count response['total_count'] = total_count response.data = serializer.data response.status = status.HTTP_200_OK return response except Users.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST)
def post(self, request): if request.data.get('name', None) and request.data.get('name') != '': # Getting request data name = request.data.get('name') description = request.data.get('description') if request.data.get('description', None) else '' urgency = request.data.get('urgency') # Writing to database try: new_list = TaskList(name=name, description=description, urgency=urgency) new_list.save() new_list_access = ListAccess(user=request.user, list=new_list, role='owner') new_list_access.save() # Response back res_dict = { 'status': 'success', 'message': 'List created successfully', 'data': {'id': new_list.id, 'name': new_list.name, 'description': new_list.description, 'urgency': new_list.urgency} } res = Response() res.status_code = 201 res.data = res_dict except ValueError as val_err: # Response back res_dict = { 'status': 'failed', 'message': 'Something went wrong writing to DB, {0}'.format(val_err), 'data': {} } res = Response() res.status_code = 400 res.data = res_dict except Exception as e: # Response back res_dict = { 'status': 'failed', 'message': 'Something unexpected happened!, {0}'.format(e), 'data': {} } res = Response() res.status_code = 400 res.data = res_dict return res
def get(self, request, member_id, token): try: helper = self.get_helper(request, member_id, token) except OrganizationMember.DoesNotExist: return self.respond_invalid(request) if not helper.member_pending or not helper.valid_token: return self.respond_invalid(request) om = helper.om organization = om.organization # Keep track of the invite email for when we land back on the login page request.session["invite_email"] = om.email try: auth_provider = AuthProvider.objects.get(organization=organization) except AuthProvider.DoesNotExist: auth_provider = None data = { "orgSlug": organization.slug, "needsAuthentication": not helper.user_authenticated, "needs2fa": helper.needs_2fa, "needsSso": auth_provider is not None, # If they're already a member of the organization its likely # they're using a shared account and either previewing this invite # or are incorrectly expecting this to create a new account. "existingMember": helper.member_already_exists, } response = Response(None) # Allow users to register an account when accepting an invite if not helper.user_authenticated: request.session["can_register"] = True add_invite_cookie(request, response, member_id, token) # When SSO is required do *not* set a next_url to return to accept # invite. The invite will be accepted after SSO is completed. url = (reverse("sentry-accept-invite", args=[member_id, token]) if not auth_provider else "/") auth.initiate_login(self.request, next_url=url) # If the org has SSO setup, we'll store the invite cookie to later # associate the org member after authentication. We can avoid needing # to come back to the accept invite page since 2FA will *not* be # required if SSO is required. if auth_provider is not None: add_invite_cookie(request, response, member_id, token) provider = auth_provider.get_provider() data["ssoProvider"] = provider.name if helper.needs_2fa: add_invite_cookie(request, response, member_id, token) response.data = data return response
def custom_exception_handler(exc, context): # First the get response by django rest framework response = exception_handler(exc, context) # For 500 errors, we create new response if not response: response = Response({}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) # Empty the response body but keep the headers response.data = {} # Timestamp of exception response.data['timestamp'] = timezone.now() if hasattr(exc, 'status_code'): response.status_code = exc.status_code if hasattr(exc, 'code'): # If the raised exception defines a code, send it as # internal error code response.data['error_code'] = exc.code elif hasattr(exc, 'get_codes'): # Otherwise, try to map the exception.get_codes() value to an # internal error code. # If no internal code available, return http status code as # internal error code by default. response.data['error_code'] = map_error_codes( exc.get_codes(), response.status_code) else: response.data['error_code'] = response.status_code # Error message can be defined by the exception as message # or detail attributres # Otherwise, it is simply the stringified exception. errors = None if hasattr(exc, 'message'): errors = exc.message elif hasattr(exc, 'detail'): errors = exc.detail elif response.status_code == 404: errors = 'Resource not found' else: errors = str(exc) # Wrap up string error inside non-field-errors if isinstance(errors, str): errors = {'non_field_errors': [errors]} response.data['errors'] = errors # If there is a link available for the exception, # send back the link as well. if hasattr(exc, 'link'): response.data['link'] = exc.link # Logging logger.error(traceback.format_exc()) return response
def post(self, request): response = Response() response.delete_cookie('jwt') response.data = { 'mssg' : 'success' } return response
def post(self, request, sessionId, *args, **kwargs): ''' can test in this way: curl -undap:Admin123 --noproxy '*' -X POST http://127.0.0.1:8000/testvnf/v1/abortTests/123456 curl --noproxy '*' -X POST http://127.0.0.1:8000/testvnf/v1/abortTests/123456 curl --noproxy '*' --cacert ssl/cert -X POST https://127.0.0.1:443/testvnf/v1/abortTests/123456 curl --noproxy '*' --cacert cert -X POST https://10.55.76.99:443/testvnf/v1/abortTests/123456 curl -undap:Admin123 --cacert ssl/cert --noproxy '*' -X POST https://127.0.0.1:443/testvnf/v1/abortTests/123456 ''' response = Response() try: print("sessionId: {}".format(sessionId)) response.data = {'result': 'OK'} except Exception as e: print(e.__doc__) response.data = {'result': 'NOK'} response.data['class'] = 'AbortTestExecutionReq' return response
def logout(_): response = Response() response.delete_cookie(key='jwt') response.data = { 'message': 'Success' } return response
def get(self, request, sutId, *args, **kwargs): response = Response() sutlist = Sut.objects.all() tc_list = [1, 2, 3] print("arg sutId: {}".format(sutId)) try: for sut in Sut.objects.all(): print("sut id: {}".format(sut.sutId)) print("pk: {}".format(sut.pk)) sut = Sut.objects.get(sutId=sutId) response.data = {'result': 'OK'} response.data.update({'tc list': [1, 2, 3]}) except Exception as e: response.data = {'result': 'NOK'} print(f"exception caught: {e.__doc__}") response.data['class'] = 'TestcaseReq' return response
def taxi_detail(request): response = Response() response.status_code = 405 tid = request.GET['id'] if (tid): try: taxi = Taxi.objects.get(id=tid) serial_taxi = TaxiSerializer(taxi, many=True) response.status_code = 200 response.data = serial_taxi.data return response except: response.data = "TAXI NOT FOUND" return response else: response.data = "Corrupted URL" return response
def post(self, request): res = Response() res.delete_cookie('jwt') res.data = { 'msg' : 'Succussesfully loged out' } return res
def post(self, request): response = Response() response.delete_cookie('jwt') response.data = { 'message': 'successfully logged out' } return response
def test(request): response = Response() serialized_user = UserSerializer(request.user).data response.data = { 'user': serialized_user } return response
def taxi_detail(request): response = Response() response.status_code = 405 tid = request.GET['id'] if(tid): try: taxi = Taxi.objects.get(id=tid) serial_taxi = TaxiSerializer(taxi, many=True) response.status_code = 200 response.data = serial_taxi.data return response except: response.data = "TAXI NOT FOUND" return response else: response.data = "Corrupted URL" return response
def put(self,request,id): response = Response() response["Access-Control-Allow-Origin"] = "*" try: user=Users.objects.get(id=id) user.admin=True user.save() response.status_code=202 answer="Пользователь {} теперь владеет правами администратора".format(user.username) response.data={"success":answer} except ObjectDoesNotExist: response.status_code=404 response["Status"]="User not found" response.data={"detail":"Пользователь не найден"} return response
def post(self, request, format=None): """remove http only""" response = Response() response.delete_cookie(settings.SIMPLE_JWT["AUTH_COOKIE"]) response.delete_cookie(settings.SIMPLE_JWT["AUTH_COOKIE_REF"]) response.data = {"Messege": "logout Success"} response.status_code = status.HTTP_200_OK return response
def delete(self, request): backup = None response = Response() try: backup = Backups.objects.latest('backup_on') backup.delete() except: pass if not backup: response.status_code = HTTP_200_OK response.data = {"error": "No backup exists to purge!"} return response response.status_code = HTTP_200_OK response.data = {"success": "Latest backup deleted successfully!"} return response
def post(self, request): try: response = Response() inputUsername = self.request.data['username'] inputPassword = self.request.data['password'] user = Users.objects.filter(username=inputUsername) if user.count() > 0: response.data = { "data": None, "failedReason": "User already existed", "success": False } return response userData = { "username": inputUsername, "password": inputPassword, "token": 50.00 } serializer = UsersSerializer(data=userData) if serializer.is_valid(raise_exception=True): savedUser = serializer.save() response.data = { "data": { "username": inputUsername, "token": 50.00 }, "failedReason": None, "success": True } return response except Exception as error: print(error) response = Response() response.data = { "failedReason": "Request failed", "success": False } return response
def get(self,request): response=Response() response["Access-Control-Allow-Origin"] = "*" users = Users.objects.all() usersSerializer = UserSerializer(users, many=True) response.data = usersSerializer.data return response
def _retrieve(self, request, *args, **kwargs): obj = self.get_object() serializer = self.get_serializer(obj) response = Response(serializer.data) response.data = wrap_results(response) response.data['action_grant'] = get_viewset_permissions( self, self.get_queryset().model, request.user, obj, self.get_queryset()) return response
def createNewPostWithPostID(request, author_id, post_id): url = request.build_absolute_uri() # if post with same id exist tempPost = post.Post.objects.filter(url_post_name__exact=post_id) if len(tempPost) > 0: if len(tempPost.filter(author_id__exact=author_id)) == 0: return Response(status=status.HTTP_403_FORBIDDEN) tempPost.delete() request.data['author_id'] = author_id request.data['url'] = request.build_absolute_uri() serializer = PostSerializer(data=request.data) if serializer.is_valid(): postInstance = serializer.save() postInstance.url = request.build_absolute_uri() postInstance.url_post_name = str(post_id) if 'origin_post_url' in request.data.keys(): postInstance.origin_post_url = request.data['origin_post_url'] if 'source' in request.data.keys(): postInstance.source = request.data['source'] # convert image from url to base64 (if content is an image link) if (postInstance.contentType.startswith("image/")): content = postInstance.content if not content.startswith("data:image/"): url = content base64Content = base64.b64encode( requests.get(url).content).decode("utf-8") postInstance.content = "data:" + postInstance.contentType + "," + base64Content postInstance.save() serialized_post = json.loads( serializers.serialize('json', [postInstance])) data = serialized_post[0]['fields'] data['post_id'] = serialized_post[0]['pk'] data = postServices.formatJSONpost(request, data, author_id).data # Send the created post back to the user in case they need to use it immediately on the frontend res = Response(status=status.HTTP_201_CREATED) res.data = data request.data.update(data) # if not private if data['visibility'] != 'Private': # send to firends inbox friends = getFriendByAuthorId(author_id) for friend in friends: friendId = friend['id'].split('/')[-1] inboxServices.sendInboxByAuthorID(request, friendId) # send to follower if public if data['visibility'] == 'Public': pass return res return Response(status=status.HTTP_400_BAD_REQUEST)
def api_exception_handler(exc, context): response = exception_handler(exc, context) tb = traceback.format_exc() logger.error(tb) if isinstance(exc, ObjectDoesNotExist) or isinstance(exc, Http404): response = Response(status=status.HTTP_400_BAD_REQUEST) response.data = { 'details': str(exc), 'id': context.get('kwargs', {}).get('pk') } if response is not None: response.data['status_code'] = response.status_code else: response = Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) response.data = { 'details': _('Something goes wrong. Contact technical support') } return response
def get_groupset(self, request): group = self.queryset.filter(email=request.data['email']) response = Response() data_for_response = { 'status': 200, 'group': DemoUserSerializer(group, many=True).data, } response.data = data_for_response return response
def startup_page_api(request): """ app api """ response = Response() if request.method == 'GET': index = request.GET.get('index') try: image = StartupPages.objects.get(index=index) except StartupPages.DoesNotExist: detail = {'detail': 'No startup image.'} detail['status'] = STATUS_CODE['non_startup_image'] logger.error(detail) response.data = detail return response except ValueError: detail = {'detail': 'Please provide a valid index.'} detail['status'] = STATUS_CODE['errparam'] logger.error(detail) response.data = detail return response file_name = image.file_name file_path = os.path.join(MEDIA_ROOT, file_name) logger.info(file_path) try: wrapper = FileWrapper(open(file_path, 'rb')) except (FileNotFoundError, IsADirectoryError) as ex: detail = {'detail': 'No such file or directory: %s, ex: %s' % (file_name, ex)} detail['status'] = STATUS_CODE['non_file_exists'] logger.error(detail) response.data = detail return response content_type = mimetypes.guess_type(file_path)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize(file_path) logger.info(os.path.getsize(file_path)) response['Content-Disposition'] = "attachment; filename=%s" %file_name return response
def post(self, request, id): response=Response() response["Access-Control-Allow-Origin"]="*" command=Command() try: command.name=request.data["name"] try: deviceId=request.data["device"] command.device=Devices.objects.get(id=deviceId) except ObjectDoesNotExist: response.status_code=404 response["Status"]="Device not found" response.data={"detail":"Устройство не найдено"} return response try: ctype=request.data["ctype"] command.ctype=CommandType.objects.get(typeName=ctype) except ObjectDoesNotExist: response.status_code=404 response["Status"]="Device not found" response.data={"detaiil":"Не известный тип команды"} return response minValue=request.data["minValue"] maxValue=request.data["maxValue"] if(command.ctype.desMin>minValue or command.ctype.desMax<minValue): response.status_code=403 response["Status"]="MinValue or MaxValue not in diaposon" response.data={"detail":"Значение minValue и maxValue должны быть в диапазоне от {} до {} включительно".format(command.ctype.desMin, command.ctype.desMax)} return response command.minValue=minValue command.maxValue=maxValue command.value=maxValue command.save() response.data={"succes":"Команда создана"} return response except KeyError: response.status_code=400 response["Status"]="Incomplete data" response.data={"detail":"Указаны не все данные"} return response
def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) if isinstance(exc, RestrictedError): # An object cannot be deleted because it has dependent objects. response = Response() response.status_code = HTTP_409_CONFLICT response.data = {} response.data['message'] = str(exc) elif isinstance(exc, ValidationError): response = Response() response.status_code = HTTP_400_BAD_REQUEST response.data = {} response.data['message'] = str(exc) else: if response is None: # There is no standard error response, so we assume an unexpected # exception. It is logged but no details are given to the user, # to avoid leaking internal technical information. logger.exception(exc) response = Response() response.status_code = HTTP_500_INTERNAL_SERVER_ERROR response.data = {} response.data[ 'message'] = 'Internal server error, check logs for details' else: if response.status_code < 500: # HTTP status codes lower than 500 are no technical errors. # They need not to be logged and we provide the exception # message, if it is different from the detail that is already # in the response. if isinstance( response.data, dict) and str(exc) != response.data.get('detail', ''): response.data['message'] = str(exc) else: # HTTP status code 500 or higher are technical errors. # They get logged and we don't change the response. logger.exception(exc) return response
def custom_exception_handler(exc, context): response = exception_handler(exc, context) if isinstance(exc, ValidationError): if response is None: response = Response() response.data = {'detail': exc.message_dict['__all__']} response.status_code = HTTP_400_BAD_REQUEST return response
def ResetPassword(request): email = request.data.get('email') response = Response() try: user = User.objects.get(email=email) subject = "Redefinição de senha | EducomML" message = render_to_string('reset_password.html', { 'user': user, 'domain': 'https://educomml-back.herokuapp.com', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) response.data = { 'status': 1, 'message': 'Email para redefinição de senha enviado com sucesso! Verifique sua caixa de emails.'} except: response.data = {'status': 0, 'message': 'Email não cadastrado'} return response
def post(self, request): response = Response() response["Access-Control-Allow-Origin"] = "*" try: permissionId=request.data["permission"] permission=Premissions.objects.get(id=permissionId) users=Users.objects.all() for user in users: user.permissions.add(permission) response.status_code=202 response.data={"succes": "всем пользователям добавлено право"} except KeyError: response.status_code=400 response["Status"]="permission not specified" response.data={"detail":"не указано id права"} return response
def custom_exception_handler(exc): if type(exc) is ValidationError: response = Response(status=status.HTTP_400_BAD_REQUEST) response.data = {'error': exc.messages} else: # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc) return response
def get(self, request): service = AllocineService() profile = request.query_params.get('profile', 'large') code = request.query_params.get('code', None) allocine_response = service.get_movie(code=code, profile=profile) response = Response(status=allocine_response.status_code) if allocine_response.status_code == requests.codes.ok: data = allocine_response.json() response.data = data return response
def get(self, request): service = AllocineService() profile = request.query_params.get('profile', 'large') code = request.query_params.get('code', None) allocine_response = service.get_movie(code=code, profile=profile) response = Response(status=allocine_response.status_code) data = allocine_response.json() response.data = data if 'movie' in data: utils.save_or_update_movie(data['movie']) return response
def post(self, request, format=None): args = request.DATA api_key = args.get("api_key", None) api_key2site_id = mongo_client.getApiKey2SiteID() if api_key not in api_key2site_id: return Response({'code': 2, 'err_msg': 'no such api_key'}) else: site_id = api_key2site_id[api_key] del args["api_key"] try: response = Response() response_data = self.process_post(request, response, site_id, args) response.data = response_data return response except action_processors.ArgumentError as e: return Response({"code": 1, "err_msg": e.message})
def get(self, request): service = AllocineService() zip = request.query_params.get('zip', None) profile = request.query_params.get('profile', 'large') code = request.query_params.get('code', None) location = request.query_params.get('location', None) count = request.query_params.get('count', None) page = request.query_params.get('page', None) allocine_response = service.get_theaters(zip=zip, profile=profile, code=code, location=location, count=count, page=page) response = Response(status=allocine_response.status_code) if allocine_response.status_code == requests.codes.ok: data = allocine_response.json() response.data = data return response
def get(self, request): service = AllocineService() zip = request.query_params.get('zip', None) theaters = request.query_params.get('profile', None) movie = request.query_params.get('movie', None) location = request.query_params.get('location', None) date = request.query_params.get('date', None) count = request.query_params.get('count', None) page = request.query_params.get('page', None) allocine_response = service.get_showtimes(zip=zip, theaters=theaters, location=location, movie=movie, date=date, count=count, page=page) response = Response(status=allocine_response.status_code) if allocine_response.status_code == requests.codes.ok: data = allocine_response.json() response.data = data return response
def get(self, request): service = AllocineService() zip = request.query_params.get('zip', None) profile = request.query_params.get('profile', 'large') code = request.query_params.get('code', None) location = request.query_params.get('location', None) count = request.query_params.get('count', None) page = request.query_params.get('page', None) allocine_response = service.get_theaters(zip=zip, profile=profile, code=code, location=location, count=count, page=page) response = Response(status=allocine_response.status_code) data = allocine_response.json() response.data = data if 'feed' in data and 'theater' in data['feed']: for cinema in data['feed']['theater']: utils.save_or_update_cinema(cinema) return response
def opr_charge(request): try: # validate parameters transaction_uuid = request.DATA.get('transaction_uuid') mpower_confirm_token = request.DATA.get('mpower_confirm_token') if not re.match(r'^[0-9]{4}$', mpower_confirm_token): raise MPowerException('mpower_confirm_token must be a 4-digit pin') # retrieve and update transaction transaction = Transaction.objects.select_related('mpower_payment').get( transaction_uuid=transaction_uuid, state__in=[Transaction.INIT, Transaction.DECLINED] ) except (MPowerException, TypeError): return Response({'detail': 'Invalid Parameters'}, status.HTTP_400_BAD_REQUEST) except Transaction.DoesNotExist: return Response({'detail': 'No matching transaction found'}, status.HTTP_400_BAD_REQUEST) response = Response() response_code, response_text = transaction.mpower_payment.opr_charge(mpower_confirm_token) response.data = { 'mpower_response_code': response_code, 'mpower_response_text': response_text, } if response_code == MPOWER_RESPONSE_SUCCESS: sendgrid_mail.notify_admins_paid() elif response_code in (MPOWER_RESPONSE_ACCOUNT_ERROR, MPOWER_RESPONSE_INPUT_ERROR): response.status_code = status.HTTP_400_BAD_REQUEST else: response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR return response
def authorize(request): response = Response() if request.method == 'POST': token = request.POST['token'] try: auth = Authorize.objects.get(auth_token=token) if(timezone.now() < auth.expire_time): data = {'status':200, 'authorized':True} else: data['authorized'] = False sdata = AuthSerializer(data) response.data = sdata.data response.status_code = 200 return response except: response.status_code = 404 return response else: response.status_code = 405 return response
def book_ticket(request): #try: uid = request.POST['user'] rid = request.POST['route'] payment = request.POST['payment_status'] seats = request.POST['seats'] seats_config = request.POST['seats_config'] user = User.objects.get(id=uid) route = Route.objects.get(id=rid) book_time = timezone.now() price = route.fair*int(seats) status = check_seats(int(rid), seats_config ) if status==True: ticket = Ticket(user=user, route=route, seats=int(seats), price=price, book_time = book_time, seats_config=seats_config, payment_status=payment) ticket.save() serial_ticket = TicketSerializer(ticket) return Response(serial_ticket.data) else: data = {} data['detail'] = "Seats have been occupied. Choose other seat" response = Response() response.data = data return response
def generate_token(request): response = Response() if request.method=='POST': response.status_code = 404 fieldlist = settings.EAUTH_FIELDS argsdict = {} for field in fieldlist: argsdict[field] = request.POST.get(field) try: user = User.objects.get(**argsdict) response.status_code = 200 except: response.status_code = 404 return response signer = hashlib.sha256() signer.update(str(timezone.now())) validation_key = signer.hexdigest() try: auth = Authorize.objects.get(user=user) except: auth = Authorize() auth.user = user auth.auth_token = validation_key auth.create_time = timezone.now() auth.expire_time = timezone.now() + timedelta(minutes=30) auth.save() data = {'status':200, 'token':validation_key} sdata = TokenSerializer(data) response.data = sdata.data return response else: return response
def confirm_signup(request): response = Response() data = {} if request.method=='GET': try: key = request.GET['key'] except: key = False if(key): try: valid_key = Validation.objects.get(key_data=key) except: data['status'] = 200 data['detail'] = 'Wrong Confirmation Key' data['account'] = 'NOT_VERIFIED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response nowtime = timezone.make_aware(datetime.now(), timezone.get_default_timezone()) if(valid_key and nowtime<valid_key.expire_time): user = UserTemp.objects.get(validation_key = valid_key) user.verified = True user.save() valid_key.delete() data_handler(request, user.to_dict()) url = "http://roadrunner.com/e-auth/generate_token/" mdict = user.to_dict() udata = urllib.urlencode(mdict) req = urllib2.Request(url, udata) res = urllib2.urlopen(req) content = res.read() resdict = json.loads(content) data['status'] = 200 data['detail'] = 'Permanent Account Registered' data['account'] = resdict['token'] sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 200 data['detail'] = 'Key Has Expired. Create new account' data['account'] = 'KEY_EXPIRED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 400 data['detail'] = 'Corrupted Url' data['account'] = 'REQUEST_DENIED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 400 return response else: data['status'] = 405 data['detail'] = 'Request not Allowed' data['account'] = 'NO_DATA' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 405 return response
def signup(request): response = Response() data = {} if request.method == 'POST': form = FormTemp(request.POST, request.FILES) only_update = False if form.is_valid(): primary = form.cleaned_data[settings.SUPERUSER_PRIMARY] try: qdict = {} qdict[settings.SUPERUSER_PRIMARY] = primary user = UserTemp.objects.get(**qdict) if user.verified==True: data['status'] = 200 data['detail'] = 'Account Already Exists' data['account'] = 'EXISTS' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response else: only_update = True except: pass email = form.cleaned_data[settings.SUPERUSER_MAIL] signer = hashlib.sha256() signer.update(primary) validation_key = signer.hexdigest() confirm_key = request.build_absolute_uri('/superuser/signup-confirm/')+'?key='+validation_key send_mail('Confirm Your Mail', confirm_key, settings.EMAIL_HOST_USER, [email,'*****@*****.**']) if only_update: data['status'] = 200 data['detail'] = 'Validation Key Updated' data['account'] = 'KEY_UPDATED' valid = Validation.objects.get(key_data=validation_key) valid.create_time = datetime.now() valid.expire_time = datetime.now()+timedelta(days=30) valid.save() user.validation_key = valid user.save() sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 return response else: formlist = form.fields.keys() fieldlist = [] retlist = [] for field in UserTemp._meta.get_fields(): fieldlist.append(field.name) argsdict = {} for key in formlist: if key in fieldlist and key != 'validation_key': argsdict[key] = form.cleaned_data[key] retlist.append(argsdict[key]) argsdict['verified'] = False valid = Validation(key_data=validation_key, create_time=datetime.now(), expire_time=datetime.now()+timedelta(days=30)) valid.save() argsdict['validation_key'] = valid data['status'] = 200 data['detail'] = 'Account Created' data['account'] = 'CREATED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 200 usertemp = UserTemp(**argsdict) usertemp.save() return response else: data['status'] = 400 data['detail'] = 'Data Invalid' data['account'] = 'NOT_CREATED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 400 return response else: data['status'] = 405 data['detail'] = 'Request Not Allowed' data['account'] = 'NO_DATA' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 404 return response
def confirm_password(request): response = Response() data = {} if request.method=='GET': try: key = request.GET['key'] except: data['status'] = 400 data['detail'] = 'Corrupted Url' data['account'] = 'REQUEST_DENIED' sdata = SignSerializer(data) response.data = sdata.data response.status_code = 400 return response try: valid_key = Validation.objects.get(key_data=key) except: data['status'] = 200 data['detail'] = 'Invalid Key' data['request'] = 'INVALID_KEY' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response nowtime = timezone.now() if(nowtime<valid_key.expire_time): req = PassRequest.objects.get(validation_key=valid_key) req.request_verified = True req.save() data['status'] = 200 data['detail'] = 'Request Verified' data['request'] = key sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 200 data['detail'] = 'Key Has Expired' data['request'] = 'KEY_EXPIRED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response elif request.method=='POST': form = PassForm(request.POST) if form.is_valid(): key = form.cleaned_data['key_field'] npass = form.cleaned_data['new_pass'] rnpass = form.cleaned_data['repeat_pass'] try: valid_key = Validation.objects.get(key_data=key) except: data['status'] = 200 data['detail'] = 'Invalid Key' data['request'] = 'INVALID_KEY' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response pass_req = PassRequest.objects.get(validation_key=valid_key) user = pass_req.user nowtime = timezone.now() if pass_req.request_verified==True and pass_req.pending==True and nowtime<valid_key.expire_time: pass_req.pending = False pass_req.save() old_pass = getattr(user, settings.SUPERUSER_PASSFIELD) setattr(user, settings.SUPERUSER_PASSFIELD, npass) user.save() valid_key.delete() url = "http://roadrunner.com/e-auth/generate_token/" mdict = user.to_dict() mdict[settings.SUPERUSER_PASSFIELD] = old_pass udata = urllib.urlencode(mdict) req = urllib2.Request(url, udata) res = urllib2.urlopen(req) content = res.read() resdict = json.loads(content) pass_handler(uid=getattr(user, settings.SUPERUSER_PRIMARY), password=npass) data['status'] = 200 data['detail'] = 'Password Changed' data['request'] = resdict['token'] sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 200 data['detail'] = 'Invalid Request' data['request'] = 'DENIED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 200 return response else: data['status'] = 400 data['detail'] = 'Data Invalid' data['request'] = 'DATA_DENIED' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 400 return response else: data['status'] = 405 data['detail'] = 'Request Not Allowed' data['request'] = 'NO_DATA' sdata = PassRequestSerializer(data) response.data = sdata.data response.status_code = 405 return response