Ejemplo n.º 1
0
    def POST(self, filepath):
        web.header('Content-Type', 'text/plain; charset=UTF-8')
        filepath = str(filepath)

        if filepath == '/':
            granted_locks = {}

            for filepath in web.data().split('\n'):
                if not filepath:
                       continue

                try:
                    granted_locks[filepath] = _grant_new_lock(filepath)
                except Exception as e:
                    logging.exception(e)

                    for filepath in granted_locks: #revoke all reviously allocated locks
                        _revoke_lock(filepath)

                    raise web.unauthorized()

            return '\n'.join('%s=%d' % (filepath, lock_id,) #list file name, lock id
                    for filepath, lock_id in granted_locks.items())

        try:
            return _grant_new_lock(filepath)
        except Exception as e:
            logging.exception(e)
            raise web.unauthorized()
Ejemplo n.º 2
0
def myProcessor(handler):
    web.ctx.veerezoDB = model.getDBConnection()
    try:
        username = checkUserAuth()
        web.ctx.username = username
    except ValueError:
        web.header('WWW-Authenticate', 'Basic realm="Veerezo"')
        web.unauthorized()
        return 'Access denied'

    web.ctx.beanstalk = pybsc.BeanstalkClient()

    def postBackendJob(method, *args, **kwargs):
        d = {}
        d['method'] = method
        d['args'] = args
        d['kwargs'] = kwargs

        jobID = web.ctx.beanstalk.put(json.dumps(d),
                                      ttr=60,
                                      tube='veerezo-backend')
        model.addJob(web.ctx.veerezoDB, jobID)

        return jobID

    web.ctx.postBackendJob = postBackendJob
    result = handler()
    return result
Ejemplo n.º 3
0
    def POST(self, filepath):
        web.header('Content-Type', 'text/plain; charset=UTF-8')
        filepath = str(filepath)

        if filepath == '/':
            granted_locks = {}

            for filepath in web.data().split('\n'):
                if not filepath:
                    # to allow an empty line at the end of the request data
                    continue

                try:
                    lock_id = random.randrange(0, 32768)
                    logging.info('Granting lock (%d) on %s.', lock_id,
                                 filepath)
                    t = datetime.datetime.now()
                    lock[filepath] = lock(lock_id, t, t)
                    return lock_id
                except Exception as e:
                    logging.exception(e)

                    raise web.unauthorized()

            # list of filename=lock_id
            return '\n'.join('%s=%d' % (filepath, lock_id,) \
                             for filepath, lock_id in granted_locks.items())

        raise web.unauthorized()
Ejemplo n.º 4
0
def processor(handler):
    api_name = web.ctx.path.split("/")[-1]

    if web.ctx.path not in anonymous_urls:
        if api_name != 'login' and api_name != 'logout' and not session.get('logged_in', False):
            if Ezs3CephConfig().get_cluster_name():
                raise web.unauthorized()
            else:
                # customize message to hint user login with root account
                raise web.unauthorized('need root')

        if api_name != 'login':
            # make login_id and login_type accessible by handlers
            web.ctx.login_id = session.get('login_id')
            web.ctx.login_type = session.get('login_type')
            if not check_url_permission():
                raise web.unauthorized()

    if api_name in binary_api:
        web.header('Content-type', 'application/octet-stream')
        return handler()
    else:
        result = handler()
        if isinstance(result, int):
            resp = response(api_name, result)
        elif isinstance(result, tuple):
            if len(result) == 2:
                resp = extra_response(api_name, result[0], result[1])
            else:
                logger.error("Invalid API response: {}".format(result))
                resp = response(api_name, errors.GENERAL.GENERAL_ERROR)
        else:
            logger.error("Invalid API response: {}".format(result))
            resp = response(api_name, errors.GENERAL.GENERAL_ERROR)
        return resp
Ejemplo n.º 5
0
    def wrapper(self, *args, **kwargs):
        if web.ctx.env.has_key("HTTP_AUTHORIZATION"):
            (user, email) = login()

            if user:
                self.me = user

                # Logout
                fname = "%s%s" % (LOGOUT_FILE_PREFIX, self.me.email)
                if os.access(fname, os.F_OK):
                    os.unlink(fname)
                    return web.unauthorized()

                # Login: Success
                if user.languages in self.languages:
                    x = self.languages.index(user.languages)
                    self.languages.pop(x)

                self.languages.insert(0, user.languages)
                self.logger.info(
                    "user_id=%s,lang=%s : Method=%s - Basic Authentication=Success"
                    % (self.me.id, ",".join(self.languages), self.__method__)
                )

                # __init__#self._ update!!
                self._ = mako_translation(languages=self.languages)
                return func(self, *args, **kwargs)
            else:
                # Login: Failure
                self.logger.info("user=%s : Method=%s - Basic Authentication=Failure" % (email, self.__method__))
                return web.unauthorized()
        else:
            # Login: Anonymous
            self.logger.info("user=anonymous : Method=%s - Basic Authentication=Anonymous" % (self.__method__))
            return web.unauthorized()
Ejemplo n.º 6
0
def validate_basic_auth():
    """
  Authenticates against the database user accounts using HTTP Basic authentication
  """
    log.loggit('validate_basic_auth()')
    auth_header = web.ctx.env.get('HTTP_AUTHORIZATION')
    username = ""
    password = ""

    if auth_header is None:
        raise web.unauthorized(UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS)

    elif not auth_header.startswith('Basic '):
        raise web.unauthorized(UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS)

    else:
        auth = re.sub('^Basic ', '', auth_header)
        username, password = base64.decodestring(auth).split(':')

    adb = accountdb.AccountDB()
    account = adb.login(username, password, False)
    if account is None:
        raise web.unauthorized(UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS)

    return True
Ejemplo n.º 7
0
def _auth_check():
    """ checks if user is authenticated and throws exception if he isn't """
    try:
        if not _is_authenticated():
            raise web.unauthorized()
    except:
        raise web.unauthorized()
Ejemplo n.º 8
0
def validate_basic_auth():
  """
  Authenticates against the database user accounts using HTTP Basic authentication
  """
  log.loggit( 'validate_basic_auth()' )
  auth_header = web.ctx.env.get('HTTP_AUTHORIZATION')
  username = ""
  password = ""

  if auth_header is None:
    raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )

  elif not auth_header.startswith('Basic '):
    raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )

  else:
    auth = re.sub('^Basic ','',auth_header)
    username, password = base64.decodestring( auth ).split(':')

  adb = accountdb.AccountDB()
  account = adb.login( username, password, False )
  if account is None:
    raise web.unauthorized( UNAUTHORIZED_MESSAGE, UNAUTHORIZED_HEADERS )

  return True
Ejemplo n.º 9
0
def myProcessor(handler):
    web.ctx.veerezoDB = model.getDBConnection()
    try:
        username = checkUserAuth()
        web.ctx.username = username
    except ValueError:
        web.header('WWW-Authenticate', 'Basic realm="Veerezo"')
        web.unauthorized()
        return 'Access denied'

    web.ctx.beanstalk = pybsc.BeanstalkClient()

    def postBackendJob(method, *args, **kwargs):
        d = {}
        d['method'] = method
        d['args'] = args
        d['kwargs'] = kwargs

        jobID = web.ctx.beanstalk.put(json.dumps(d), ttr=60, tube='veerezo-backend')
        model.addJob(web.ctx.veerezoDB, jobID)

        return jobID
    web.ctx.postBackendJob = postBackendJob
    result = handler()
    return result
Ejemplo n.º 10
0
    def _setReturnCode(self, code):
        """Set the return code

        :param: code
        :type code: integer or string
        returns success: [True|False]
        """
        success = False

        if code in (200, "200", "ok"):
            web.ok()
            success = True
        elif code in (201, "201", "created"):
            web.created()
            success = True
        elif code in (400, "400", "badrequest"):
            web.badrequest()
        elif code in (401, "401", "unauthorized"):
            web.unauthorized()
        elif code in (404, "404", "notfound"):
            web.notfound()
        elif code in (409, "409", "conflict"):
            web.conflict()
        elif code in (500, "500", "internalerror"):
            web.internalerror()

        if success:
            logging.debug("[LayMan][_setReturnCode] Code: '%s'" % code)
        else:
            logging.error("[LayMan][_setReturnCode] Code: '%s'" % code)

        return success
Ejemplo n.º 11
0
    def _getParamsOrError(self):
        params = {}

        try:
                body = xml.dom.minidom.parseString(web.data())
                request = body.getElementsByTagName("Request")[0]
                for param in request.childNodes:
                        if (param.nodeType == param.ELEMENT_NODE):
                                params[param.tagName] = param.childNodes[0].data
        except:
                raise web.badrequest()

        if (not web.ctx.environ.has_key('HTTP_X_FINKIN_AUTH')):
                raise web.unauthorized()

        if (web.ctx.environ.has_key('HTTP_X_FINKIN_DEBUG')):
                params['debug'] = True

        fda = finkin.FinkinDA(False)
	userID = fda.Auth(web.ctx.environ['HTTP_X_FINKIN_AUTH'])
        if (userID == 0):
                raise web.unauthorized()
	params['log-user'] = userID

        return params
    def POST(self, path):
        web.header('Content-Type', 'text; char=UTF-8')
        path = str(path)

        if path == '/':
            lock_given = {}

            for path in web.data().split('\n'):
                if not path:
                    continue

                try:
                    lock_given[path] = _check_new_lock(path)
                except Exception as e:
                    logging.exception(e)                    
                    for path in lock_given:
                        lock_given(path)
                    raise web.unauthorized()
            return '\n'.join('%s=%d' % (path, lock_id,)\
                    for path, lock_id in lock_given.items())
        try:
            return _check_new_lock(path)
        except Exception as e:
            logging.exception(e)
            raise web.unauthorized()
Ejemplo n.º 13
0
 def GET(self):
     qdict = web.input()
     try:
         if not qdict.has_key('o25') and qdict['pw'] != base64.b64decode(
                 gv.sd['pwd']):
             raise web.unauthorized()
             return
         elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict[
                 'pw'] != base64.b64decode(gv.sd['pwd']):
             raise web.unauthorized()
             return
         elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict[
                 'pw'] == base64.b64decode(gv.sd['pwd']):
             gv.sd['ipas'] = 1
     except KeyError:
         pass
     try:
         if qdict['cpw'] != '' and qdict['cpw'] == qdict['npw']:
             gv.sd['pwd'] = base64.b64encode(qdict['npw'])
     except KeyError:
         pass
     vstr = data('options')
     ops = vstr.index('[') + 1
     ope = vstr.index(']')
     optstr = vstr[ops:ope]
     optlst = optstr.split(',')
     onumlst = []
     i = 3
     while i < len(optlst):
         onumlst.append(optlst[i].replace(' ', ''))
         if optlst[i - 2] == '1':  #clear check box items
             optlst[i - 1] = '0'
             try:
                 sdref[optlst[i]]
                 gv.sd[sdref[optlst[i]]] = 0
             except KeyError:
                 pass
         i += 4
     for key in qdict.keys():
         if key[:1] == 'o':
             oidx = onumlst.index(key[1:])
             if qdict[key] == 'on' or '':
                 qdict[key] = '1'
             optlst[(oidx * 4) + 2] = qdict[key]
     optstr = ','.join(optlst)
     optstr = optstr.replace(', ', ',')
     vstr = vstr.replace(vstr[ops:ope], optstr)
     save('options', vstr)
     if int(qdict['o15']) + 1 != gv.sd['nbrd']: self.update_scount(qdict)
     if int(qdict['o18']) != gv.sd['mas']:
         clear_mm()
     self.update_sd(qdict)
     raise web.seeother('/')
     #alert = '<script>alert("Options values saved.");window.location="/";</script>'
     return  #alert # -- Alerts are not considered good interface progrmming. Use sparingly!
Ejemplo n.º 14
0
 def __init__(self):
     # Authenticate a request and save the associated product and component ID
     logger.debug('Authenticating a new request')
     self.product_id = SprinklerDB.authorize_product()
     if not self.product_id:
         logger.warn('Not Authenticated: Unknown API KEY')
         raise web.unauthorized('Unknown API KEY')
     self.valve_id = SprinklerDB.get_component_id(self.product_id, config['VALVE_COMP_TYPE'])
     if not self.valve_id:
         logger.warn('Not Authenticated: Not authorized for component')
         raise web.unauthorized('Not authorized for component')
     logger.info('Request authenticated: Product ID:%d, Valve ID:%d', self.product_id, self.valve_id)
Ejemplo n.º 15
0
 def GET(self):
     qdict = web.input()
     try:
         if not qdict.has_key('o25') and qdict['pw'] != base64.b64decode(gv.sd['pwd']):
             raise web.unauthorized()
             return
         elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict['pw'] != base64.b64decode(gv.sd['pwd']):
             raise web.unauthorized()
             return
         elif qdict.has_key('o25') and gv.sd['ipas'] == 0 and qdict['pw'] == base64.b64decode(gv.sd['pwd']):
             gv.sd['ipas'] = 1
     except KeyError:
         pass
     try:
         if qdict['cpw'] !='' and qdict['cpw'] == qdict['npw']:
             gv.sd['pwd'] = base64.b64encode(qdict['npw'])
     except KeyError:
         pass 
     vstr = data('options')
     ops = vstr.index('[')+1
     ope = vstr.index(']')
     optstr = vstr[ops:ope]
     optlst = optstr.split(',')
     onumlst = []
     i=3
     while i < len(optlst):
         onumlst.append(optlst[i].replace(' ', ''))
         if optlst[i-2] == '1': #clear check box items
             optlst[i-1]= '0'
             try:
               sdref[optlst[i]];  
               gv.sd[sdref[optlst[i]]]=0
             except KeyError:
                 pass
         i+=4
     for key in qdict.keys():
         if key[:1] == 'o':
             oidx = onumlst.index(key[1:])
             if qdict[key] == 'on' or '':
                 qdict[key] = '1'
             optlst[(oidx*4)+2] = qdict[key]   
     optstr = ','.join(optlst)
     optstr = optstr.replace(', ', ',')
     vstr = vstr.replace(vstr[ops:ope], optstr)
     save('options', vstr)
     if int(qdict['o15'])+1 != gv.sd['nbrd']: self.update_scount(qdict)
     if int(qdict['o18']) != gv.sd['mas']:
         clear_mm()
     self.update_sd(qdict)
     raise web.seeother('/')
     #alert = '<script>alert("Options values saved.");window.location="/";</script>'
     return #alert # ---- Alerts are not considered good interface progrmming. Use sparingly!
Ejemplo n.º 16
0
    def wrapper(self, *args, **kwargs):

        if web.ctx.path[0:6] == '/data/':
            languages = unicode(karesansui.config['application.default.locale'])
            if web.ctx.env.has_key('HTTP_AUTHORIZATION'):
                _http_auth = web.ctx.env['HTTP_AUTHORIZATION'].strip()
                if _http_auth[:5] == 'Basic':
                    email, password = b64decode(_http_auth[6:].strip()).split(':')
                    session = web.ctx.orm
                    user = findby1email(session, email)
                    languages = user.languages

            self._ = mako_translation(languages=[ unicode(languages), ])
            return func(self, *args, **kwargs)

        if karesansui_database_exists() is False:
            return web.tempredirect(web.ctx.path + "init", absolute=False)

        if web.ctx.env.has_key('HTTP_AUTHORIZATION'):
            (user, email) = login()

            if user:
                self.me = user

                # Logout
                fname = '%s%s' % (LOGOUT_FILE_PREFIX, self.me.email,)
                if os.access(fname, os.F_OK):
                    os.unlink(fname)
                    return web.unauthorized()

                # Login: Success
                if user.languages in self.languages:
                    x = self.languages.index(user.languages)
                    self.languages.pop(x)
                    
                self.languages.insert(0, user.languages)
                self.logger.info('user_id=%s,lang=%s : Method=%s - Basic Authentication=Success' %
                                  (self.me.id, ','.join(self.languages), self.__method__))
                
                # __init__#self._ update!!
                self._ = mako_translation(languages=self.languages)
                return func(self, *args, **kwargs)
            else:
                 # Login: Failure
                self.logger.info('user=%s : Method=%s - Basic Authentication=Failure' %
                                  (email, self.__method__))
                return web.unauthorized()
        else:
            # Login: Anonymous
            self.logger.info('user=anonymous : Method=%s - Basic Authentication=Anonymous' %
                              (self.__method__))
            return web.unauthorized()
Ejemplo n.º 17
0
    def POST(self, filepath):
        """If filepath == / (useless for now, but allow easy addition
           of transactions: try to get a lock for all filepaths in the
           request data (each one is separated from the next one
           by a newline). If it's possible return a list of
           filepath/lock_id like this:
               /data/sample.in=12345
               /src/linux/kernel.h=42
           If at least one file can't be locked, then no lock is granted
           and a '401 Unauthorized' response is send.

           Else, if there's no lock on filepath, or an old lock,
           grant a new one (and revoke the older one if needed).
           Return a 200 OK, with the lock id.

           If a client want mutliples locks it should request them in one
           query (/) because if it ask in one request for each lock, it may
           create dead locks.
        """

        web.header('Content-Type', 'text/plain; charset=UTF-8')
        filepath = str(filepath)

        if filepath == '/':
            granted_locks = {}

            for filepath in web.data().split('\n'):
                if not filepath:
                    # to allow an empty line at the end of the request data
                    continue

                try:
                    granted_locks[filepath] = _grant_new_lock(filepath)
                except Exception as e:
                    logging.exception(e)

                    # revoking all previoulsy allocated locks
                    for filepath in granted_locks:
                        _revoke_lock(filepath)

                    raise web.unauthorized()

            # list of filename=lock_id
            return '\n'.join('%s=%d' % (filepath, lock_id,)\
                    for filepath, lock_id in granted_locks.items())

        try:
            return _grant_new_lock(filepath)
        except Exception as e:
            logging.exception(e)
            raise web.unauthorized()
Ejemplo n.º 18
0
    def POST(self, filepath):
        """If filepath == / (useless for now, but allow easy addition
           of transactions: try to get a lock for all filepaths in the
           request data (each one is separated from the next one
           by a newline). If it's possible return a list of
           filepath/lock_id like this:
               /data/sample.in=12345
               /src/linux/kernel.h=42
           If at least one file can't be locked, then no lock is granted
           and a '401 Unauthorized' response is send.

           Else, if there's no lock on filepath, or an old lock,
           grant a new one (and revoke the older one if needed).
           Return a 200 OK, with the lock id.

           If a client want mutliples locks it should request them in one
           query (/) because if it ask in one request for each lock, it may
           create dead locks.
        """

        web.header('Content-Type', 'text/plain; charset=UTF-8')
        filepath = str(filepath)

        if filepath == '/':
            granted_locks = {}

            for filepath in web.data().split('\n'):
                if not filepath:
                    # to allow an empty line at the end of the request data
                    continue

                try:
                    granted_locks[filepath] = _grant_new_lock(filepath)
                except Exception as e:
                    logging.exception(e)

                    # revoking all previoulsy allocated locks
                    for filepath in granted_locks:
                        _revoke_lock(filepath)

                    raise web.unauthorized()

            # list of filename=lock_id
            return '\n'.join('%s=%d' % (filepath, lock_id,)\
                    for filepath, lock_id in granted_locks.items())

        try:
            return _grant_new_lock(filepath)
        except Exception as e:
            logging.exception(e)
            raise web.unauthorized()
Ejemplo n.º 19
0
 def GET(self):
     #check if the user is Admin
     if web.ctx.session.is_admin(): 
     	render = get_render('admin')
     	return render.add_user()
     else:
     	return web.unauthorized()
Ejemplo n.º 20
0
    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        validate_remote(ddict) # may raise unauthorized

        subj = ''
        body = ''
        try:
            subj = ddict['subject']
            body = ddict['body']
            if gv.sd['master']:
                email(subj, body)
                ret_str = json.dumps({'status':0})
            else:
                gv.logger.error('mail not sent by slave body: ' + body)
                ret_str = json.dumps({'status':1})
        except:
            gv.logger.exception('could not send email. subject: ' + subj + ' body: ' + body)
            ret_str = json.dumps({'status':2})
        web.header('Content-Type', 'application/json')
        return ret_str
Ejemplo n.º 21
0
def check_login(redirect=False):
    from ospy import server
    import web
    from ospy.options import options
    qdict = web.input()

    try:
        if options.no_password:
            return True

        if server.session.validated:
            return True
    except KeyError:
        pass

    if 'pw' in qdict:
        if test_password(qdict['pw']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login', True)
    return False
Ejemplo n.º 22
0
    def GET(self, resource_type=None, resource=None):
        """
        Credentials here are not actually used for authorization, but instead
        are used to identify:

            consumer ID in the username field
            repository ID in the password field

        This is to work around the fact that the "puppet module install"
        command has hard-coded absolute paths, so we cannot put consumer or
        repository IDs in the URL's path.
        """
        if resource_type is not None:
            if resource_type == self.REPO_RESOURCE:
                credentials = ('.', resource)
            elif resource_type == self.CONSUMER_RESOURCE:
                credentials = (resource, '.')
            else:
                return web.notfound()

        else:
            credentials = self._get_credentials()
            if not credentials:
                return web.unauthorized()

        module_name = self._get_module_name()
        if not module_name:
            # apparently our version of web.py, 0.36, doesn't take a message
            # parameter for error handlers like this one. Ugh.
            return web.badrequest()
        version = web.input().get('version')

        data = self.get_releases(*credentials, module_name=module_name, version=version)
        return self.format_results(data)
Ejemplo n.º 23
0
    def GET(self):
        """
        Credentials here are not actually used for authorization, but instead
        are used to identify:

            consumer ID in the username field
            repository ID in the password field

        This is to work around the fact that the "puppet module install"
        command has hard-coded absolute paths, so we cannot put consumer or
        repository IDs in the URL's path.
        """
        credentials = self._get_credentials()
        if not credentials:
            return web.unauthorized()

        module_name = self._get_module_name()
        if not module_name:
            # apparently our version of web.py, 0.36, doesn't take a message
            # parameter for error handlers like this one. Ugh.
            return web.badrequest()
        version =  web.input().get('version')

        web.header('Content-Type', 'application/json')
        data = releases.view(*credentials, module_name=module_name, version=version)
        return json.dumps(data)
Ejemplo n.º 24
0
    def GET(self):
        qdict = web.input()

        #ensure request is from localhost and we trust it
        remote = web.ctx.env['REMOTE_ADDR']
        if remote != '127.0.0.1':
            gv.logger.info('receive_remote_sensor_data invalid remote: ' + remote)
            raise web.unauthorized()

        remote_sensor_name = ''
        try:
            remote_sensor_name = qdict['name']
            del qdict['name']
            if remote_sensor_name in gv.remote_sensors:
                sensor_data = gv.remote_sensors[remote_sensor_name]
            else:
                sensor_data = {}
            for key in qdict:
                sensor_data[key] = int(qdict[key], 0)
            sensor_data['time'] = gv.now
            gv.remote_sensors[remote_sensor_name] = sensor_data
        except:
            gv.logger.exception('receive_remote_sensor_data name: ' + remote_sensor_name + ' qdict: ' + str(qdict))

        zone_list = []
        for z in gv.remote_zones:
            zone_list.append(z)
        web.header('Content-Type', 'application/json')
        return json.dumps(zone_list)
Ejemplo n.º 25
0
 def GET(self):
     qdict = web.input()
     try:
         if gv.sd["ipas"] != 1 and qdict["pw"] != base64.b64decode(gv.sd["pwd"]):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     pnum = int(qdict["pid"]) + 1  # program number
     cp = json.loads(qdict["v"])
     if cp[0] == 0 and pnum == gv.pon:  # if disabled and program is running
         for i in range(len(gv.ps)):
             if gv.ps[i][0] == pnum:
                 gv.ps[i] = [0, 0]
             if gv.srvals[i]:
                 gv.srvals[i] = 0
         for i in range(len(gv.rs)):
             if gv.rs[i][3] == pnum:
                 gv.rs[i] = [0, 0, 0, 0]
     if cp[1] >= 128 and cp[2] > 1:
         dse = int((time.time() - time.timezone) / 86400)
         ref = dse + cp[1] - 128
         cp[1] = (ref % cp[2]) + 128
     if int(qdict["pid"]) > gv.sd["mnp"]:
         alert = '<script>alert("Maximum number of programs\n has been reached.");window.location="/";</script>'
         return alert
     elif qdict["pid"] == "-1":  # add new program
         gv.pd.append(cp)
     else:
         gv.pd[int(qdict["pid"])] = cp  # replace program
     jsave(gv.pd, "programs")
     gv.sd["nprogs"] = len(gv.pd)
     raise web.seeother("/vp")
     return
Ejemplo n.º 26
0
    def GET(self):
        #Check if Admin
        if web.ctx. session.is_admin():       
	        render = get_render('admin')
	        return render.user()
        else:
        	return web.unauthorized()
Ejemplo n.º 27
0
 def GET(self):
     qdict = web.input()
     try:
         if gv.sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(gv.sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     if not gv.sd['en']: return # check operation status
     gv.rovals = json.loads(qdict['t'])
     gv.rovals.pop()
     gv.ps = []
     for i in range(gv.sd['nst']):
         gv.ps.append([0,0])
     gv.rs = [] #run schedule
     for i in range(gv.sd['nst']): # clear run schedule
         gv.rs.append([0,0,0,0])
     ro_now = time.time()    
     for i, v in enumerate(gv.rovals):
         if v: # if this element has a value
             gv.rs[i][0] = ro_now
             gv.rs[i][2] = v
             gv.rs[i][3] = 98
             gv.ps[i][0] = 98
             gv.ps[i][1] = v
     schedule_stations(ro_now)
     raise web.seeother('/')
Ejemplo n.º 28
0
def check_login(redirect=False):
    """
    Check login.
    """
    qdict = web.input()

    try:
        if gv.sd['ipas'] == 1:
            return True

        if web.config._session.user == 'admin':
            return True
    except KeyError:
        pass

    if 'pw' in qdict:
        if gv.sd['password'] == password_hash(qdict['pw'], gv.sd['salt']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login')
    return False
Ejemplo n.º 29
0
def _raise_if_locked(filepath): #Exception 401 if file is locked and lockid doesn't match as per the request

    i = web.input()

    host, port = utils.get_host_port(_config['lockserver'])
    if utils.is_locked(filepath, host, port, i.get('lock_id', None)):
        raise web.unauthorized()
Ejemplo n.º 30
0
    def GET(self):
        """
        Credentials here are not actually used for authorization, but instead
        are used to identify:

            consumer ID in the username field
            repository ID in the password field

        This is to work around the fact that the "puppet module install"
        command has hard-coded absolute paths, so we cannot put consumer or
        repository IDs in the URL's path.
        """
        credentials = self._get_credentials()
        if not credentials:
            return web.unauthorized()

        module_name = self._get_module_name()
        if not module_name:
            # apparently our version of web.py, 0.36, doesn't take a message
            # parameter for error handlers like this one. Ugh.
            return web.badrequest()
        version = web.input().get('version')

        web.header('Content-Type', 'application/json')
        data = releases.view(*credentials,
                             module_name=module_name,
                             version=version)
        return json.dumps(data)
Ejemplo n.º 31
0
def check_login(redirect=False):
    """
    Check login.
    """
    qdict = web.input()

    try:
        if gv.sd['ipas'] == 1:
            return True

        if web.config._session.user == 'admin':
            return True
    except KeyError:
        pass

    if 'pw' in qdict:
        if gv.sd['password'] == password_hash(qdict['pw'], gv.sd['salt']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login')
    return False
Ejemplo n.º 32
0
 def GET(self):
     qdict = web.input()
     try:
         if gv.sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(
                 gv.sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     pnum = int(qdict['pid']) + 1  # program number
     cp = json.loads(qdict['v'])
     if cp[0] == 0 and pnum == gv.pon:  # if disabled and program is running
         for i in range(len(gv.ps)):
             if gv.ps[i][0] == pnum:
                 gv.ps[i] = [0, 0]
             if gv.srvals[i]:
                 gv.srvals[i] = 0
         for i in range(len(gv.rs)):
             if gv.rs[i][3] == pnum:
                 gv.rs[i] = [0, 0, 0, 0]
     if cp[1] >= 128 and cp[2] > 1:
         dse = int((time.time() - time.timezone) / 86400)
         ref = dse + cp[1] - 128
         cp[1] = (ref % cp[2]) + 128
     if int(qdict['pid']) > gv.sd['mnp']:
         alert = '<script>alert("Maximum number of programs\n has been reached.");window.location="/";</script>'
         return alert
     elif qdict['pid'] == '-1':  #add new program
         gv.pd.append(cp)
     else:
         gv.pd[int(qdict['pid'])] = cp  #replace program
     jsave(gv.pd, 'programs')
     gv.sd['nprogs'] = len(gv.pd)
     raise web.seeother('/vp')
     return
Ejemplo n.º 33
0
 def GET(self):
     qdict = web.input()
     global rovals, sd
     try:
         if sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     if not sd['en']: return # check operation status
     sd['rsn'] = 0
     sd['bsy'] = 1
     rovals = json.loads(qdict['t'])
     rovals.pop()
     gv.ps = []
     for i in range(sd['nst']):
         gv.ps.append([0,0])
     for i, t in enumerate(rovals):
         if t != 0:
             gv.ps[i][0] = 98
             gv.ps[i][1] = t
             gv.rs[i][1] = time.time() + t
     thread.start_new_thread(self.run, ())
     raise web.seeother('/')
     return
Ejemplo n.º 34
0
def check_login(redirect=False):
    from ospy import server
    import web
    from ospy.options import options
    qdict = web.input()

    try:
        if options.no_password:
            return True

        if server.session.validated:
            return True
    except KeyError:
        pass

    if 'pw' in qdict:
        if test_password(qdict['pw']):
            return True
        if redirect:
            raise web.unauthorized()
        return False

    if redirect:
        raise web.seeother('/login', True)
    return False
Ejemplo n.º 35
0
    def GET(self):
        qdict = web.input()

        #ensure request is from localhost and we trust it
        remote = web.ctx.env['REMOTE_ADDR']
        if remote != '127.0.0.1':
            gv.logger.info('receive_remote_sensor_data invalid remote: ' + remote)
            raise web.unauthorized()

        remote_sensor_name = ''
        try:
            remote_sensor_name = qdict['name']
            del qdict['name']
            if remote_sensor_name in gv.remote_sensors:
                sensor_data = gv.remote_sensors[remote_sensor_name]
            else:
                sensor_data = {}
            for key in qdict:
                sensor_data[key] = int(qdict[key], 0)
            sensor_data['time'] = gv.now
            gv.remote_sensors[remote_sensor_name] = sensor_data
        except:
            gv.logger.exception('receive_remote_sensor_data name: ' + remote_sensor_name + ' qdict: ' + str(qdict))

        zone_list = []
        for z in gv.remote_zones:
            zone_list.append(z)
        web.header('Content-Type', 'application/json')
        return json.dumps(zone_list)
Ejemplo n.º 36
0
 def GET(self):
     qdict = web.input()
     try:
         if gv.sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(
                 gv.sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     if not gv.sd['en']: return  # check operation status
     gv.rovals = json.loads(qdict['t'])
     gv.rovals.pop()
     gv.ps = []
     for i in range(gv.sd['nst']):
         gv.ps.append([0, 0])
     gv.rs = []  #run schedule
     for i in range(gv.sd['nst']):  # clear run schedule
         gv.rs.append([0, 0, 0, 0])
     ro_now = time.time()
     for i, v in enumerate(gv.rovals):
         if v:  # if this element has a value
             gv.rs[i][0] = ro_now
             gv.rs[i][2] = v
             gv.rs[i][3] = 98
             gv.ps[i][0] = 98
             gv.ps[i][1] = v
     schedule_stations(ro_now)
     raise web.seeother('/')
Ejemplo n.º 37
0
def check_login(redirect=False):
    """
    Check login.
    """
    qdict = web.input()

    try:
        #         if gv.sd['ipas'] == 1:
        #             return True

        if web.config._session['user'] == 'admin':
            return True
    except KeyError:
        pass

    if ('password' in qdict) and ('username' in qdict):
        if validate_login(qdict['username'], qdict['password']):
            return True
        if redirect:
            raise web.unauthorized()
        return False


#     if 'pw' in qdict:
#         if gv.sd['password'] == password_hash(qdict['pw'], gv.sd['salt']):
#             return True
#         if redirect:
#             raise web.unauthorized()
#         return False

    if redirect:
        raise web.seeother('/login')
    return False
Ejemplo n.º 38
0
Archivo: ospi.py Proyecto: cwalv/OSPi
def approve_pwd(qdict):
    """Password checking"""
    try:
        if not gv.sd['ipas'] and not qdict['pw'] == base64.b64decode(gv.sd['pwd']):
            raise web.unauthorized()
    except KeyError:
        pass
Ejemplo n.º 39
0
def approve_pwd(qdict):
    """Password checking"""
    try:
        if not gv.sd['ipas'] and not qdict['pw'] == base64.b64decode(gv.sd['pwd']):
            raise web.unauthorized()
    except KeyError:
        pass
Ejemplo n.º 40
0
    def GET(self, tenant_id):
        auth_token = web.ctx.get("environ").get("HTTP_X_AUTH_TOKEN", None)
        auth_tenant_id = web.ctx.get("environ").get("HTTP_X_AUTH_TENANT_ID", None)

        keystone = identity.auth(
            token_id=auth_token,
            tenant_id=auth_tenant_id,
            url=_endpoint,
            api="NATIVE",
            admin=True,
            admin_url="http://10.100.32.36:35357/v2.0",
        )
        keystone.management_url = _admin_endpoint

        if len(tenant_id) <= 0:
            tenant = identity.list_tenants(keystone, "NATIVE")
        else:
            tenant = identity.get_tenant(keystone, tenant_id, "NATIVE")

        if tenant is None:
            return web.unauthorized()

        body = json.dumps(tenant, indent=4)
        web.header("Content-Type", "application/json")
        return body
Ejemplo n.º 41
0
 def GET(self):
     qdict = web.input()
     global rovals, srvals, ps, sd
     try:
         if sd['ipas'] != 1 and qdict['pw'] != base64.b64decode(sd['pwd']):
             raise web.unauthorized()
             return
     except KeyError:
         pass
     if not sd['en']: return  # check operation status
     sd['rsn'] = 0
     sd['bsy'] = 1
     rovals = json.loads(qdict['t'])
     rovals.pop()
     ps = []
     for i in range(sd['nst']):
         ps.append([0, 0])
     for i, t in enumerate(rovals):
         if t != 0:
             ps[i][0] = 98
             ps[i][1] = t
             rs[i][1] = time.time() + t
     thread.start_new_thread(self.run, ())
     raise web.seeother('/')
     return
Ejemplo n.º 42
0
 def POST(self):
     i = web.input()
     usr = da.user.login(i.email, i.password)
     if not usr:
         raise web.unauthorized()
     usr = {id: usr.id, secretkey: usr.secretkey}
     web.header('Content-Type', 'application/json')
     return json.dumps(usr)
Ejemplo n.º 43
0
 def GET(self, image_id):
     """GET
     """
     if not Logged().logged():
         return web.unauthorized()
     ImageDB().delete_image(image_id)
     # raise web.seeother('/' + str(image_id) + '/')
     raise web.seeother('/')
Ejemplo n.º 44
0
 def POST(self):
   signature = getSignature()
   if verifySignature(SECRET, signature, web.data()):
     repository = getRepoName(web.data())
     update_gitlab_mirror = "cd $s && ./update_mirror.sh %s" %(WORK_DIR, repository)
     out = commands.getoutput(update_gitlab_mirror)
     return out
   return web.unauthorized()
Ejemplo n.º 45
0
 def GET(self, image_id):
     """GET
     """
     if not Logged().logged():
         return web.unauthorized()
     ImageDB().delete_image(image_id)
     # raise web.seeother('/' + str(image_id) + '/')
     raise web.seeother('/')
Ejemplo n.º 46
0
 def DELETE(instance_name, version):
     auth = web.ctx.env.get('HTTP_AUTHORIZATION')
     username = ''  # We need to initialise these to empty values in the case that auth is disabled
     password = ''
     if auth is not None:
         try:
             auth = re.sub('^Basic ', '', auth)
             username, password = base64.decodestring(auth).split(':')
         except ValueError:
             return web.unauthorized()
     if not check_auth(username, password):
         return web.unauthorized()
     try:
         pleasance.delete_historic_version(instance_name, version)
         return 'Configuration ' + version + ' for ' + instance_name + ' deleted'
     except pleasance.EnvironmentNotFoundError:
         return web.notfound()
Ejemplo n.º 47
0
 def POST(self):
     i = web.input()
     usr = da.user.login(i.email,i.password)
     if not usr:
         raise web.unauthorized()
     usr = {id:usr.id, secretkey:usr.secretkey}
     web.header('Content-Type', 'application/json')
     return json.dumps(usr)
Ejemplo n.º 48
0
 def GET(self):
     web.header('Access-Control-Allow-Origin', '*')
     params = web.input()
     if 'user' not in params or 'pass' not in params:
         return web.badrequest()
     if random.choice([True, False]):
         return web.ok()
     else:
         return web.unauthorized()
Ejemplo n.º 49
0
 def POST(self):
     variables = web.input()
     if (variables.get('username') == configuration.web_user()) & (variables.get('password') == configuration.web_pwd()):
         user_session.login = 1
         print 'Logged in.'
         return web.ok()           
     else:
         user_session.login = 0
         return web.unauthorized()          
Ejemplo n.º 50
0
    def GET(self):
        qdict = web.input()
        remote = web.ctx.env['REMOTE_ADDR']
#        print 'slave iface remote: ' + remote + ' qdict: ' + str(qdict)
        if remote != '127.0.0.1':
            gv.logger.info('slave_iface invalid remote: ' + remote)
            raise web.unauthorized()

        gv.radio_iface = qdict['radio']
        gv.vpn_iface = qdict['vpn']
Ejemplo n.º 51
0
def _raise_if_locked(filepath):
    """Raise a 401 unauthorized it the filepath is locked, and the
       appropriate locked wasn't given in the request.
    """

    i = web.input()

    host, port = utils.get_host_port(_config['lockserver'])
    if utils.is_locked(filepath, host, port, i.get('lock_id', None)):
        raise web.unauthorized()
Ejemplo n.º 52
0
def _raise_if_locked(filepath):
    """Raise a 401 unauthorized it the filepath is locked, and the
       appropriate locked wasn't given in the request.
    """

    i = web.input()

    host, port = utils.get_host_port(_config['lockserver'])
    if utils.is_locked(filepath, host, port, i.get('lock_id', None)):
        raise web.unauthorized()
Ejemplo n.º 53
0
    def GET(self):
        qdict = web.input()
        remote = web.ctx.env['REMOTE_ADDR']
#        print 'slave iface remote: ' + remote + ' qdict: ' + str(qdict)
        if remote != '127.0.0.1':
            gv.logger.info('slave_iface invalid remote: ' + remote)
            raise web.unauthorized()

        gv.radio_iface = qdict['radio']
        gv.vpn_iface = qdict['vpn']
Ejemplo n.º 54
0
Archivo: ospi.py Proyecto: gazetaj/OSPi
def verifyLogin():
    qdict = web.input()

    if gv.sd['ipas'] == 1:
        return True
    if web.config._session.user == 'admin':
        return True
    if qdict.has_key('pw') and gv.sd['password'] == sha1(qdict['pw'] + gv.sd['salt']).hexdigest():
        return True

    raise web.unauthorized()
Ejemplo n.º 55
0
def verifyLogin():
    qdict = web.input()

    if gv.sd['ipas'] == 1:
        return True
    if web.config._session.user == 'admin':
        return True
    if qdict.has_key('pw') and gv.sd['password'] == sha1(qdict['pw'] + gv.sd['salt']).hexdigest():
        return True

    raise web.unauthorized()
Ejemplo n.º 56
0
def validate_two_leg_oauth():
    """
  Verify 2-legged oauth request using values in "Authorization" header.
  """
    log.loggit('validate_two_leg_oauth()')
    parameters = web.input()
    if web.ctx.env.has_key('HTTP_AUTHORIZATION') and web.ctx.env[
            'HTTP_AUTHORIZATION'].startswith('OAuth '):
        parameters = split_header(web.ctx.env['HTTP_AUTHORIZATION'])

    # We have to reconstruct the original full URL used when signing
    # so if there are ever 401 errors verifying a request, look here first.
    req = oauth2.Request(web.ctx.env['REQUEST_METHOD'],
                         web.ctx['homedomain'] + web.ctx.env['REQUEST_URI'],
                         parameters=parameters)

    if not req.has_key('oauth_consumer_key'):
        raise web.unauthorized()

    # Verify the account referenced in the request is valid
    adb = accountdb.AccountDB()
    account = adb.review_account_using_info('consumer_key',
                                            req['oauth_consumer_key'])
    if not account:
        raise web.unauthorized(UNAUTHORIZED_MESSAGE)

    # Create an oauth2 Consumer with an account's consumer_key and consumer_secret
    # to be used to verify the request
    consumer = oauth2.Consumer(account['consumer_key'],
                               account['consumer_secret'])

    # Create our oauth2 Server and add hmac-sha1 signature method
    server = oauth2.Server()
    server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())

    # Attempt to verify the authorization request via oauth2
    try:
        server.verify_request(req, consumer, None)
    except oauth2.Error, e:
        log.loggit('validate_two_leg_oauth() - %s %s' % (repr(e), str(e)))
        raise web.unauthorized(e)
Ejemplo n.º 57
0
 def PUT(installer_name, target_os):
     auth = web.ctx.env.get('HTTP_AUTHORIZATION')
     username = ''  # We need to initialise these to empty values in the case that auth is disabled
     password = ''
     try:
         if auth is not None:
             auth = re.sub('^Basic ', '', auth)
             username, password = base64.decodestring(auth).split(':')
     except ValueError:
         return web.unauthorized()
     if not check_auth(username, password):
         return web.unauthorized()
     content_type = ''
     if web.ctx.env.get('CONTENT_TYPE'):
         content_type = web.ctx.env.get('CONTENT_TYPE')
     try:
         if pleasance.update_installer_specific(installer_name, target_os,
                                                content_type, web.data()):
             return "Created Installer for " + installer_name + " on platform: " + target_os
     except pleasance.InstallerNotFoundError:
         return web.notfound()
Ejemplo n.º 58
0
 def PATCH(self):
     web.header('Access-Control-Allow-Origin', '*')
     web.header('Access-Control-Allow-Credentials', 'true')
     web.header('Content-Type', 'application/json')
     input = json.loads(web.data())
     res = patch_graph(input["user"], input["graph"], input["data"])
     if res == 200:
         return json.dumps({"ok": True}, default=_jsonforammter)
     elif res == 401:
         raise web.unauthorized()
     else:
         raise web.internalerror()