Esempio n. 1
0
 def handle_noargs(self, **options):
     print "Creating application"
     app = ClientApp(url='fixtureapp.tmp')
     app.save()
     usr = User.objects.create_user(app.url, '*****@*****.**', 'testapp')
     app.user = usr
     app.save()
     print "Creating test users for application"
     client1 = ClientUser(app=app, clientId='testUser1')
     client1.save()
     client2 = ClientUser(app=app, clientId='testUser2')
     client2.save()
     
     json_serializer = serializers.get_serializer('json')()        
     fixture = open(os.path.join(settings.ROOT_PATH, 'profile', 'fixtures', 'testApp.json'), 'w')
     
     print "Creating fixture"
     try:
         json_serializer.serialize([app,usr,client1,client2], stream = fixture)
     except:
         print "couldn't serialize"
         pass
     
     print "Deleting from db"
     app.delete()
     usr.delete()
     client1.delete()
     client2.delete()
     
Esempio n. 2
0
def register_users(request, bulk=False):
    """Register a user or a list of users. If bulk, then it will be asynchronous"""
    from profile.models import ClientApp, ClientUser
    #it MUST exist, otherwise the middleware would have intercepted it
    app = ClientApp.get_for_token(request.POST.get('appId'))
    
    users = request.POST.getlist('user')
#    if not users:
#        return HttpResponseBadRequest("Expected at least one 'user' argument, none given")
    
    if app.users.count() - 1 + len(users) >= settings.FREE_USER_LIMIT:
        return HttpResponseForbidden('Impossible to add more users: user limit would be exceeded')
    
    if bulk:
        #add_bulk_users.delay(users, app, request.build_absolute_uri('/api/getUsers/'))
        bulk_added = _bulk_add(users, app)[0]
        return {'added': bulk_added}
    else:
        #just get the first, then
        user = users[0]
        try:
            u, created = ClientUser.objects.get_or_create(app=app, clientId=user)
            return {'added': created}
        except:
            return HttpResponseServerError('Could not add user')
Esempio n. 3
0
def get_users(request):
    """Given an app, get it's users"""
    if not 'appId' in request.REQUEST:
        return HttpResponseBadRequest()
    else:
        app= ClientApp.get_for_token(request.REQUEST['appId'])
        return HttpResponse(json.dumps([{'k': e.clientId, 'val': e.clientId} for e in app.users.iterator()], 
                                       ensure_ascii=False), mimetype="application/json") 
Esempio n. 4
0
 def clean(self):
     from profile.models import ClientApp
     from django.contrib.auth.models import User
     """Register the app"""
     super(RegisterForm, self).clean()
     #in automated tests, the captcha is ignored:
     if settings.IGNORE_CAPTCHA and 'recaptcha' in self._errors:
         #logging.debug(self._errors)
         del self._errors['recaptcha']
         self.cleaned_data['recaptcha'] = 'test'                    
     if any(self.errors):
         return self.cleaned_data
     if ClientApp.objects.filter(url__iexact=self.cleaned_data['url']).count() > 0:
         self._errors['url']=ErrorList([_('There is an app with that name already registered'),])
         del self.cleaned_data['url']
     else:
         key = ""
         try:
             app = ClientApp(url=self.cleaned_data['url'])
             app.save()                
             key = app.get_token()
             
             raw_pass = User.objects.make_random_password()
             u = User.objects.create_user(app.url, self.cleaned_data['mail'], raw_pass)
             u.save()                                           
             #logging.debug('pass for %s: %s' % (app.url, raw_pass))
             app.user = u
             app.save()
             self.cleaned_data['key'] = key
             self.cleaned_data['pass']= raw_pass
         except:
             pass                       
         
         return self.cleaned_data
Esempio n. 5
0
def delete_user(request):
    """Remove a single user"""
    from profile.models import ClientApp, ClientUser
    
    app = ClientApp.get_for_token(request.POST.get('appId'))
    
    users = request.POST.getlist('user')
        
    #just get the first, then
    user = users[0]
    try:
        u = ClientUser.objects.get(app=app, clientId=user)
        u.delete()
        return {'deleted': True}
    except:
        return {'deleted': False}
Esempio n. 6
0
 def handle(self, url, email, *args, **options):
     try:
         app = ClientApp(url=url)
         app.save()
         
         raw_pass = User.objects.make_random_password()
         u = User.objects.create_user(app.url, email, raw_pass)
         u.save()                                           
         #logging.debug('pass for %s: %s' % (app.url, raw_pass))
         app.user = u
         app.save()
         
         return app.get_token(), app.user.username, raw_pass
     except Exception, e:
         raise CommandError(e.message)
Esempio n. 7
0
 def process_request(self, request):
     assert hasattr(request, 'session'),\
      "The profile middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
     m = re.match(API_URLS, request.path)
     if not m:            
         return None
     from profile import APP_ID, APP_KEY, PROFILE_ID
     from profile.models import ClientApp
     #try to respect REST:, if they provide the appId again, it must be that they like doing queries all the time:        
     if APP_ID in request.REQUEST:
         message = "No app with the given token is registered or the token is invalid"
         try:                
             a = ClientApp.get_for_token(request.REQUEST[APP_ID], id_only=True)
             request.session[APP_KEY] = a
             request.__class__.profile = LazyProfile(request.session[APP_KEY])
             if not hasattr(request, 'profile') and PROFILE_ID in request.REQUEST:
                 message = "The requested user does not exist"
                 raise Exception('Not existent user')
             #limit the number of requests:
             #r=ClientRequest(date=date.today(), app=a, ip=request.META.get('REMOTE_ADDRESS', ''));r.save() 
             #if ClientRequest.objects.filter(date = date.today(), app = a).count() > REQUEST_LIMIT: rval = "403 Exceeded";raise Exc
             #limit the number of users:
             #if ClientApp.objects.get(pk=a).users.count() >= USER_LIMIT: rval="403 usr limit exceeded"; raise Exc 
         except:
             rval = json.dumps({'message': message,
                                'status': 404,
                                'data': {}})
             cb = ''
             if 'callback' in request.REQUEST:
                 cb = request.REQUEST['callback']            
                 if not validate_jsonp.is_valid_jsonp_callback_value(cb):
                     return HttpResponseBadRequest('%s is not a valid jsonp callback identifier' % cb,
                                  mimetype='text/plain')
                 rval = '%s(%s)' % (cb, rval)
             return HttpResponse(rval, mimetype='application/json')
         
     #elif not APP_KEY in request.session:
     #    return HttpResponseBadRequest("An app token must have been provided in a call to startSession or in this request")
                     
     return None
Esempio n. 8
0
def app_users(request):
    """Return a dump of all the users in an app"""
    from profile.models import ClientApp   
    
    return {'users': [{'id': e.clientId, 'added': str(e.added)} 
                                              for e in ClientApp.get_for_token(request.GET.get('appId')).users.iterator()]}