Exemple #1
0
def prepare(sender, **kwargs):
    public_key = intensity_conf.get('ReCaptcha', 'public_key')
    if public_key == '': return ''

    errors = kwargs.get('errors', [])
    errors = filter(lambda pair: pair[0] == IDENTIFIER, errors)
    error = errors[0][1] if len(errors) == 1 else ''

    return '''
<p>Please prove you are human:
<script>
var RecaptchaOptions = {
   theme : 'white',
   tabindex : 2
};
</script>
<script type="text/javascript"
   src="http://api.recaptcha.net/challenge?k=%(key)s&error=%(error)s">
</script>

<noscript>
   <iframe src="http://api.recaptcha.net/noscript?k=%(key)s&error=%(error)s">
       height="300" width="500" frameborder="0"></iframe><br>
   <textarea name="recaptcha_challenge_field" rows="3" cols="40">
   </textarea>
   <input type="hidden" name="recaptcha_response_field" 
       value="manual_challenge">
</noscript>
</p>
''' % {
        'key': public_key,
        'error': error
    }
Exemple #2
0
    def process_response(self, request, response):
        if intensity_conf.get('Django', 'logging', '0') == '1':
            if hasattr(request, 'user'):
                user_info = request.user.username if request.user.is_authenticated(
                ) else '<<anonymous>>'
            else:
                user_info = '<<anonymous>>'

            user_info += ' ' + request.META['REMOTE_ADDR']

            logging.info('%s - %s - %s' %
                         (user_info, request.method, request.path))

            if len(connection.queries) > 0:
                time = sum([float(q['time']) for q in connection.queries])
                t = Template('''
    {{count}} quer{{count|pluralize:\"y,ies\"}} in {{time}} seconds:
        {% for sql in sqllog %}[{{forloop.counter}}] {{sql.time}}s: {{sql.sql|safe}}{% if not forloop.last %}\n        \n{% endif %}{% endfor %}
''')
                logging.info(
                    t.render(
                        Context({
                            'sqllog': connection.queries,
                            'count': len(connection.queries),
                            'time': time
                        })))
            else:
                logging.info('    (no queries)')

        return response
def getselected(request):
    instance = None
    try:
        instance = SelectedInstance.objects.get(account = request.account).instance
    except SelectedInstance.DoesNotExist:
#        return HttpResponse(urllib.urlencode([
#            ('error', "You haven't selected a server."),
#        ]))

        # Find a 'good' random server to connect to, even though one isn't selected -  temporary
        # workaround until we have a nice UI for this stuff

        possibles = intensity_conf.get('InstanceSelector', 'possibles', '')
        if possibles == '':
            instances = ServerInstance.objects.filter(activity__isnull=False) # All instances running activities
        else:
            possibles = possibles.split(',')
            instances = []
            for possible in possibles:
                try:
                    instance = ServerInstance.objects.get(user_interface=possible)
                except ServerInstance.DoesNotExist:
                    continue
                if instance.activity is not None:
                    instances.append(instance)

        instances = filter(lambda instance: instance.players < instance.max_players, instances) # Non-full
        instances = filter(lambda instance: 'localhost' not in instance.user_interface, instances) # No localhosts

        if len(instances) == 0:
            return HttpResponse(urllib.urlencode([
                ('error', "All servers (in main pool) are full."),
            ]))

        weights = map(lambda instance: 1.0/(instance.max_players - instance.players), instances) # More weight to nearly-full
        total = sum(weights)
        weights = map(lambda weight: weight/total, weights)
        x = random.random()
        for i in range(len(instances)):
            if weights[i] >= x:
                instance = instances[i]
                break
            x -= weights[i]

        if instance == None:
            logging.warning('An error occurred in randomly generating an instance')
            instance = random.choice(instances)

    return HttpResponse(urllib.urlencode([
        ('interface', instance.user_interface),
    ]))
Exemple #4
0
def account_instancelogin(request):
    instance_id = request.GET['instance_id']
    code = request.GET['code']

    instance = ServerInstance.objects.get(uuid=instance_id)

    error = False
    try:
        account_id, session_id = code.split(',')
        try:
            account = UserAccount.objects.get(uuid=account_id)
            # TODO: Validate session_id
        except:
            error = True
    except:
        error = True

    if error:
        return HttpResponse(
            urllib.urlencode([('error', 'Invalid validation code')]))

    # Immediately note the new # of players. This may be buggy sometimes, but good enough.
    instance.players += 1
    pre_instance_update.send(
        None,
        instance=instance)  # As if the instance is updated, with new stats
    post_instance_update.send(
        None,
        instance=instance)  # As if the instance is updated, with new stats
    instance.save()

    # TODO: As components
    activity = instance.activity
    if activity is not None:
        is_owner = account.uuid in [
            owner.uuid for owner in activity.asset.owners.all()
        ]
    else:
        is_owner = False

    can_edit = bool(int(intensity_conf.get('Instances',
                                           'let_anyone_edit'))) or is_owner

    return HttpResponse(
        urllib.urlencode([
            ('success', '1'),
            ('user_id', account.uuid),
            ('username', account.nickname),
            ('can_edit', str(int(can_edit))),
        ]))
Exemple #5
0
def register(request, template_name='registration/register.html'):
    if intensity_conf.get('Accounts', 'allow_registrations', '') != '1':
        return HttpResponseRedirect('/accounts/register/signup_for_notify/')

    def on_valid(form):
        logging.info('Creating user: '******'username'])

        User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email'],
        )

    return getpost_form(request, 'registration/register.html', UserAccountCreationForm, on_valid, '/accounts/register/finish/', form_params={'request': request})
Exemple #6
0
def getlobby(request):
    possibles = intensity_conf.get('Lobby', 'possibles', '')
    if possibles == '':
        instances = []
    else:
        possibles = possibles.split(',')
        instances = []
        for possible in possibles:
            try:
                instance = ServerInstance.objects.get(user_interface=possible)
            except ServerInstance.DoesNotExist:
                continue
            if instance.activity is not None:
                instances.append(instance)

    instances = filter(
        lambda instance: instance.players < instance.max_players,
        instances)  # Non-full
    instances = filter(
        lambda instance: 'localhost' not in instance.user_interface,
        instances)  # No localhosts

    if len(instances) == 0:
        return HttpResponse(
            urllib.urlencode([
                ('error', "No lobby servers available."),
            ]))

    weights = map(lambda instance: 1.0 /
                  (instance.max_players - instance.players),
                  instances)  # More weight to nearly-full
    total = sum(weights)
    weights = map(lambda weight: weight / total, weights)
    x = random.random()
    for i in range(len(instances)):
        if weights[i] >= x:
            instance = instances[i]
            break
        x -= weights[i]

    if instance == None:
        logging.warning('An error occurred in randomizing a lobby.')
        instance = random.choice(instances)

    return HttpResponse(
        urllib.urlencode([
            ('interface', instance.user_interface),
        ]))
Exemple #7
0
    def testPasswordReset(self):
        self.assertContains(self.client.get('/accounts/resetpassword/'), 'Enter your email')
        self.assertContains(self.client.post('/accounts/resetpassword/'), 'is required')

        class Content:
            emails = []

        def adder(sender, **kwargs):
            Content.emails.append(kwargs['body'])

        with EmailSender(adder):
            account = User.objects.create_user(username='******', password='******', email='*****@*****.**')

            self.assertEquals(len(Content.emails), 0)

            # Require captcha, if we are using one
            if intensity_conf.get('ReCaptcha', 'public_key') != '':
                self.assertContains(self.client.post('/accounts/resetpassword/', {'email': '*****@*****.**'}), 'Security checks not passed.')

            with IntensityConfSetting('ReCaptcha', 'public_key', ''): # Disable captcha
                with IntensityConfSetting('ReCaptcha', 'private_key', ''): # Disable captcha
                    url = get_redirect_url(self.client.post('/accounts/resetpassword/', {'email': '*****@*****.**'}))
                    self.assertContains(
                        self.client.get(url),
                        'If an account exists with that email, a new password has been sent to it'
                    )
                    self.assertEquals(len(Content.emails), 0) # No such account

                    with IntensityConfSetting('Email', 'username', ''): # Disable email
                        url = get_redirect_url(self.client.post('/accounts/resetpassword/', {'email': '*****@*****.**'}))
                        self.assertContains(
                            self.client.get(url),
                            'If an account exists with that email, a new password has been sent to it'
                        )
                        self.assertEquals(len(Content.emails), 1)

            # Succeed to login with new password

            lines = Content.emails[0].split('\n')
            password = None
            for line in lines:
                ind = 'Your password is now set to: '
                if ind in line:
                    password = line[line.find(ind)+len(ind):]
            self.assertNotEquals(password, None)

            self.assertTrue(self.client.login(username='******', password=password))
def upload(request, uuid):
    asset = AssetInfo.objects.get(uuid=uuid)
    if intensity_conf.get('Instances', 'let_anyone_edit') != '1':
        owner_uuids = [owner.uuid for owner in asset.owners.all()]
        assert request.account.uuid in owner_uuids, 'You must be an owner of this asset to upload content'

    if request.method == 'GET':
        return direct_to_template(request, template="do_upload.html", extra_context = {'asset': asset})
    else:
        # Receive the uploaded file, and hand off reception to the appropriate service provider
        asset_file = request.FILES['file']
        ret = multiple_send(store_asset, None, asset=asset, asset_file=asset_file)
        if reduce(lambda x, y: x and y, ret) is True:
            request.session['message'] = 'Upload was successful.'
            return HttpResponseRedirect('/tracker/asset/view/%s/' % asset.uuid)
        else:
            raise Exception(str(ret))
Exemple #9
0
def register(request, template_name='registration/register.html'):
    if intensity_conf.get('Accounts', 'allow_registrations', '') != '1':
        return HttpResponseRedirect('/accounts/register/signup_for_notify/')

    def on_valid(form):
        logging.info('Creating user: '******'username'])

        User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email'],
        )

    return getpost_form(request,
                        'registration/register.html',
                        UserAccountCreationForm,
                        on_valid,
                        '/accounts/register/finish/',
                        form_params={'request': request})
Exemple #10
0
def account_instancelogin(request):
    instance_id = request.GET['instance_id']
    code = request.GET['code']

    instance = ServerInstance.objects.get(uuid=instance_id)

    error = False
    try:
        account_id, session_id = code.split(',')
        try:
            account = UserAccount.objects.get(uuid=account_id)
            # TODO: Validate session_id
        except:
            error = True
    except:
        error = True

    if error:
        return HttpResponse(urllib.urlencode([('error', 'Invalid validation code')]))

    # Immediately note the new # of players. This may be buggy sometimes, but good enough.
    instance.players += 1
    pre_instance_update.send(None, instance=instance) # As if the instance is updated, with new stats
    post_instance_update.send(None, instance=instance) # As if the instance is updated, with new stats
    instance.save()

    # TODO: As components
    activity = instance.activity
    if activity is not None:
        is_owner = account.uuid in [owner.uuid for owner in activity.asset.owners.all()]
    else:
        is_owner = False

    can_edit = bool(int(intensity_conf.get('Instances', 'let_anyone_edit'))) or is_owner

    return HttpResponse(urllib.urlencode([
        ('success', '1'),
        ('user_id', account.uuid),
        ('username', account.nickname),
        ('can_edit', str(int(can_edit))),
    ]))
def getlobby(request):
    possibles = intensity_conf.get('Lobby', 'possibles', '')
    if possibles == '':
        instances = []
    else:
        possibles = possibles.split(',')
        instances = []
        for possible in possibles:
            try:
                instance = ServerInstance.objects.get(user_interface=possible)
            except ServerInstance.DoesNotExist:
                continue
            if instance.activity is not None:
                instances.append(instance)

    instances = filter(lambda instance: instance.players < instance.max_players, instances) # Non-full
    instances = filter(lambda instance: 'localhost' not in instance.user_interface, instances) # No localhosts

    if len(instances) == 0:
        return HttpResponse(urllib.urlencode([
            ('error', "No lobby servers available."),
        ]))

    weights = map(lambda instance: 1.0/(instance.max_players - instance.players), instances) # More weight to nearly-full
    total = sum(weights)
    weights = map(lambda weight: weight/total, weights)
    x = random.random()
    for i in range(len(instances)):
        if weights[i] >= x:
            instance = instances[i]
            break
        x -= weights[i]

    if instance == None:
        logging.warning('An error occurred in randomizing a lobby.')
        instance = random.choice(instances)

    return HttpResponse(urllib.urlencode([
        ('interface', instance.user_interface),
    ]))
Exemple #12
0
def upload(request, uuid):
    asset = AssetInfo.objects.get(uuid=uuid)
    if intensity_conf.get('Instances', 'let_anyone_edit') != '1':
        owner_uuids = [owner.uuid for owner in asset.owners.all()]
        assert request.account.uuid in owner_uuids, 'You must be an owner of this asset to upload content'

    if request.method == 'GET':
        return direct_to_template(request,
                                  template="do_upload.html",
                                  extra_context={'asset': asset})
    else:
        # Receive the uploaded file, and hand off reception to the appropriate service provider
        asset_file = request.FILES['file']
        ret = multiple_send(store_asset,
                            None,
                            asset=asset,
                            asset_file=asset_file)
        if reduce(lambda x, y: x and y, ret) is True:
            request.session['message'] = 'Upload was successful.'
            return HttpResponseRedirect('/tracker/asset/view/%s/' % asset.uuid)
        else:
            raise Exception(str(ret))
    def process_response(self, request, response):
        if intensity_conf.get('Django', 'logging', '0') == '1':
            if hasattr(request, 'user'):
                user_info = request.user.username if request.user.is_authenticated() else '<<anonymous>>'
            else:
                user_info = '<<anonymous>>'

            user_info += ' ' + request.META['REMOTE_ADDR']

            logging.info('%s - %s - %s' % (user_info, request.method, request.path))

            if len(connection.queries) > 0:
                time = sum([float(q['time']) for q in connection.queries])
                t = Template('''
    {{count}} quer{{count|pluralize:\"y,ies\"}} in {{time}} seconds:
        {% for sql in sqllog %}[{{forloop.counter}}] {{sql.time}}s: {{sql.sql|safe}}{% if not forloop.last %}\n        \n{% endif %}{% endfor %}
''')
                logging.info(t.render(Context({'sqllog':connection.queries,'count':len(connection.queries),'time':time})))
            else:
                logging.info('    (no queries)')

        return response
Exemple #14
0
def verify(sender, **kwargs):
    private_key = intensity_conf.get('ReCaptcha', 'private_key')
    if private_key == '': return True

    request = kwargs['request']
    params = request.POST
    challenge = params.get('recaptcha_challenge_field')
    response = params.get('recaptcha_response_field')

    if challenge is None or response is None:
        return (IDENTIFIER, '')

    ip = request.META['REMOTE_ADDR']

    params_vec = [
        ('privatekey', private_key),
        ('remoteip', ip),
        ('challenge', challenge),
        ('response', response),
    ]

    conn = httplib.HTTPConnection('api-verify.recaptcha.net')
    headers = {
        'Content-type': 'application/x-www-form-urlencoded',
        'Accept': 'text/plain'
    }
    conn.request('POST', '/verify', urllib.urlencode(params_vec), headers)
    response = conn.getresponse()
    assert (response.status == 200)
    data = response.read()
    conn.close()

    lines = data.split('\n')
    if lines[0] == 'true':
        return True
    else:
        return (IDENTIFIER, lines[1])
Exemple #15
0
def instance_update(request):
    data = request.GET.copy()

    if not check_version(data.get('version', '')):
        return HttpResponse(
            urllib.urlencode([('error', 'Engine version mismatch.')]))

    # If instance didn't send us interfaces, use 'unknown' values
    # (useful for running a master with a single server that doesn't
    # know it's IP)
    if data.get('user_interface') is None:
        data['user_interface'] = '127.0.0.1'
    if data.get('admin_interface') is None:
        data['admin_interface'] = '127.0.0.1'

    try:
        instance = ServerInstance.objects.get(
            user_interface=data.get('user_interface'))
        form = ServerInstanceUpdateForm(data, instance=instance)
    except ServerInstance.DoesNotExist:
        form = ServerInstanceUpdateForm(data)

    instance = form.instance

    assert (form.is_valid())

    instance.last_update = datetime.now()
    form.save()  # Generate UUIDs, etc.

    pre_instance_update.send(None, instance=instance)

    true_activity = instance.activity

    response = []

    response.append(('instance_id', instance.uuid))

    # If the instance is not running the right map, tell it so

    if true_activity is not None:
        true_activity_id = true_activity.uuid
        true_map_id = true_activity.asset.uuid
    else:
        true_activity_id = ''
        true_map_id = ''

    # Decide if to notify of new map, and update the status

    curr_activity_id = data.get('activity_id', '')
    if curr_activity_id != '':
        try:
            curr_activity = Activity.objects.get(uuid=curr_activity_id)
        except:
            print "Warning: Invalid activity reported by instance"
            curr_activity = None
    else:
        curr_activity = None

    curr_asset_id = data.get('map_asset_id', '')
    if curr_asset_id != '':
        curr_asset = AssetInfo.objects.get(uuid=curr_asset_id)
    else:
        curr_asset = None

    force_asset_location = intensity_conf.get('Instances',
                                              'force_asset_location')
    if force_asset_location != '':
        # We tell all instances to run a particular map asset, if not already running it
        force_asset = AssetInfo.objects.get(location=force_asset_location)
        if not (curr_asset is not None
                and curr_asset.uuid == force_asset.uuid):
            response.append(('activity_id', 'forced_location'))
            response.append(('map_asset_id', force_asset.uuid))

        instance.status = ServerInstance.STATUS.Active
    else:
        # Normal processing
        if curr_activity != true_activity:
            response.append(('activity_id', true_activity_id))
            response.append(('map_asset_id', true_map_id))

            if true_activity_id != '':
                instance.status = ServerInstance.STATUS.Preparing
            else:
                instance.status = ServerInstance.STATUS.Inactive
        else:
            if true_activity_id != '':
                instance.status = ServerInstance.STATUS.Active
            else:
                instance.status = ServerInstance.STATUS.Inactive

    # Mode

    validations = validate_instance.send(None,
                                         instance=instance,
                                         validation=data.get('validation'))
    # If at least one positive validation, then validated
    if len(validations) > 0 and reduce(
            lambda x, y: x or y, map(lambda result: result[1], validations)):
        instance.mode = ServerInstance.MODE.Pooled
        instance.session_id = make_uuid()
    else:
        instance.mode = ServerInstance.MODE.Independent
        instance.activity = curr_activity

    response.append(
        ('session_id', instance.session_id))  # Maybe the old one, or a new one

    # Post-update trigger

    post_instance_update.send(None, instance=instance)

    # Write

    form.save()

    return HttpResponse(urllib.urlencode(response))
Exemple #16
0
def instance_update(request):
    data = request.GET.copy()

    if not check_version(data.get('version', '')):
        return HttpResponse(urllib.urlencode([('error', 'Engine version mismatch.')]))

    # If instance didn't send us interfaces, use 'unknown' values
    # (useful for running a master with a single server that doesn't
    # know it's IP)
    if data.get('user_interface') is None:
        data['user_interface'] = '127.0.0.1'
    if data.get('admin_interface') is None:
        data['admin_interface'] = '127.0.0.1'

    try:
        instance = ServerInstance.objects.get(user_interface=data.get('user_interface'))
        form = ServerInstanceUpdateForm(data, instance=instance)
    except ServerInstance.DoesNotExist:
        form = ServerInstanceUpdateForm(data)

    instance = form.instance

    assert(form.is_valid())

    instance.last_update = datetime.now()
    form.save() # Generate UUIDs, etc.

    pre_instance_update.send(None, instance=instance)

    true_activity = instance.activity

    response = []

    response.append( ('instance_id', instance.uuid) )

    # If the instance is not running the right map, tell it so

    if true_activity is not None:
        true_activity_id = true_activity.uuid
        true_map_id = true_activity.asset.uuid
    else:
        true_activity_id = ''
        true_map_id = ''

    # Decide if to notify of new map, and update the status

    curr_activity_id = data.get('activity_id', '')
    if curr_activity_id != '':
        try:
            curr_activity = Activity.objects.get(uuid=curr_activity_id)
        except:
            print "Warning: Invalid activity reported by instance"
            curr_activity = None
    else:
        curr_activity = None

    curr_asset_id = data.get('map_asset_id', '')
    if curr_asset_id != '':
        curr_asset = AssetInfo.objects.get(uuid=curr_asset_id)
    else:
        curr_asset = None

    force_asset_location = intensity_conf.get('Instances', 'force_asset_location')
    if force_asset_location != '':
        # We tell all instances to run a particular map asset, if not already running it
        force_asset = AssetInfo.objects.get(location=force_asset_location)
        if not (curr_asset is not None and curr_asset.uuid == force_asset.uuid):
            response.append( ('activity_id', 'forced_location') )
            response.append( ('map_asset_id', force_asset.uuid) )

        instance.status = ServerInstance.STATUS.Active
    else:
        # Normal processing
        if curr_activity != true_activity:
            response.append( ('activity_id', true_activity_id) )
            response.append( ('map_asset_id', true_map_id) )

            if true_activity_id != '':
                instance.status = ServerInstance.STATUS.Preparing
            else:
                instance.status = ServerInstance.STATUS.Inactive
        else:
            if true_activity_id != '':
                instance.status = ServerInstance.STATUS.Active
            else:
                instance.status = ServerInstance.STATUS.Inactive

    # Mode

    validations = validate_instance.send(None, instance=instance, validation=data.get('validation'))
    # If at least one positive validation, then validated
    if len(validations) > 0 and reduce(
        lambda x,y: x or y,
        map(lambda result: result[1], validations)
    ):
        instance.mode = ServerInstance.MODE.Pooled
        instance.session_id = make_uuid()
    else:
        instance.mode = ServerInstance.MODE.Independent
        instance.activity = curr_activity

    response.append( ('session_id', instance.session_id) ) # Maybe the old one, or a new one

    # Post-update trigger

    post_instance_update.send(None, instance=instance)
    
    # Write

    form.save()

    return HttpResponse(urllib.urlencode(response))
Exemple #17
0
 def listable(self):
     if self.user_interface.split(':')[0] == 'localhost' and \
         intensity_conf.get('Network', 'address') != 'localhost':
         return False
     return True
Exemple #18
0
def getselected(request):
    instance = None
    try:
        instance = SelectedInstance.objects.get(
            account=request.account).instance
    except SelectedInstance.DoesNotExist:
        #        return HttpResponse(urllib.urlencode([
        #            ('error', "You haven't selected a server."),
        #        ]))

        # Find a 'good' random server to connect to, even though one isn't selected -  temporary
        # workaround until we have a nice UI for this stuff

        possibles = intensity_conf.get('InstanceSelector', 'possibles', '')
        if possibles == '':
            instances = ServerInstance.objects.filter(
                activity__isnull=False)  # All instances running activities
        else:
            possibles = possibles.split(',')
            instances = []
            for possible in possibles:
                try:
                    instance = ServerInstance.objects.get(
                        user_interface=possible)
                except ServerInstance.DoesNotExist:
                    continue
                if instance.activity is not None:
                    instances.append(instance)

        instances = filter(
            lambda instance: instance.players < instance.max_players,
            instances)  # Non-full
        instances = filter(
            lambda instance: 'localhost' not in instance.user_interface,
            instances)  # No localhosts

        if len(instances) == 0:
            return HttpResponse(
                urllib.urlencode([
                    ('error', "All servers (in main pool) are full."),
                ]))

        weights = map(lambda instance: 1.0 /
                      (instance.max_players - instance.players),
                      instances)  # More weight to nearly-full
        total = sum(weights)
        weights = map(lambda weight: weight / total, weights)
        x = random.random()
        for i in range(len(instances)):
            if weights[i] >= x:
                instance = instances[i]
                break
            x -= weights[i]

        if instance == None:
            logging.warning(
                'An error occurred in randomly generating an instance')
            instance = random.choice(instances)

    return HttpResponse(
        urllib.urlencode([
            ('interface', instance.user_interface),
        ]))
def base():
    scheme = 'http://' if intensity_conf.get('Network',
                                             'auth') == '0' else 'https://'
    return scheme + intensity_conf.get(
        'Network', 'address') + ':' + intensity_conf.get('Network', 'port')
import os, sys

import cherrypy

import intensity.conf as intensity_conf

if len(sys.argv) >= 2:
    intensity_conf.set_home_dir(sys.argv[1])
else:
    intensity_conf.set_home_dir()  # Use environment

# Auth servers serve using HTTPS, with a certificate in a subdirectory
# called ssl/, and use a different settings.py file
# (settings_production_auth.py).
auth = bool(int(intensity_conf.get('Network', 'auth')))

# Start and stop the CherryPy engine
#######cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__ < '3.1':
    print "Starting engine..."
    cherrypy.engine.start(blocking=False)


# Dummy root for static dir
class StaticRoot:
    pass


if __name__ == '__main__':
    # General setup
Exemple #21
0
 def __enter__(self):
     self.saved = intensity_conf.get(*(self.args[0:2]))
     intensity_conf.set(*(self.args))
Exemple #22
0
 def __enter__(self):
     self.saved = intensity_conf.get(*(self.args[0:2]))
     intensity_conf.set(*(self.args))
Exemple #23
0
    def testPasswordReset(self):
        self.assertContains(self.client.get('/accounts/resetpassword/'),
                            'Enter your email')
        self.assertContains(self.client.post('/accounts/resetpassword/'),
                            'is required')

        class Content:
            emails = []

        def adder(sender, **kwargs):
            Content.emails.append(kwargs['body'])

        with EmailSender(adder):
            account = User.objects.create_user(
                username='******',
                password='******',
                email='*****@*****.**')

            self.assertEquals(len(Content.emails), 0)

            # Require captcha, if we are using one
            if intensity_conf.get('ReCaptcha', 'public_key') != '':
                self.assertContains(
                    self.client.post('/accounts/resetpassword/',
                                     {'email': '*****@*****.**'}),
                    'Security checks not passed.')

            with IntensityConfSetting('ReCaptcha', 'public_key',
                                      ''):  # Disable captcha
                with IntensityConfSetting('ReCaptcha', 'private_key',
                                          ''):  # Disable captcha
                    url = get_redirect_url(
                        self.client.post('/accounts/resetpassword/',
                                         {'email': '*****@*****.**'}))
                    self.assertContains(
                        self.client.get(url),
                        'If an account exists with that email, a new password has been sent to it'
                    )
                    self.assertEquals(len(Content.emails),
                                      0)  # No such account

                    with IntensityConfSetting('Email', 'username',
                                              ''):  # Disable email
                        url = get_redirect_url(
                            self.client.post(
                                '/accounts/resetpassword/',
                                {'email': '*****@*****.**'}))
                        self.assertContains(
                            self.client.get(url),
                            'If an account exists with that email, a new password has been sent to it'
                        )
                        self.assertEquals(len(Content.emails), 1)

            # Succeed to login with new password

            lines = Content.emails[0].split('\n')
            password = None
            for line in lines:
                ind = 'Your password is now set to: '
                if ind in line:
                    password = line[line.find(ind) + len(ind):]
            self.assertNotEquals(password, None)

            self.assertTrue(
                self.client.login(username='******', password=password))
def toplevel(request):
    '''
    Gives a redirect URL for the toplevel
    '''
    return { 'toplevel_root': intensity_conf.get('Sites', 'toplevel_root') }
Exemple #25
0
#!/usr/bin/python

import os, sys

import intensity.conf as intensity_conf

intensity_conf.set_home_dir()

#import sys
#sys.path.insert(0, '.') # Use local Django for testing

from django.core.management import execute_manager
try:
    settings = __import__(intensity_conf.get(
        'Django', 'settings'))  # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write(
        "Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n"
        % __file__)
    sys.exit(1)

if __name__ == "__main__":
    execute_manager(settings)
Exemple #26
0
#!/usr/bin/python

import os, sys

import intensity.conf as intensity_conf
intensity_conf.set_home_dir()

#import sys
#sys.path.insert(0, '.') # Use local Django for testing

from django.core.management import execute_manager
try:
    settings = __import__(intensity_conf.get('Django', 'settings')) # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
    execute_manager(settings)
import os, sys

import cherrypy

import intensity.conf as intensity_conf

if len(sys.argv) >= 2:
    intensity_conf.set_home_dir(sys.argv[1])
else:
    intensity_conf.set_home_dir() # Use environment


# Auth servers serve using HTTPS, with a certificate in a subdirectory
# called ssl/, and use a different settings.py file
# (settings_production_auth.py).
auth = bool(int(intensity_conf.get('Network', 'auth')))

# Start and stop the CherryPy engine
#######cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__ < '3.1':
    print "Starting engine..."
    cherrypy.engine.start(blocking=False)

# Dummy root for static dir
class StaticRoot:
    pass

if __name__ == '__main__':
    # General setup

    current_dir = os.path.dirname(os.path.abspath(__file__))
Exemple #28
0
 def listable(self):
     if self.user_interface.split(':')[0] == 'localhost' and \
         intensity_conf.get('Network', 'address') != 'localhost':
         return False
     return True
def base():
    scheme = 'http://' if intensity_conf.get('Network', 'auth') == '0' else 'https://'
    return scheme + intensity_conf.get('Network', 'address') + ':' + intensity_conf.get('Network', 'port')