コード例 #1
0
def login(env):
    """
        Login method. Handles both GET and POST requests.
    """
    tmpl = jinjaenv.get_template('loginform.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Error: Invalid post data')

        if 'user' not in data or 'pass' not in data:
            return template_render(tmpl, {
                'session': env['beaker.session'],
                'loginfail': True
            })

        data['user'] = urllib.unquote_plus(data['user'])
        data['pass'] = urllib.unquote_plus(data['pass'])

        data['pass'] = hashlib.sha256(data['pass']).hexdigest()

        # Does the user exist (and is the password valid)?
        res = Session.query(User).filter(
            func.lower(User.name) == data['user'].lower()).filter(
                User.password == data['pass']).first()

        if res:
            env['beaker.session']['loggedin'] = True
            env['beaker.session']['loggedin_id'] = res.id
            env['beaker.session']['loggedin_name'] = res.name

            # XXX: Do not rely on this. Only use for showing permissions where
            # extra checks aren't nessecary. EG: Fine for links, not fine for
            # actual db changes + access to pages.
            env['beaker.session']['loggedin_level'] = res.admin_level
            env['beaker.session'].save()
            log.log([], LVL_NOTABLE, PyLogger.INFO,
                    'Login %s : %s' % (env['REMOTE_ADDR'], data['user']))
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'loginsuccess': True,
                    'user': res
                })
        else:
            log.log([], LVL_NOTABLE, PyLogger.INFO, 'Failed login %s : %s' %
                    (env['REMOTE_ADDR'], data['user']))
            return template_render(tmpl, {
                'session': env['beaker.session'],
                'loginfail': True
            })

    elif str(env['REQUEST_METHOD']) == 'GET':

        return template_render(tmpl, {'session': env['beaker.session']})
    else:
        return None
コード例 #2
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def login(env):
    """
        Login method. Handles both GET and POST requests.
    """
    tmpl = jinjaenv.get_template('loginform.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Error: Invalid post data')

        if 'user' not in data or 'pass' not in data:
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'loginfail' : True}  )

        data['user'] = urllib.unquote_plus(data['user'])
        data['pass'] = urllib.unquote_plus(data['pass'])

        data['pass'] = hashlib.sha256(data['pass']).hexdigest()

        # Does the user exist (and is the password valid)?
        res =  Session.query(User).filter(func.lower(User.name) ==
                data['user'].lower()).filter(User.password == data['pass']).first()

        if res:
            env['beaker.session']['loggedin'] = True
            env['beaker.session']['loggedin_id'] = res.id
            env['beaker.session']['loggedin_name'] = res.name

            # XXX: Do not rely on this. Only use for showing permissions where
            # extra checks aren't nessecary. EG: Fine for links, not fine for 
            # actual db changes + access to pages.
            env['beaker.session']['loggedin_level'] = res.admin_level
            env['beaker.session'].save()
            log.log([], LVL_NOTABLE, PyLogger.INFO,
                    'Login %s : %s' % (env['REMOTE_ADDR'], data['user']))
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'loginsuccess' : True,
                'user' : res} )
        else:
            log.log([], LVL_NOTABLE, PyLogger.INFO,
                    'Failed login %s : %s' % (env['REMOTE_ADDR'], data['user']))
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'loginfail' : True}  )

    elif str(env['REQUEST_METHOD']) == 'GET':

        return template_render(tmpl,
            {   'session' : env['beaker.session']}  )
    else:
        return None
コード例 #3
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def manage_variable(env, variableid):
    """
        Page to manage a variable. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl,
            {   'session' : env['beaker.session']} )

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    if user.admin_level < 1:
        return str('Access denied')

    tmpl = jinjaenv.get_template('managevariable.html')

    variable = session.query(Variable).filter(Variable.id == \
            variableid).first()

    if not variable:
        return None

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Invalid POST data')

        if 'newname' not in data:
            return str('Invalid POST data')

        data['newname'] = urllib.unquote_plus(data['newname'])
        if len(data['newname']) == 0 or len(data['newname']) > 20:
            return template_render(tmpl,
                {   'session' : env ['beaker.session'],
                    'error' : 'Variable name too long.',
                })

        res = session.query(Variable).filter(Variable.name ==
                data['newname']).first()

        if res is None:
            variable.name = data['newname']
            session.add(variable)
            try:
                session.commit()
            except sqlalchemy.exc.IntegrityError as e:
                session.rollback()
                print 'Rollback in manage_variable'
                print 'Post data:', data
                print 'Exception:', e
        else:
            return template_render(tmpl,
                {   'session' : env ['beaker.session'],
                    'error' : 'Name already exists in the system.',
                    'variable' : variable
                })

    return template_render(tmpl,
        {   'session' : env['beaker.session'],
            'variable' : variable
        })
コード例 #4
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def create_variable(env):
    """
        Page to create a variable. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl,
            {   'session' : env['beaker.session']} )

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    if user.admin_level < 1:
        return str('Access denied')

    tmpl = jinjaenv.get_template('createvariable.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)
        if data is None:
            return str('Error: Invalid POST data')

        if 'variable' in data:
            s = data['variable']
            s = urllib.unquote_plus(s)
        else:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Variable name not specified'})

        if len(s) == 0 or len(s) > 60:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Variable name has invalid length'})

        # 'on' when checked; not in data when not clicked. XXX
        if 'is_var' in data:
            v = 1
        else:
            v = 0

        res = session.query(Variable).filter(Variable.name ==
            s).first()

        if res:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Variable already exists'})

        variable = Variable(s, v)
        session.add(variable)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback! create_variable'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(tmpl, { 'session' : env ['beaker.session'],
              'newvariable' : variable})


    return template_render(tmpl,
        {'session' : env['beaker.session'] })
コード例 #5
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def create_script(env):
    """
        Page to create a script. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl,
            {   'session' : env['beaker.session']}  )

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    tmpl = jinjaenv.get_template('createscript.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)
        if data is None:
            return str('Error: Invalid POST data')

        if 'script' in data:
            s = data['script']
            s = urllib.unquote_plus(s)
        else:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Script contains invalid characters'})

        if len(s) == 0 or len(s) > 20:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Script name has invalid length'})

        res = session.query(Script).filter(Script.name == s).all()
        if res:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Script already exists'})

        user = session.query(User).filter(User.id == \
                env['beaker.session']['loggedin_id']).first()

        if not user:
            return template_render(tmpl, { 'session' : env ['beaker.session'],
                'error' : 'Error: Invalid user in session?'})

        script = Script(s)
        script.owner = user

        session.add(script)
        try:
           session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback! create_script.'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(tmpl, { 'session' : env ['beaker.session'],
              'newscript' : script })

    return template_render(tmpl,
        { 'session' : env ['beaker.session']
            })
コード例 #6
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def manage_script(env, scriptid):
    """
        Page to manage a specific script. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl,
            {   'session' : env['beaker.session']}  )

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    script = session.query(Script).filter(Script.id == scriptid).first()

    if not script:
        return None

    if script.owner.name != user.name:
        return None

    if str(env['REQUEST_METHOD']) == 'POST':
            data = read_post_data(env)

            if data is None:
                return str('Error: Invalid POST data')

            if 'variable' in data:
                try:
                    id = data['variable']
                except ValueError:
                    return str('Invalid POST data: Not a number')

            var = session.query(Variable).filter(Variable.id == id).first()

            if var is None:
                return str('Invalid POST data: No such variable')

            if var not in script.variables:
                script.variables.append(var)

            try:
                session.commit()
            except sqlalchemy.exc.IntegrityError as e:
                session.rollback()
                print 'Rollback in stats.py, manage_script:'
                print 'Postdata:', data
                print 'Exception:', e

    vars = session.query(Variable).filter(Variable.is_var==1).all()
    vars_intersect = filter(lambda x: x not in script.variables, vars) if \
        script.variables is not None else vars

    tmpl = jinjaenv.get_template('managescript.html')

    return template_render(tmpl,
        { 'session' : env ['beaker.session'],
            'script' : script,
            'vars' : vars_intersect
            })
コード例 #7
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def api_commit(env):
    """
        API to send a commit to the stats system using POST data.
    """
    if str(env['REQUEST_METHOD']) != 'POST':
        # 404
        return None

    data = read_post_data(env)

    if data is None:
        return None

    # XXX FIXME This is ugly
    pd = data.copy()
    pd['password'] = '******'
    log.log([], LVL_INFORMATIVE, PyLogger.INFO,
            'API_COMMIT: %s, %s' % (env['REMOTE_ADDR'], pd))


    if not 'user' in data or not 'password' in data:
        return '110'

    data['user'] = urllib.unquote_plus(data['user'])
    data['password'] = urllib.unquote_plus(data['password'])

#    if not alphanumspace.match(data['user']):
#        return '110'
#
#    if not alphanumspace.match(data['password']):
#        return '110'

    data['password'] = hashlib.sha256(data['password']).hexdigest()

    session = Session()

    user = session.query(User).filter(User.name == data['user']).filter(
            User.password == data['password']).first()
    if not user:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No user' \
                        % (env['REMOTE_ADDR'], pd))
        return '110'

    del data['user']
    del data['password']

    if not 'script' in data:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No script' \
                        % (env['REMOTE_ADDR'], pd))
        return '120'

    data['script'] = urllib.unquote_plus(data['script'])

    script = session.query(Script).filter(Script.id == data['script']).first()

    if not script:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid script' \
                        % (env['REMOTE_ADDR'], pd))
        return '120'

    del data['script']

    if not 'time' in data:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No time' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    try:
        time = int(data['time'])
    except ValueError:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid time (int)' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    if time < 5 or time > 60:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid time (range)' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    del data['time']

    randoms = session.query(Variable).filter(Variable.is_var==0).all()

    script_vars = dict(zip([x.name.lower() for x in script.variables], 
        script.variables))

    script_vars.update(dict(zip([x.name.lower() for x in randoms], randoms)))

    script_vars.update(dict(zip([x.id for x in randoms], randoms)))

    script_vars.update(dict(zip([x.id for x in script.variables],
        script.variables)))

    vars = dict()

    for x, y in data.iteritems():
        x = urllib.unquote_plus(x)
        x = x.lower()

        try:
            x = int(x)
        except ValueError:
            pass

        if x not in script_vars:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable for script' \
                        % (env['REMOTE_ADDR'], pd))
            return '140'
        try:
            v = int(y)
        except ValueError:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable value' \
                        % (env['REMOTE_ADDR'], pd))
            return '150'

        if v < 1 or v > 10000:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable value (%d)' \
                        % (env['REMOTE_ADDR'], pd, v))
            return '150'

        vars[script_vars[x]] = v

    res = ct.add(user, script, time, vars)
    if not res:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
            'API_COMMIT: %s, %s DENIED: Internal error' \
                    % (env['REMOTE_ADDR'], pd))
        return '160'

    return '100'
コード例 #8
0
ファイル: stats.py プロジェクト: MerlijnWajer/SRL-Stats
def register_user(env):
    """
        Page to register a user. Handles POST and GET data.
    """
    tmpl = jinjaenv.get_template('registeruser.html')

    session = Session()

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Error: Invalid post data')

        if 'user' not in data or 'pass' not in data:
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'registerfail' : True,
                'error' : 'Post data not complete'}  )

        data['user'] = urllib.unquote_plus(data['user'])
        data['pass'] = urllib.unquote_plus(data['pass'])
        if 'mail' in data:
            data['mail'] = urllib.unquote_plus(data['mail'])

        if len(data['user']) > 20 or len(data['pass']) > 20 or \
           len(data['user']) == 0 or len(data['pass']) == 0:
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'registerfail' : True,
                'error' : 'Username or Password too long.'}  )

        data['pass'] = hashlib.sha256(data['pass']).hexdigest()

        if 'mail' in data:
            if len(data['mail']) > 40:
                return template_render(tmpl,
            {   'session' : env['beaker.session'], 'registerfail' : True,
                'error' : 'Email address is too long'} )

        log.log([], LVL_VERBOSE, PyLogger.INFO, 'Register POST data: %s' %
                str(data))

        if 'mail' in data and data['mail']:
            if not emailre.match(data['mail']):
                return template_render(tmpl,
                {   'session' : env['beaker.session'], 'registerfail' : True,
                    'error': 'Invalid Email.'}  )

        # Does the user exist?
        res =  session.query(User).filter(func.lower(User.name) ==
                data['user'].lower()).first()

        if res:
            return template_render(tmpl,
            {   'session' : env['beaker.session'], 'registerfail' : True,
                'error' : 'Username already exists'}  )


        user = User(data['user'], data['pass'], data['mail'] if 'mail' in data
                else None)

        session.add(user)
        try:
           session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback in register_user'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(tmpl,
            { 'session' : env['beaker.session'],
               'registersuccess' : True,
               'user' : user} )

    elif str(env['REQUEST_METHOD']) == 'GET':
        return template_render(tmpl,
            {   'session' : env['beaker.session']}  )
    else:
        return None
コード例 #9
0
def create_variable(env):
    """
        Page to create a variable. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl, {'session': env['beaker.session']})

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    if user.admin_level < 1:
        return str('Access denied')

    tmpl = jinjaenv.get_template('createvariable.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)
        if data is None:
            return str('Error: Invalid POST data')

        if 'variable' in data:
            s = data['variable']
            s = urllib.unquote_plus(s)
        else:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Variable name not specified'
                })

        if len(s) == 0 or len(s) > 60:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Variable name has invalid length'
                })

        # 'on' when checked; not in data when not clicked. XXX
        if 'is_var' in data:
            v = 1
        else:
            v = 0

        res = session.query(Variable).filter(Variable.name == s).first()

        if res:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Variable already exists'
                })

        variable = Variable(s, v)
        session.add(variable)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback! create_variable'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(tmpl, {
            'session': env['beaker.session'],
            'newvariable': variable
        })

    return template_render(tmpl, {'session': env['beaker.session']})
コード例 #10
0
def create_script(env):
    """
        Page to create a script. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl, {'session': env['beaker.session']})

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    tmpl = jinjaenv.get_template('createscript.html')

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)
        if data is None:
            return str('Error: Invalid POST data')

        if 'script' in data:
            s = data['script']
            s = urllib.unquote_plus(s)
        else:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Script contains invalid characters'
                })

        if len(s) == 0 or len(s) > 20:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Script name has invalid length'
                })

        res = session.query(Script).filter(Script.name == s).all()
        if res:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Script already exists'
                })

        user = session.query(User).filter(User.id == \
                env['beaker.session']['loggedin_id']).first()

        if not user:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Error: Invalid user in session?'
                })

        script = Script(s)
        script.owner = user

        session.add(script)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback! create_script.'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(tmpl, {
            'session': env['beaker.session'],
            'newscript': script
        })

    return template_render(tmpl, {'session': env['beaker.session']})
コード例 #11
0
def manage_script(env, scriptid):
    """
        Page to manage a specific script. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl, {'session': env['beaker.session']})

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    script = session.query(Script).filter(Script.id == scriptid).first()

    if not script:
        return None

    if script.owner.name != user.name:
        return None

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Error: Invalid POST data')

        if 'variable' in data:
            try:
                id = data['variable']
            except ValueError:
                return str('Invalid POST data: Not a number')

        var = session.query(Variable).filter(Variable.id == id).first()

        if var is None:
            return str('Invalid POST data: No such variable')

        if var not in script.variables:
            script.variables.append(var)

        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback in stats.py, manage_script:'
            print 'Postdata:', data
            print 'Exception:', e

    vars = session.query(Variable).filter(Variable.is_var == 1).all()
    vars_intersect = filter(lambda x: x not in script.variables, vars) if \
        script.variables is not None else vars

    tmpl = jinjaenv.get_template('managescript.html')

    return template_render(tmpl, {
        'session': env['beaker.session'],
        'script': script,
        'vars': vars_intersect
    })
コード例 #12
0
def api_commit(env):
    """
        API to send a commit to the stats system using POST data.
    """
    if str(env['REQUEST_METHOD']) != 'POST':
        # 404
        return None

    data = read_post_data(env)

    if data is None:
        return None

    # XXX FIXME This is ugly
    pd = data.copy()
    pd['password'] = '******'
    log.log([], LVL_INFORMATIVE, PyLogger.INFO,
            'API_COMMIT: %s, %s' % (env['REMOTE_ADDR'], pd))

    if not 'user' in data or not 'password' in data:
        return '110'

    data['user'] = urllib.unquote_plus(data['user'])
    data['password'] = urllib.unquote_plus(data['password'])

    #    if not alphanumspace.match(data['user']):
    #        return '110'
    #
    #    if not alphanumspace.match(data['password']):
    #        return '110'

    data['password'] = hashlib.sha256(data['password']).hexdigest()

    session = Session()

    user = session.query(User).filter(User.name == data['user']).filter(
        User.password == data['password']).first()
    if not user:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No user' \
                        % (env['REMOTE_ADDR'], pd))
        return '110'

    del data['user']
    del data['password']

    if not 'script' in data:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No script' \
                        % (env['REMOTE_ADDR'], pd))
        return '120'

    data['script'] = urllib.unquote_plus(data['script'])

    script = session.query(Script).filter(Script.id == data['script']).first()

    if not script:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid script' \
                        % (env['REMOTE_ADDR'], pd))
        return '120'

    del data['script']

    if not 'time' in data:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: No time' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    try:
        time = int(data['time'])
    except ValueError:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid time (int)' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    if time < 5 or time > 60:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid time (range)' \
                        % (env['REMOTE_ADDR'], pd))
        return '130'

    del data['time']

    randoms = session.query(Variable).filter(Variable.is_var == 0).all()

    script_vars = dict(
        zip([x.name.lower() for x in script.variables], script.variables))

    script_vars.update(dict(zip([x.name.lower() for x in randoms], randoms)))

    script_vars.update(dict(zip([x.id for x in randoms], randoms)))

    script_vars.update(
        dict(zip([x.id for x in script.variables], script.variables)))

    vars = dict()

    for x, y in data.iteritems():
        x = urllib.unquote_plus(x)
        x = x.lower()

        try:
            x = int(x)
        except ValueError:
            pass

        if x not in script_vars:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable for script' \
                        % (env['REMOTE_ADDR'], pd))
            return '140'
        try:
            v = int(y)
        except ValueError:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable value' \
                        % (env['REMOTE_ADDR'], pd))
            return '150'

        if v < 1 or v > 10000:
            log.log([], LVL_NOTABLE, PyLogger.WARNING,
                'API_COMMIT: %s, %s DENIED: Invalid variable value (%d)' \
                        % (env['REMOTE_ADDR'], pd, v))
            return '150'

        vars[script_vars[x]] = v

    res = ct.add(user, script, time, vars)
    if not res:
        log.log([], LVL_NOTABLE, PyLogger.WARNING,
            'API_COMMIT: %s, %s DENIED: Internal error' \
                    % (env['REMOTE_ADDR'], pd))
        return '160'

    return '100'
コード例 #13
0
def register_user(env):
    """
        Page to register a user. Handles POST and GET data.
    """
    tmpl = jinjaenv.get_template('registeruser.html')

    session = Session()

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Error: Invalid post data')

        if 'user' not in data or 'pass' not in data:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'registerfail': True,
                    'error': 'Post data not complete'
                })

        data['user'] = urllib.unquote_plus(data['user'])
        data['pass'] = urllib.unquote_plus(data['pass'])
        if 'mail' in data:
            data['mail'] = urllib.unquote_plus(data['mail'])

        if len(data['user']) > 20 or len(data['pass']) > 20 or \
           len(data['user']) == 0 or len(data['pass']) == 0:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'registerfail': True,
                    'error': 'Username or Password too long.'
                })

        data['pass'] = hashlib.sha256(data['pass']).hexdigest()

        if 'mail' in data:
            if len(data['mail']) > 40:
                return template_render(
                    tmpl, {
                        'session': env['beaker.session'],
                        'registerfail': True,
                        'error': 'Email address is too long'
                    })

        log.log([], LVL_VERBOSE, PyLogger.INFO,
                'Register POST data: %s' % str(data))

        if 'mail' in data and data['mail']:
            if not emailre.match(data['mail']):
                return template_render(
                    tmpl, {
                        'session': env['beaker.session'],
                        'registerfail': True,
                        'error': 'Invalid Email.'
                    })

        # Does the user exist?
        res = session.query(User).filter(
            func.lower(User.name) == data['user'].lower()).first()

        if res:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'registerfail': True,
                    'error': 'Username already exists'
                })

        user = User(data['user'], data['pass'],
                    data['mail'] if 'mail' in data else None)

        session.add(user)
        try:
            session.commit()
        except sqlalchemy.exc.IntegrityError as e:
            session.rollback()
            print 'Rollback in register_user'
            print 'Post data:', data
            print 'Exception:', e

        return template_render(
            tmpl, {
                'session': env['beaker.session'],
                'registersuccess': True,
                'user': user
            })

    elif str(env['REQUEST_METHOD']) == 'GET':
        return template_render(tmpl, {'session': env['beaker.session']})
    else:
        return None
コード例 #14
0
def manage_variable(env, variableid):
    """
        Page to manage a variable. Handles both GET and POST.
    """
    if not loggedin(env):
        tmpl = jinjaenv.get_template('loginform.html')
        return template_render(tmpl, {'session': env['beaker.session']})

    session = Session()

    user = session.query(User).filter(User.id == \
            env['beaker.session']['loggedin_id']).first()

    if not user:
        return None

    if user.admin_level < 1:
        return str('Access denied')

    tmpl = jinjaenv.get_template('managevariable.html')

    variable = session.query(Variable).filter(Variable.id == \
            variableid).first()

    if not variable:
        return None

    if str(env['REQUEST_METHOD']) == 'POST':
        data = read_post_data(env)

        if data is None:
            return str('Invalid POST data')

        if 'newname' not in data:
            return str('Invalid POST data')

        data['newname'] = urllib.unquote_plus(data['newname'])
        if len(data['newname']) == 0 or len(data['newname']) > 20:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Variable name too long.',
                })

        res = session.query(Variable).filter(
            Variable.name == data['newname']).first()

        if res is None:
            variable.name = data['newname']
            session.add(variable)
            try:
                session.commit()
            except sqlalchemy.exc.IntegrityError as e:
                session.rollback()
                print 'Rollback in manage_variable'
                print 'Post data:', data
                print 'Exception:', e
        else:
            return template_render(
                tmpl, {
                    'session': env['beaker.session'],
                    'error': 'Name already exists in the system.',
                    'variable': variable
                })

    return template_render(tmpl, {
        'session': env['beaker.session'],
        'variable': variable
    })