Exemplo n.º 1
0
    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)

        
Exemplo n.º 2
0
Arquivo: user.py Projeto: qbig/wger
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)
Exemplo n.º 3
0
 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'))
                 })
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
 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()
Exemplo n.º 10
0
 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()
Exemplo n.º 11
0
	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 )
Exemplo n.º 12
0
 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'))
                 })
Exemplo n.º 13
0
 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()
Exemplo n.º 14
0
def auth(request):
    key = None
    date = None
    message = None
    try:
        api_key = ApiKey.objects.get(user=request.user)
    except ApiKey.DoesNotExist:
        api_key = None
    
    if request.method == 'POST':
        try:
            action = request.POST['action']
            if action == 'delete' and api_key:
                api_key.delete()
                api_key = None
                message = 'The API key was successfully deleted.'
            elif action == 'generate':
                if not api_key:
                    api_key = ApiKey.objects.create(user=request.user)
                else:
                    api_key.key = ApiKey.generate_key(api_key)
                message = 'The API key was successfully generated.'
        except MultiValueDictKeyError:
            pass

    if api_key:
        key = api_key.key
        date = api_key.created
        
    return render_to_response('server/auth.html',{'logged': True, 'key': key, 'date': date,
                                                     'message': message},
                              context_instance=RequestContext(request))
Exemplo n.º 15
0
    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 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)

        
Exemplo n.º 18
0
 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()
Exemplo n.º 19
0
 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)
Exemplo n.º 20
0
 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()
Exemplo n.º 21
0
def userEdit(request):
    userId = request.GET.get('id')
    user = get_object_or_404(myUser, id=userId)
    data = userForm(instance=user)
    chkApiAuth = ApiKey.objects.filter(user=user)
    if request.method == 'POST':
        post = request.POST
        data = userForm(post, instance=user)
        if post.get('apiAuth') and not chkApiAuth:
            ApiKey(user=user).save()
            sendApiPswMail(user)
        elif not post.get('apiAuth') and chkApiAuth:
            chkApiAuth.delete()
        if data.is_valid():
            data.save()
            return HttpResponseRedirect('/accounts/userList')
    return render_to_response('accounts/userEdit.html',locals(),context_instance=RequestContext(request))
Exemplo n.º 22
0
    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'})
Exemplo n.º 23
0
def userAdd(request):
    listOrAddTag = ['user','accounts', 'userAdd']
    data = userForm()
    if request.method == 'POST':
        post = request.POST
        data = userForm(post)
        username = post.get('username')
        if data.is_valid():
            data.save()
            if post.get('apiAuth'):
                user = myUser.objects.get(username=username,availabity__lte=1)
                ApiKey(user=user).save()
                if not sendApiPswMail(user):
                    emg = u'api密码发送失败。'
            if post.get('EMAIL_PUSH'):
                user = myUser.objects.get(username=username,availabity=1)
                sendInitMail(request.get_host(),user)
            smg = u'用户%s添加成功!' % username
    return render_to_response('accounts/userAdd.html',locals(),context_instance=RequestContext(request))
Exemplo n.º 24
0
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)
Exemplo n.º 25
0
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)
Exemplo n.º 26
0
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)
Exemplo n.º 27
0
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,
                })
Exemplo n.º 28
0
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)
Exemplo n.º 29
0
 def register(self, request=None, **kwargs):
     '''
     will try and register the user
     we expect here an email and a password sent as post params
     @return:    201 if user is created
                 500 failed to send emails
                 409 conflict with existing account
     '''
     
     #get params
     post = simplejson.loads(request.body)
     password = post.get('password')
     email = post.get('email')
     
     #create the username
     api_key = ApiKey()
     username = api_key.generate_key()[0:30]
     
     #set the request post to contain email password and username
     post_values = {}
     post_values['username'] = username
     post_values['password1'] = password
     post_values['password2'] = password
     post_values['email'] = email
     
     #is the email already exists?
     try:
         user = User.objects.get(email=email)
         return self.create_response(request, {
                 'success': False,
                 'message': 'User with this mail address already exists',
                 }, HttpConflict )
     except:
         pass
     
     #validation success
     user_form = UserCreateForm(post_values)
     if user_form.is_valid():
         
         #create the user
         username = user_form.clean_username()
         password = user_form.clean_password2()
         user_form.save()
         user = authenticate(username=username,
                             password=password)
         login(request, user)
         
         #creathe the email hash
         email_hash = api_key.generate_key()
         user_profile = user.profile
         user_profile.email_hash = email_hash
         user_profile.save()
         
         #send the verification mail
         if is_send_grid():
             user.is_active = False
             user.save()
             t = get_template('emails/verify_email_mail.html')
             html = t.render(Context({'hash': user_profile.email_hash, 'url': os.environ['CLIENT_SITE_URL'] + '#/verify-email/', 'email': email}))
             text_content = strip_tags(html)
             msg = EmailMultiAlternatives('Nerdeez account activation', text_content, settings.FROM_EMAIL_ADDRESS, [email])
             msg.attach_alternative(html, "text/html")
             try:
                 msg.send()
             except SMTPSenderRefused, e:
                 return self.create_response(request, {
                     'success': False,
                     'message': 'Failed to send activation mail',
                     }, HttpApplicationError )
         
         #return the status code
         return self.create_response(request, {
                 'success': True,
                 'message': 'Successfully created the account, Verification mail was sent to your mail address',
                 }, HttpCreated )