def login(request, **kwargs): # self.method_check(request, allowed=['post']) # self.is_authenticated(request) # self.throttle_check(request) developer_key = request.GET.get('developer_key') username = request.GET.get('username') password = request.GET.get('password') if not developer_key or not username or not password: return HttpUnauthorized() try: dev_key = DeveloperApiKey.objects.get(key=developer_key, approved=True) except DeveloperApiKey.DoesNotExist: return HttpUnauthorized() user = authenticate(username=username, password=password) if user: try: key = UserApiKey.objects.get(user=user, developer_key=dev_key) except UserApiKey.DoesNotExist: key = UserApiKey(user=user, developer_key=dev_key) key.save() # self.log_throttled_access(request) serializer = Serializer() desired_format = determine_format(request, serializer) serialized = serializer.serialize({'key': key.key}, desired_format) return HttpResponse(content=serialized, content_type=build_content_type(desired_format)) else: return HttpUnauthorized()
def wrapper(request, *args, **kwargs): auth = api_auth_class.is_authenticated(request) if auth: if isinstance(auth, HttpUnauthorized): return auth try: allowed_ips = request.user.api_key.apikeysettings.ip_whitelist except (ApiKey.DoesNotExist, ApiKeySettings.DoesNotExist): allowed_ips = [] if allowed_ips and get_ip(request) not in allowed_ips: return HttpUnauthorized() return view(request, *args, **kwargs) response = HttpUnauthorized() return response
def obj_get(self, request=None, **kwargs): # Make sure the resource name /schedule/FOO/ is equal to their username if kwargs['pk'] != request.user.username: raise ImmediateHttpResponse(HttpUnauthorized()) # Call the script, pass in username and password on via STDIN # so username/password doesn't show up in the process table # when passing using CLI arguments process = Popen( [settings.CASPERJS_BIN, settings.FETCH_SCHEDULE_SCRIPT], stdout=PIPE, stdin=PIPE, stderr=STDOUT) output = process.communicate( input="%s\n%s" % (request.user.username, request.user.password))[0].strip() # hardcoded output # output = '1|ANTH*1150*01|2012/01/09|2012/04/20|LEC|Tues, Thur |10:00AM - 11:20AM|ROZH, Room 101,1|ANTH*1150*01|2012/04/19|2012/04/19|EXAM|Thur |07:00PM - 09:00PM|ROZH, Room 101,2|PHIL*2140*DE|2012/01/09|2012/04/20|Distance Education|Days TBA|Times TBA|Room TBA,2|PHIL*2140*DE|2012/04/18|2012/04/18|EXAM|Wed |11:30AM - 01:30PM|MACN, Room 113' parser = scheduleparser.ScheduleParser() schedule = parser.get_schedule(output) return_object = ScheduleObject(initial=schedule) return_object.user = request.user.username return return_object
def emission_update(self, request, **kwargs): # TODO: check for scheduler permissions if not request.user.is_authenticated(): return HttpUnauthorized() e = Emission.objects.get(**self.remove_api_resource_names(kwargs)) data = json.loads(request.body) locked = data.get('locked', 0) color = data.get('color', 0) if int(locked) == 1: e.locked = True else: e.locked = False e.color = int(color) data = {} e.save() #action.send(request.user, verb='updated', target=e.content_object) return self.json_response(request, data)
def obj_delete(self, request=None, **kwargs): # Make sure that the user can modifty. observation_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, observation_id): raise ImmediateHttpResponse( HttpUnauthorized("Cannot edit other users' observations")) return super(ObservationResource, self).obj_delete(request, **kwargs)
def obj_create(self, bundle, **kwargs): if bundle.request.user.is_authenticated(): return super(QuoteResource, self).obj_create(bundle, poster=bundle.request.user, **kwargs) raise ImmediateHttpResponse(HttpUnauthorized('Not authenticated'))
def wrapper(request, *args, **kwargs): auth = auth_check(request) if auth: return view(request, *args, **kwargs) response = HttpUnauthorized() return response
def obj_delete_list(self, bundle, **kwargs): raise ImmediateHttpResponse( response=HttpUnauthorized( json.dumps( {'error': 'You can\'t delete membership without id'}) ) )
def bulk_add(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) # Make sure user is superuser. if not request.user.is_superuser: raise ImmediateHttpResponse(HttpUnauthorized("Cannot bulk add")) # Try making a new user try: user_list = json.loads(request.raw_post_data) print user_list import_users = bulk_import.importUsers(user_list) objects = [] for result in import_users: bundle = self.build_bundle(obj=result, request=request) bundle = self.full_dehydrate(bundle) objects.append(bundle) object_list = { 'objects': objects, } return self.create_response(request, object_list) except ValueError: return self.create_response(request, "Invalid JSON", response_class=HttpApplicationError)
def update_product_prices(request): from dateutil import parser try: if request.method == 'POST': if not is_authenticated(request): return HttpUnauthorized() data = json.loads(request.body) ids = [s.split("/")[-2] for s in data["products"]] products = Product.objects.filter(id__in=ids) prices_dicts = [{ "unit": UNIT.enum_dict[p["unit"]], "amount": p["amount"], "currency": p["currency"], "started_at": parser.parse(p["started_at"]).date(), "ended_at": parser.parse(p["ended_at"]).date() } for p in data["prices"]] for product in products: product.prices.all().delete() for price_dict in prices_dicts: Price(product=product, **price_dict).save() return HttpResponse() else: return HttpBadRequest() except Exception: traceback.print_exc()
def test_various_statuses(self): created = HttpCreated(location='http://example.com/thingy/1/') self.assertEqual(created.status_code, 201) self.assertEqual(created['Location'], 'http://example.com/thingy/1/') # Regression. created_2 = HttpCreated() self.assertEqual(created_2.status_code, 201) self.assertEqual(created_2['Location'], '') accepted = HttpAccepted() self.assertEqual(accepted.status_code, 202) no_content = HttpNoContent() self.assertEqual(no_content.status_code, 204) see_other = HttpSeeOther() self.assertEqual(see_other.status_code, 303) not_modified = HttpNotModified() self.assertEqual(not_modified.status_code, 304) bad_request = HttpBadRequest() self.assertEqual(bad_request.status_code, 400) unauthorized = HttpUnauthorized() self.assertEqual(unauthorized.status_code, 401) not_found = HttpNotFound() self.assertEqual(not_found.status_code, 404) not_allowed = HttpMethodNotAllowed() self.assertEqual(not_allowed.status_code, 405) conflict = HttpConflict() self.assertEqual(conflict.status_code, 409) gone = HttpGone() self.assertEqual(gone.status_code, 410) toomanyrequests = HttpTooManyRequests() self.assertEqual(toomanyrequests.status_code, 429) not_implemented = HttpNotImplemented() self.assertEqual(not_implemented.status_code, 501)
def post_list( self, request, **kwargs ): response_data = { 'success': False } try: # Check if the user has enough permission to create a new # repository. bundle = self.build_bundle( request=request ) if not self.authorized_create_list( None, bundle ): return HttpUnauthorized() # TODO: Support POSTs through the API using the API keys user = bundle.request.user form = NewBatchRepoForm( request.POST, request.FILES, user=user ) if form.is_valid(): new_repo = form.save() response_data[ 'success' ] = True response_data[ 'repo' ] = new_repo.mongo_id else: response_data[ 'errors' ] = [( k, v[0] ) for k, v in form.errors.items()] except Exception as e: import traceback traceback.print_exc() return self.create_response( request, response_data )
def is_authenticated(self, request, **kwargs): try: secret_key = self.extract_credentials(request) except ValueError: return HttpUnauthorized() if not secret_key: return HttpUnauthorized() try: user = User.objects.get(comics_profile__secret_key=secret_key, is_active=True) except (User.DoesNotExist, User.MultipleObjectsReturned): return HttpUnauthorized() request.user = user return True
def __init__(self, wallet=None): response = { 'error': 'not_enough_balance', 'message': 'El monedero no tiene suficiente saldo disponible para realizar la operación' } self.response = HttpUnauthorized(content=json.dumps(response), content_type='application/json')
def __init__(self, wallet=None): response = { 'error': 'wrong_pincode', 'message': 'El código pin introducido no es correcto' } self.response = HttpUnauthorized(content=json.dumps(response), content_type='application/json')
def _unauthorized(self): response = HttpUnauthorized() new_uuid = uuid.uuid4() opaque = hmac.new(str(new_uuid), digestmod=sha1).hexdigest() response['WWW-Authenticate'] = python_digest.build_digest_challenge( time.time(), getattr(settings, 'SECRET_KEY', ''), self.realm, opaque, False) return response
def unauthorized(cls, msg, extend_dict=None): error_dict = { 'status': 'error', 'message': msg, } if extend_dict: error_dict.update(extend_dict) msg_json = json.dumps(error_dict) return HttpUnauthorized(msg_json, content_type='application/json')
def wrapper(request, *args, **kwargs): auth = api_auth_class.is_authenticated(request) if auth: if isinstance(auth, HttpUnauthorized): return auth return view(request, *args, **kwargs) response = HttpUnauthorized() return response
def obj_create(self, bundle, request=None, **kwargs): # Get the user of the observation by fully hydrating the bundle and then # check if the user is allowed to add to this observation. user = self.full_hydrate(bundle).obj.observation.staff.user if not request.user.is_superuser and user != request.user: raise ImmediateHttpResponse( HttpUnauthorized( "Cannot add other users' animal observations")) return super(AnimalObservationResource, self).obj_create(bundle, request, **kwargs)
def obj_get(self, request=None, **kwargs): # Make sure the resource name /schedule/FOO/ is equal to their username if kwargs['pk'] != request.user.username: raise ImmediateHttpResponse(HttpUnauthorized()) try: parser = mealplanparser.MealPlanParser(request.user.username, request.user.password) data = parser.get_balance() except mealplanparser.InvalidCredentialsException, e: raise ImmediateHttpResponse(HttpNotFound(e.message))
def dispatch_list(self, request, **kwargs): try: return super(UserDomainsResource, self).dispatch_list(request, **kwargs) except ImmediateHttpResponse as immediate_http_response: if isinstance(immediate_http_response.response, HttpUnauthorized): raise ImmediateHttpResponse(response=HttpUnauthorized( content='Username or API Key is incorrect', content_type='text/plain')) else: raise
def _unauthorized(self): response = HttpUnauthorized() new_uuid = uuid.uuid4() opaque = hmac.new(str(new_uuid).encode('utf-8'), digestmod=sha1).hexdigest() response['WWW-Authenticate'] = python_digest.build_digest_challenge( timestamp=time.time(), secret=settings.SECRET_KEY, realm=self.realm, opaque=opaque, stale=False) return response
def obj_get(self, bundle, **kwargs): """ Returns mongodb document from provided id. """ obj = self.get_collection()\ .find_one( { '_id': ObjectId( kwargs.get( 'pk' ) ) } ) try: if self.authorized_read_detail(obj, bundle): return Document(obj) except ValueError: raise ImmediateHttpResponse(HttpUnauthorized())
def extract_credentials(self, request): #print request.META if request.META.get('HTTP_X_IDENTITY') and request.META.get( 'HTTP_X_SIGNATURE'): x_identity = request.META['HTTP_X_IDENTITY'] x_signature = request.META['HTTP_X_SIGNATURE'] else: return HttpUnauthorized() #this throws some weird error# ValueError("Incorrect authorization headers.") return x_identity, x_signature
def login(self, request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is None: raise ImmediateHttpResponse(HttpUnauthorized()) if not user.is_active: raise ImmediateHttpResponse(HttpForbidden()) auth.login(request, user) return self.create_response(request, self._serialize_user(request, user))
def obj_get_list(self, bundle, **kwargs): """ Maps mongodb documents to Document class. """ try: objects = map( Document, self.authorized_read_list(self.get_collection(), bundle)) except ValueError: raise ImmediateHttpResponse(HttpUnauthorized()) return objects
def obj_update(self, bundle, request=None, **kwargs): # PATCH fix bundle.data['animal'] = bundle.data['animal'].data['resource_uri'] if not isinstance(bundle.data['behavior'], basestring): bundle.data['behavior'] = bundle.data['behavior'].data[ 'resource_uri'] # Make sure that the user can modifty. ao_id = int(kwargs.pop('pk', None)) if not self.can_modify_observation(request, ao_id): raise ImmediateHttpResponse( HttpUnauthorized( "Cannot edit other users' animal observations")) return super(AnimalObservationResource, self).obj_update(bundle, request, **kwargs)
def bulk_add(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) # Make sure user is superuser. if not request.user.is_superuser: raise ImmediateHttpResponse(HttpUnauthorized("Cannot bulk add")) # try loading the json try: enrichment_list = json.loads(request.raw_post_data) except ValueError, e: raise ValueError('Bad JSON: %s' % e)
def bulk_add(self, request, **kwargs): self.method_check(request, allowed=['post']) self.is_authenticated(request) self.throttle_check(request) # Make sure user is superuser if not request.user.is_superuser: raise ImmediateHttpResponse( HttpUnauthorized("Cannot edit other users' observations")) # try to load the json file try: animal_list = json.loads(request.raw_post_data) except ValueError, e: raise ValueError('Bad JSON: %s' % e)
def check_perm(request, perm, obj=None, raise_on_fail=True): fail = False if obj: if not request.user.has_perm(perm, obj): fail = True else: if not request.user.has_perm(perm): fail = True if fail and raise_on_fail: raise ImmediateHttpResponse(response=HttpUnauthorized()) elif fail: return False else: return True