def handle(self, *args, **options): self.options = options if len(args) < 1 or len(args) > 1: print >>sys.stderr, "takes one argument: %s" % self.args return user = args[0] u = None try: u = User.objects.get(username=user) print 'User {0} exists'.format(user) except User.DoesNotExist: print 'User {0} does not exist - creating'.format(user) u = User(username=user, is_staff=True) u.save() try: key = ApiKey.objects.get(user=u) print 'User {0} already has api key, skipping creation'.format(user) except ApiKey.DoesNotExist: print 'User {0} does not have an api key - creating'.format(user) u_apikey = ApiKey(user=u) u_apikey.key = u_apikey.generate_key() u_apikey.save() u.save() key = ApiKey.objects.get(user=u) print 'Key: {0}'.format(key)
def api_key(request): ''' Allows the user to generate an API key for the REST API ''' context = {} context.update(csrf(request)) try: key = ApiKey.objects.get(user=request.user) except ApiKey.DoesNotExist: key = False if request.GET.get('new_key'): if key: key.delete() key = ApiKey() key.user = request.user key.save() # Redirect to get rid of the GET parameter return HttpResponseRedirect(reverse('core:api-key')) context['key'] = key return render(request, 'user/api_key.html', context)
def twitter_login_callback(self, request=None, **kwargs): ''' when we have the oauth verifier then send it through this api ''' #get the params twitter need post = simplejson.loads(request.body) twitter_key = settings.TWITTER_KEY twitter_secret = settings.TWITTER_SECRET oauth_token = request.session.get('OAUTH_TOKEN', '') oauth_token_secret = request.session.get('OAUTH_TOKEN_SECRET', '') oauth_verifier = post.get('oauth_verifier', '') #get the params from the login twitter = Twython(twitter_key, twitter_secret,oauth_token, oauth_token_secret) final_step = twitter.get_authorized_tokens(oauth_verifier) user_oauth_token = final_step['oauth_token'] user_oauth_token_secret = final_step['oauth_token_secret'] #find existing user or create a new one try: userprofile = UserProfile.objects.get(twitter_oauth_token=user_oauth_token, twitter_oauth_token_secret=user_oauth_token_secret) user = userprofile.user except: #create a user and user profile api_key = ApiKey() username = api_key.generate_key()[0:30] password = api_key.generate_key()[0:30] user = User() user.username = username user.is_active = True user.password = password user.save() userprofile = user.profile userprofile.twitter_oauth_token = user_oauth_token userprofile.twitter_oauth_token_secret = user_oauth_token_secret userprofile.save() #delete all the old api keys api_keys = ApiKey.objects.filter(user=user) api_keys.delete() #create a new api key api_key, created = ApiKey.objects.get_or_create(user=user) api_key.save() #store the keys in the session request.session['api_key'] = api_key.key request.session['username'] = user.username ur = UserProfileResource() ur_bundle = ur.build_bundle(obj=user.profile, request=request) return self.create_response(request, { 'is_logged_in': True, 'message': 'The user is logged in', 'username': user.username, 'api_key': api_key.key, 'user_profile': json.loads(ur.serialize(None, ur.full_dehydrate(ur_bundle), 'application/json')) })
def create_profiles(sender, **kw): user = kw["instance"] if kw["created"]: Token.objects.get_or_create(user=user) UserProfile.objects.get_or_create(user=user) UserBmiProfile.objects.get_or_create(user=user, ) apiKey = ApiKey(user=user, key="1") apiKey.save()
def generate_new_api_key(self): key, created = ApiKey.objects.get_or_create(user=self) if not created: #DON'T TRY AND CHANGE THE KEY VALUE. DELETE INSTEAD key.delete() key = ApiKey(user=self) key.save() return key.key
def generate_new_api_key(self): key, created = ApiKey.objects.get_or_create(user = self) if not created: #DON'T TRY AND CHANGE THE KEY VALUE. DELETE INSTEAD key.delete() key = ApiKey(user = self) key.save() return key.key
def login(self, request, **kwargs): # Allows POST request self.method_check(request, allowed=['post']) # Deserialize the JSon response data = self.deserialize(request, request.raw_post_data, format=request.META.get( 'CONTENT_TYPE', 'application/json')) # Get the needed datas username = data.get('username', '') password = data.get('password', '') # Try to authenticate the user user = authenticate(username=username, password=password) # If user exist and is active if user: if user.is_active: # Get the associated member member = Member.objects.get(user_id=user.id) memberDict = member.__dict__ preferedCategoryIDs = member.preferedCategoryIDs.all() memberDict['preferedCategories'] = [ cat.name for cat in preferedCategoryIDs ] del memberDict["_state"] del memberDict["user_id"] # Log the user login(request, user) api_key = ApiKey.objects.filter(user=user) if len(api_key) == 0: api_key = ApiKey(user=user) api_key.save() else: api_key = api_key[0] # Add the ApiKey memberDict["api_key"] = api_key.key # Return success=True and the member object return self.create_response(request, { 'success': True, 'member': memberDict, }) else: # If user not active, return success = False and disabled return self.create_response(request, { 'success': False, 'reason': 'disabled', }, HttpForbidden) else: # If user does not exist, return success=False and incorrect return self.create_response(request, { 'success': False, 'reason': 'incorrect', }, HttpUnauthorized)
class ApiResourceTests(ResourceTestCase): """abstract class to make resource-specific tests more concise""" def setUp(self): super(ApiResourceTests, self).setUp() self.user = User.objects.create_superuser('test user', '*****@*****.**', 'password') self.api_key = ApiKey(user=self.user) self.api_key.save() try: obj = self.model(name='test') obj.save() self.list_uri = '/api/sku_service/%s/' % self.uri_spec self.detail_uri = self.list_uri + '1/' except Exception: pass self.payload = json.dumps({'name': 'test'}) def get_credentials(self): return self.create_apikey(self.user.username, self.api_key) @expectedFailure def test_get_list(self): response = self.api_client.get(self.list_uri, authentication=self.get_credentials()) self.assertHttpOK(response) @expectedFailure def test_get_list_unauthorized(self): response = self.api_client.get(self.list_uri) self.assertHttpUnauthorized(response) @expectedFailure def test_get_detail(self): response = self.api_client.get(self.detail_uri, authentication=self.get_credentials()) self.assertHttpOK(response) @expectedFailure def test_get_detail_unauthorized(self): response = self.api_client.get(self.detail_uri) self.assertHttpUnauthorized(response) @expectedFailure def test_other_methods(self): response = self.api_client.delete(self.detail_uri, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.patch(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.post(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.put(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response)
def handle(self, *args, **options): from tastypie.models import ApiKey users = User.objects.all() for user in users: try: key = user.api_key except ApiKey.DoesNotExist: print('Creating API key for {}'.format(user.username)) k = ApiKey() k.user = user k.save()
def login(self, request, **kwargs): # Allows POST request self.method_check(request, allowed=['post']) # Deserialize the JSon response data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json')) # Get the needed datas username = data.get('username', '') password = data.get('password', '') # Try to authenticate the user user = authenticate(username=username, password=password) # If user exist and is active if user: if user.is_active: # Get the associated member member = Member.objects.get(user_id=user.id) memberDict = member.__dict__ preferedCategoryIDs = member.preferedCategoryIDs.all() memberDict['preferedCategories'] = [cat.name for cat in preferedCategoryIDs] del memberDict["_state"] del memberDict["user_id"] # Log the user login(request, user) api_key = ApiKey.objects.filter(user=user) if len(api_key) == 0: api_key = ApiKey(user=user) api_key.save() else: api_key = api_key[0] # Add the ApiKey memberDict["api_key"] = api_key.key # Return success=True and the member object return self.create_response(request, { 'success': True, 'member': memberDict, }) else: # If user not active, return success = False and disabled return self.create_response(request, { 'success': False, 'reason': 'disabled', }, HttpForbidden ) else: # If user does not exist, return success=False and incorrect return self.create_response(request, { 'success': False, 'reason': 'incorrect', }, HttpUnauthorized )
def fb_login(self, request=None, **kwargs): ''' will login the user using facebook ''' #get the params post = simplejson.loads(request.body) access_token = post.get('access_token') signed_request = post.get('signed_request') #get the email of the user fb_decode = fb_request_decode(signed_request) fb_user_id = fb_decode['fb_data']['user_id'] facebook=fb.graph.api(access_token) object=facebook.get_object(cat="single", id=fb_user_id, fields=[ ] ) email = object['email'] #find the user try: user = User.objects.get(email=email) except: #create the user object api_key = ApiKey() username = api_key.generate_key()[0:30] password = api_key.generate_key()[0:30] user = User() user.username = username user.email = email user.is_active = True user.password = password user.save() #delete all the old api keys api_keys = ApiKey.objects.filter(user=user) api_keys.delete() #create a new api key api_key, created = ApiKey.objects.get_or_create(user=user) api_key.save() ur = UserProfileResource() ur_bundle = ur.build_bundle(obj=user.profile, request=request) return self.create_response(request, { 'is_logged_in': True, 'message': 'The user is logged in', 'api_key': api_key.key, 'username': user.username, 'user_profile': json.loads(ur.serialize(None, ur.full_dehydrate(ur_bundle), 'application/json')) })
def handle(self, *args, **options): self.options = options if len(args) < 1 or len(args) > 1: print >>sys.stderr, "takes one argument: %s" % self.args return user = args[0] u = None try: u = User.objects.get(username=user) print 'User {0} exists'.format(user) except User.DoesNotExist: print 'User {0} does not exist - creating'.format(user) u = User(username=user, is_staff=True) u.save() print 'Setting metadata POST permissions.' for model_name in ['psmetadata', 'pspointtopointsubject', 'pseventtypes', 'psmetadataparameters']: for perm_name in ['add', 'change', 'delete']: perm = Permission.objects.get(codename='{0}_{1}'.format(perm_name, model_name)) print perm u.user_permissions.add(perm) u.save() try: key = ApiKey.objects.get(user=u) print 'User {0} already has api key, skipping creation'.format(user) except ApiKey.DoesNotExist: print 'User {0} does not have an api key - creating'.format(user) u_apikey = ApiKey(user=u) u_apikey.key = u_apikey.generate_key() u_apikey.save() u.save() key = ApiKey.objects.get(user=u) print 'Key: {0}'.format(key)
def handle(self, *args, **options): self.options = options if len(args) < 1 or len(args) > 1: print >>sys.stderr, "takes one argument: %s" % self.args return user = args[0] u = None try: u = User.objects.get(username=user) print 'User {0} exists'.format(user) except User.DoesNotExist: print 'User {0} does not exist - creating'.format(user) u = User(username=user, is_staff=True) u.save() print 'Setting timeseries permissions.' for resource in ['timeseries']: for perm_name in ['view', 'add', 'change', 'delete']: perm = Permission.objects.get( codename="esmond_api.{0}_{1}".format(perm_name, resource)) u.user_permissions.add(perm) u.save() try: key = ApiKey.objects.get(user=u) print 'User {0} already has api key, skipping creation'.format(user) except ApiKey.DoesNotExist: print 'User {0} does not have an api key - creating'.format(user) u_apikey = ApiKey(user=u) u_apikey.key = u_apikey.generate_key() u_apikey.save() u.save() key = ApiKey.objects.get(user=u) print 'Key: {0}'.format(key)
class PSAPIBaseTest(ResourceTestCase): fixtures = ['perfsonar_api_metadata.json'] def setUp(self): super(PSAPIBaseTest, self).setUp() #create user credentials self.noperms_user = User(username="******", is_staff=True) self.noperms_user.save() self.noperms_apikey = ApiKey(user=self.noperms_user) self.noperms_apikey.key = self.noperms_apikey.generate_key() self.noperms_apikey.save() self.admin_user = User(username="******", is_staff=True) self.admin_user.save() for model_name in ['psmetadata', 'pspointtopointsubject', 'pseventtypes', 'psmetadataparameters']: for perm_name in ['add', 'change', 'delete']: perm = Permission.objects.get(codename='{0}_{1}'.format(perm_name, model_name)) self.admin_user.user_permissions.add(perm) #Add timeseries permissions for perm_name in ['add', 'change', 'delete']: perm = Permission.objects.get(codename='esmond_api.{0}_timeseries'.format(perm_name)) self.admin_user.user_permissions.add(perm) self.admin_user.save() self.admin_apikey = ApiKey(user=self.admin_user) self.admin_apikey.key = self.admin_apikey.generate_key() self.admin_apikey.save() def create_noperms_credentials(self): return self.create_apikey(self.noperms_user.username, self.noperms_apikey.key) def create_admin_credentials(self): return self.create_apikey(self.admin_user.username, self.admin_apikey.key) def assertExpectedResponse(self, expected, url, get_params={}): response = self.client.get(url, get_params) self.assertHttpOK(response) data = json.loads(response.content) self.assertEquals(expected, data)
class ApiResourceTests(ResourceTestCase): """abstract class to make resource-specific tests more concise""" def setUp(self): super(ApiResourceTests, self).setUp() self.user = User.objects.create_superuser('test user', '*****@*****.**', 'password') self.api_key = ApiKey(user=self.user) self.api_key.save() try: obj = self.model(name='test') obj.save() self.list_uri = '/api/sku_service/%s/' % self.uri_spec self.detail_uri = self.list_uri + '1/' except Exception: pass self.payload = json.dumps({'name': 'test'}) def get_credentials(self): return self.create_apikey(self.user.username, self.api_key) @expectedFailure def test_get_list(self): response = self.api_client.get(self.list_uri, authentication=self.get_credentials()) self.assertHttpOK(response) @expectedFailure def test_get_list_unauthorized(self): response = self.api_client.get(self.list_uri) self.assertHttpUnauthorized(response) @expectedFailure def test_get_detail(self): response = self.api_client.get(self.detail_uri, authentication=self.get_credentials()) self.assertHttpOK(response) @expectedFailure def test_get_detail_unauthorized(self): response = self.api_client.get(self.detail_uri) self.assertHttpUnauthorized(response) @expectedFailure def test_other_methods(self): response = self.api_client.delete( self.detail_uri, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.patch(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.post(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response) response = self.api_client.put(self.detail_uri, data=self.payload, authentication=self.get_credentials()) self.assertHttpMethodNotAllowed(response)
class ApiTestCase(DirectSEOTestCase): fixtures = ['seo_views_testdata.json'] def setUp(self): super(ApiTestCase, self).setUp() # Create a test user and an API key for that user. self.user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email self.user.save() self.key = ApiKey(user=self.user) self.key.save() self.api_key = self.key.key self.auth_qs = '?&username=%s&api_key=%s' % (self.username, self.api_key) self.entry_1 = SeoSite.objects.get(group=1) self.detail_url = '/api/v1/seosite/{0}/'.format(self.entry_1.pk) self.serializer = Serializer() def deserialize(self, resp): return self.serializer.deserialize(resp.content, format=resp['Content-Type']) def test_not_authorized(self): """ Test if a user can gain access without an API key """ user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email user.save() resp = self.client.get("api/v1/jobsearch/?format=xml") self.assertEqual(resp.status_code, 404) resp = self.client.get("api/v1/seosite/?format=xml") self.assertEqual(resp.status_code, 404) key = ApiKey(user=self.user) def test_list_xml(self): resp = self.client.get("/api/v1/seosite/?%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_list_json(self): resp = self.client.get("/api/v1/seosite/?%s&format=json" % (self.auth_qs)) self.assertEqual(len(self.deserialize(resp)['objects']), 1) self.assertEqual(resp.status_code, 200) self.serializer.from_json(resp.content) def test_get_detail_xml(self): resp = self.client.get("/api/v1/seosite/1/%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_nopost(self): """ Ensure that POST requests are rejected. This test can be removed if/when we allow other methods besides GET to our resources. """ jobjson = ("""{"buid": 13543, "city": "Chester",\ "company": "Edward Jones", "country": "United States",\ "date_new": "2012-05-31T11:49:23",\ "mocs": "[\'021\', \'0193\', \'2820\', \'2G000\', \'2G091\',\ \'2R000\', \'2R071\', \'2R090\', \'2R171\', \'2S000\',\ \'2S071\', \'2S091\', \'2T000\', \'2T071\', \'2T091\',\ \'3A000\', \'3A071\', \'3A091\', \'3C000\', \'3C071\',\ \'3C090\', \'3C171\', \'3C191\', \'4A000\', \'4A091\',\ \'4A100\', \'4A191\', \'6F000\', \'6F091\', \'8M000\']",\ "onet": "43101100",\ "resource_uri": "/seo/v1/jobposting/29068157/",\ "state": "Virginia", "title": "Branch Office Administrator -\ Chester, VA - Branch 48113", "uid": "29068157"}""") resp = self.client.post("/api/v1/jobsearch/%s" % self.auth_qs, data=jobjson, content_type="application/json") # HTTP 405 == 'Method Not Allowed' self.assertEqual(resp.status_code, 405)
def vw_login_page(request): mesage = None error = None #redirect_to = request.REQUEST.get('next', '') redirect_to = "" if not redirect_to: redirect_to = 'homepage' if request.user.is_authenticated(): print("is_authenticated") print(request.user) return HttpResponseRedirect(reverse('homepage')) else: if request.method == 'POST': print("NOT is_authenticated - POST") form = login_form(request.POST) if form.is_valid(): f = form.cleaned_data try: user = auth.authenticate(username=f['user'], password=f['password']) print("user - POST ") except: user = None pass if user is not None and user.is_active: print("log login") #log try: lo = mdlLog() lo.user = user lo.content_type = ContentType.objects.get(model='user') lo.object_id = user.id lo.action = 'login' lo.save() except Exception as e: logging.error(e) #request.session.set_expiry(timedelta(days=settings.KEEP_LOGGED_DURATION)) try: from tastypie.models import ApiKey #we create an api key api = ApiKey() api.user = user api.save() except Exception as e: logging.error(e) if request.session.test_cookie_worked(): request.session.delete_test_cookie() print("auth login") auth.login(request, user) request.session['welcome_msg'] = _( 'Welcome ') + user.username + '.' return HttpResponseRedirect(reverse('homepage')) else: error = _('User or password not in our systems') return render( request, 'login/login.html', { 'form': form, 'mesage': mesage, 'error': error, 'redirect_to': redirect_to, }) else: error = _('User or password not in our systems') return render( request, 'login/login.html', { 'form': form, 'mesage': mesage, 'error': error, 'redirect_to': redirect_to, }) else: print("NOT is_authenticated - NOT POST") form = login_form() return render( request, 'login/login.html', { 'form': form, 'mesage': mesage, 'error': error, 'redirect_to': redirect_to, })