Exemple #1
0
 def POST(self):
     if session.get('token') is not None:
         data = web.input()
         print("name = {0} path = {1}".format(data.get('file'),
                                              data.get('dir')))
         path = "{0}{1}".format(data.get("dir"), data.get('file'))
         long_path = "repositories/{0}/{1}{2}{3}".format(
             session.get('userName'), session.repository, data.get("dir"),
             data.get('file'))
         print("path = {0}".format(path))
         print("long_path = {0}".format(long_path))
         path = re.sub(r'^\/', '', path)
         print("path = {0}".format(path))
         try:
             open(long_path, "a").close()
         except:
             raise web.Unauthorized()
         result = subprocess.check_output(
             "cd repositories/{0}/{1} && git add {2} || exit 0".format(
                 session.userName, session.repository, path),
             shell=True,
             stderr=subprocess.STDOUT)
         print result
         session.openFile = path
         return ''
    def GET(self, userID):
        web.header('Content-Type', 'application/JSON')

        if not web.ctx.environ.has_key(
                'HTTP_AUTHORIZATION'
        ) or not web.ctx.environ['HTTP_AUTHORIZATION'].startswith('Basic '):
            return web.Unauthorized()
        else:
            hash = web.ctx.environ['HTTP_AUTHORIZATION'][6:]
            remoteUser, remotePasswd = base64.b64decode(hash).split(':')

        admiralUser = userID
        accesspath = "/usr/local/sbin/admiraluserinfo.sh" + " " + remoteUser + " " + admiralUser
        logger.debug("accesspath = " + repr(accesspath))
        cmdOutput = subprocess.Popen(accesspath,
                                     shell=True,
                                     stdout=subprocess.PIPE)
        cmdOutputString = cmdOutput.stdout.read()
        cmdOutputString = cmdOutputString.strip()
        #print "Status: 303 ADMIRAL SERVER ERROR"

        if cmdOutputString.find("ADMIRAL SERVER ERROR") == -1:
            # Convert the retrieved column of users to a list to enable easy conversion to json
            cmdOutputList = []
            #cmdOutputList = cmdOutputString.split("\n")
            cmdOutputString = '{"' + cmdOutputString + '"}'
            cmdOutputString = cmdOutputString.replace("\n", '","')
            cmdOutputString = cmdOutputString.replace(":", '":"')
            logger.debug("cmdOutputList = " + repr(cmdOutputList))
            return json.dumps(ast.literal_eval(cmdOutputString))
        else:
            returnString = '{"redirect":"' + cmdOutputString + '"}'
            return returnString
Exemple #3
0
 def POST(self):
     data = web.input()
     auth = GitHub().authorize(data['username'], data['password'])
     if auth is not None:
         raise web.seeother('/')
     else:
         raise web.Unauthorized()
    def GET(self):
        web.header('Content-Type', 'application/JSON')

        if not web.ctx.environ.has_key(
                'HTTP_AUTHORIZATION'
        ) or not web.ctx.environ['HTTP_AUTHORIZATION'].startswith('Basic '):
            return web.Unauthorized()
        else:
            hash = web.ctx.environ['HTTP_AUTHORIZATION'][6:]
            remoteUser, remotPasswd = base64.b64decode(hash).split(':')

        logger.debug("Remote user = "******"/usr/local/sbin/listAdmiralUsers.sh" + " " + remoteUser
        logger.debug("accesspath = " + repr(accesspath))
        cmdOutput = subprocess.Popen(accesspath,
                                     shell=True,
                                     stdout=subprocess.PIPE)
        cmdOutputString = cmdOutput.stdout.read()

        # Convert the retrieved column of users to a list to enable easy conversion to json
        cmdOutputList = []
        cmdOutputString = cmdOutputString.strip()
        cmdOutputString = cmdOutputString.replace("\n", ",")
        cmdOutputList = cmdOutputString.split(",")
        logger.debug("cmdOutputList = " + repr(cmdOutputList))
        web.ok
        return json.dumps(cmdOutputList, sort_keys=True)
Exemple #5
0
    def POST(self):
        try:
            tid_value = web.input()['tid']
        except KeyError:
            return web.BadRequest()

        try:
            team_id = cfg['TEAM_ID_DICT'][tid_value.upper()]
        except KeyError:
            return web.Unauthorized()

        if len(web.data()) == 0:
            return web.BadRequest()

        data = simplejson.loads(web.data())
        # json validation
        good, errors = IssueValidator().validate(data)
        if not good:
            return errors

        r = requests.post(''.join(['http://', cfg['REMOTE_HOST'], '/pp']), data=simplejson.dumps({'tid': str(team_id), 'iid': data['ID']}))
        if r.status_code != 200:
            print 'Call remote server failed...'
            print r.text

        api = WxApi(cfg['CORP_ID'], cfg['SECRET'])
        api.send_text(self.build_msg(data), team_id, 0, '@all')

        return web.OK('ok')
Exemple #6
0
    def GET(self):
        user_data = web.input(auth_code='')
        if user_data.auth_code.upper() not in AUTH_CODE.keys():
            raise web.Unauthorized('Unauthorized visit.')

        url_scheme = web.ctx.environ['wsgi.url_scheme']
        param = get_param(user_data)
        raise web.redirect(get_redirect_loc('%s://%s/wx/cate2_init?%s&td_channelid=%s' % \
            (url_scheme, setting.wx_host, param, user_data.auth_code.upper())))
Exemple #7
0
    def GET(self):
        input_parameters = web.input()

        if len(input_parameters) == 0:
            return web.Unauthorized()

        echo = WxApp()
        echo_str = echo.process(input_parameters, xml=None)
        return echo_str
Exemple #8
0
    def POST(self):
        input_parameters = web.input()
        input_data = web.data()

        if len(input_parameters) == 0 or len(input_data) == 0:
            return web.Unauthorized()

        wx_callback = WxApp()
        return wx_callback.process(input_parameters, input_data)
Exemple #9
0
 def DELETE(package_name, package_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 = ''
     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()
     try:
         if pleasance.delete_package_version(package_name, package_version):
             return package_name + " version " + package_version + " has been deleted.\n"
         else:
             return web.forbidden()
     except pleasance.PackageNotFoundError:
         return web.notfound()
Exemple #10
0
 def execute(self):
     try:
         dict = {"data": web.data(), "headers": {"Content-Type": web.ctx.env.get('CONTENT_TYPE')}, "type": self.type}
         AirwatchHandler(dict).handle()
         monitorutils.count_task("notificationrestservice", True)
         return web.OK()
     except AuthenticationFailureException, e:
         logger.error('Notification REST Service - %s' % e)
         monitorutils.count_task("notificationrestservice", False)
         raise web.Unauthorized()
Exemple #11
0
 def DELETE(context):
     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()
     if context.lstrip('/').split('/').__len__() > 1:
         return web.badrequest(context + " " +
                               str(context.lstrip('/').split('/')) +
                               " greater than 1")
     else:
         try:
             if pleasance.delete_bootstrap(context):
                 return "Deleted Bootstrap " + context
         except pleasance.BootStrapNotFoundError:
             return web.notfound()
    def POST(self, UserID):
        web.header('Content-Type', 'application/JSON')
        print "Web.data() = " + web.data()
        #jsonInputData = json.loads(web.data())
        jsonInputData = urlparse.parse_qs(web.data().replace('\n', "").replace(
            '\r', ""),
                                          keep_blank_values=True)
        print "jsonInputData = " + repr(jsonInputData)
        #print "PUT : "  + jsonInputData
        UserID = jsonInputData["UserID"]
        FullName = jsonInputData["UserFullName"]
        Role = jsonInputData["UserRole"]
        RoomNumber = jsonInputData["UserRoomNumber"]
        WorkPhone = jsonInputData["UserWorkPhone"]
        Password = jsonInputData["UserPassword"]
        Operation = jsonInputData["UserOperation"]

        if not web.ctx.environ.has_key(
                'HTTP_AUTHORIZATION'
        ) or not web.ctx.environ['HTTP_AUTHORIZATION'].startswith('Basic '):
            return web.Unauthorized()
        else:
            hash = web.ctx.environ['HTTP_AUTHORIZATION'][6:]
            remoteUser, remotPasswd = base64.b64decode(hash).split(':')

        admiralUser = UserID
        print "USAGE: admiralupdateuserinfo.sh  RemoteUserID UserID [FullName] [Role] [Room Number] [Work phone] [Password]"
        commandString = "/usr/local/sbin/admiraladdnewuser.sh" + " " + "'" + remoteUser + "'" + " " + "'" + admiralUser + "'" + " " + "'" + FullName + "'" + " " + "'" + Role + "'" + " " + "'" + RoomNumber + "'" + " " + "'" + WorkPhone + "'" + " " + "'" + Password + "'"
        print commandString
        logger.debug("commandString = " + repr(commandString))
        cmdOutput = subprocess.Popen(commandString,
                                     shell=True,
                                     stdout=subprocess.PIPE)
        cmdOutputString = cmdOutput.stdout.read()
        cmdOutputString = cmdOutputString.strip()

        if cmdOutputString.find("ADMIRAL SERVER ERROR") == -1:
            #cmdOutputList = []
            #cmdOutputList = cmdOutputString.split("\n")
            #cmdOutputString = '{"' + cmdOutputString + '"}'
            #cmdOutputString = cmdOutputString.replace("\n", '","')
            #cmdOutputString = cmdOutputString.replace(":", '":"')
            #logger.debug("cmdOutputList = " + repr(cmdOutputList))
            #return json.dumps(ast.literal_eval(cmdOutputString))

            return json.dumps({"Update": "Successful"})
        else:
            returnString = '{"redirect":"' + cmdOutputString + '"}'
            return returnString
Exemple #13
0
 def PUT(instance_name, node_identifier):
     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:
         auth = re.sub('^Basic ', '', auth)
         username, password = base64.decodestring(auth).split(':')
     if not check_auth(username, password):
         return web.Unauthorized()
     try:
         if pleasance.create_node_configuration(
                 instance_name, node_identifier,
                 web.ctx.env.get('CONTENT_TYPE'), web.data()):
             return "Updated node Configuration for " + node_identifier + " in " + instance_name
     except pleasance.EnvironmentNotFoundError:
         return web.notfound()
     except pleasance.ConfigurationNotValidJSONError:
         return web.badrequest('Could not parse the JSON supplied')
Exemple #14
0
    def POST(self):
        try:
            tid_value = web.input()['tid']
        except KeyError:
            return web.BadRequest()

        try:
            team_id = cfg['TEAM_ID_DICT'][tid_value.upper()]
        except KeyError:
            return web.Unauthorized()

        if len(web.data()) == 0:
            return web.BadRequest()

        api = WxApi(cfg['CORP_ID'], cfg['SECRET'])
        api.send_text(web.data(), team_id, 0, '@all')

        return web.OK('ok')
Exemple #15
0
 def PUT(instance_name):
     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:
         if pleasance.update_configuration(instance_name,
                                           web.ctx.env.get('CONTENT_TYPE'),
                                           web.data(), username):
             return "Updated Environment " + instance_name
     except pleasance.ConfigurationNotJSONError:
         return web.webapi.UnsupportedMediaType()
     except pleasance.ConfigurationNotValidJSONError:
         return web.badrequest('Could not parse the JSON supplied')
Exemple #16
0
def common_setup():
    web.header('Server', "%s/%s" % (version.APP_NAME, version.VERSION))
    # for quick shutdown
    web.header('Connection', "Close")
    global controller
    if controller.settings.auth_enabled:
        auth = web.ctx.env.get('HTTP_AUTHORIZATION')
        authreq = False
        if auth is None:
            authreq = True
        else:
            auth = re.sub('^Basic ', '', auth)
            username, password = base64.decodestring(auth).split(':')
            if username == controller.settings.auth_username and hash_password(password) == controller.settings.auth_password:
                return
            else:
                authreq = True
        if authreq:
            web.header('WWW-Authenticate', 'Basic realm="PyWebGet"')
            web.ctx.status = '401 Unauthorized'
            raise web.Unauthorized()
Exemple #17
0
def view(consumer_id, repo_id, module_name, version=None):
    """
    produces data for the "releases.json" view

    :param consumer_id: unique ID for a consumer
    :type  consumer_id: str
    :param repo_id:     unique ID for a repo
    :type  repo_id:     str
    :param module_name: name of a module in form "author/title"
    :type  module_name: str
    :param version:     optional version
    :type  version:     str

    :return:    data structure defining dependency data for the given module and
                its download path, identical to what the puppet forge v1 API
                generates, except this structure is not yet JSON serialized
    :rtype:     dict
    """
    if repo_id == constants.FORGE_NULL_AUTH_VALUE:
        if consumer_id == constants.FORGE_NULL_AUTH_VALUE:
            # must provide either consumer ID or repo ID
            raise web.Unauthorized()
        repo_ids = get_bound_repos(consumer_id)
    else:
        repo_ids = [repo_id]
    if version:
        unit = find_version(repo_ids, module_name, version)
    else:
        unit = find_newest(repo_ids, module_name)
    if not unit:
        raise web.NotFound()
    try:
        data = unit.build_dep_metadata()
    finally:
        unit.db.close()
    return data
Exemple #18
0
    def generate_http_response(self,
                               status_code,
                               data=None,
                               exc_cls=None,
                               exc_msg=None):

        if status_code == HTTP_STATUS_CODE.OK:
            if data:
                raise web.OK(data=json.dumps(data), headers={})
            else:
                raise web.OK()
        elif status_code == HTTP_STATUS_CODE.Created:
            raise web.Created()
        elif status_code == HTTP_STATUS_CODE.Accepted:
            raise web.Accepted()
        elif status_code == HTTP_STATUS_CODE.BadRequest:
            raise web.BadRequest(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Unauthorized:
            raise web.Unauthorized(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Forbidden:
            raise web.Forbidden(
                message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.NotFound:
            raise web.NotFound(message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.Conflict:
            raise web.Conflict(message=self.generate_message(exc_cls, exc_msg))
        elif status_code == HTTP_STATUS_CODE.InternalError:
            raise web.InternalError(
                message=self.generate_message(exc_cls, exc_msg))
        else:
            if data:
                raise web.HTTPError(status_code, data=json.dumps(data))
            else:
                raise web.HTTPError(status_code)
Exemple #19
0
    def GET(self, file=None):
        # Static files (style sheets, index.html)
        if file:
            if not os.path.exists(file):
                raise web.NotFound()
            elif not os.access(file, os.R_OK):
                raise web.Unauthorized()
            else:
                #print "have file", file
                f = open(UIDIR + '/' + file, 'r')
                return f.read()

        cwd = os.getcwd()

        # GET MEDIA FILE LIST
        os.chdir(MEDIADIR)
        mediafiles = [f[2:] for f in get_filepaths(".", MEDIATYPES)]
        mediafiles.sort()
        os.chdir(cwd)
        # multiple file select for delete file select box:
        mediafilesdelete = make_select_list("delete", mediafiles, None, True)
        mediafilestest = make_select_list("test", mediafiles, None, False)

        # which is current:
        mediacurrent = open(MEDIACONTROLFILE, 'r').read().split()[0]
        if len(mediacurrent) > 1 and mediacurrent not in mediafiles:
            mediacurrent = mediafiles[0]
        mediafilescontrol = make_control_list(mediafiles, mediacurrent)
        # set next and previous
        i = mediafiles.index(mediacurrent)
        mediaprevious = mediafiles[(i - 1) % len(mediafiles)]
        medianext = mediafiles[(i + 1) % len(mediafiles)]

        clientip = web.ctx.env['REMOTE_ADDR']
        serverip = web.ctx.env['HTTP_HOST']

        web.header('Cache-control', 'no-cache, no-store, must-revalidate')
        web.header('Pragma', 'no-cache')
        #web.header('Expires', '0')
        #web.header('Cache-Control', 'post-check=0, pre-check=0', False)
        return """<html><head><title>model: %s</title><meta charset="utf-8">
        <link rel="stylesheet" href="/style.css">
        </head>
        <body>
        <script>
        function http_get(theUrl)
            {
                console.log('get: '+theUrl);
                var xmlHttp = null;
                try {
                        xmlHttp = new XMLHttpRequest();
                        xmlHttp.open( "GET", theUrl, false );
                        xmlHttp.send( null );
                    }
                catch(err) {
                    console.log(err);
                    return null;
                }
                document.getElementById('debug').innerText = 'response: '+xmlHttp.responseText;
                //return JSON.parse(xmlHttp.responseText);
            }
        function media_play(file) {
            //var brightness=parseInt(document.getElementById('brightness').value)
            brightness=localStorage.brightness
            http_get("/media_play?file="+file+"&brightness="+brightness);
            window.location.reload(); // pretty cheap
        }
        function hr_set(offset=0) {
            var hr=parseInt(document.getElementById('hr').value)
            if (offset < 0 || offset > 0) {
                hr += offset
                document.getElementById('hr').value = hr
            }
            http_get('/hr?do=set&hr='+hr+'&brightness='+localStorage.brightness)
        }
        window.onload = function (e) {
            console.log("localStorage", localStorage)
            if (localStorage.brightness) {
                document.getElementById('brightness').value=localStorage.brightness
            }
        }
        </script>

        <style>
        /** { font-size: 10pt; font-family: sans-serif, sans; }*/
        _input, _button, select { font-size: 0.8em; margin: 0px; padding: 0px; }
        select { max-width:300px; background-color: white; border: solid 1px #ccc; border-radius: 0; padding: 0 4; margin: 1 0; outline:0px;
                 -webkit-appearance: none; -moz-appearance: none; appearance: none; }
        #debug {opacity: 0.3;}
        td { padding: 8px 28px; }
        a { text-decoration: none; color: inherit}
        .media_selected { font-weight: bold }
        .media_selected::after { content: ' <-' }
        h2 { text-decoration: underline;}
        button { margin: 2px 3px; font-size: 1.1em;}
        </style>
        <center>Model: %s<br>
        </center>
        <table>

        <td valign=top bgcolor="#eee">
            <h2>Upload Media</h2>
            <form method="POST" enctype="multipart/form-data" action="/upload">
            <input type="file" name="newfile" /><br>
            <input type="submit" value="Upload"/>
            </form>
            <h2>Delete</h2>
            <form method="POST" action="/upload">
            %s
            <br><input type="submit" value="Delete"/>
            </form>

        </td>

        <td valign=top>
            <h2>Control Display</h2>
            <input type=text size=4 id=brightness value=%s onchange='javascript:localStorage.brightness=document.getElementById("brightness").value'> brightness<br>
            <h3>Counter</h3>
            <!-- stop: &#9724; pause: &#9646;&#9646; play: &#9654; record: &#9679; -->
            <button onclick="javascript:http_get('/counter?do=play&brightness='+localStorage.brightness)" class=play>&#9654;</button>
            <button onclick="javascript:http_get('/counter?do=pause')" class=pause>&#9646;&#9646;</button>
            <button onclick="javascript:http_get('/counter?do=stop')" class=pause>&#9724;</button><br>
            <h3>Set Pulse</h3>
            <button onclick="javascript:http_get('/hr?do=start&brightness='+localStorage.brightness)">&#9654;</button>
            <button onclick="javascript:http_get('/hr?do=stop')">&#9724;</button><br>
            <button onclick="javascript:hr_set(1)">+</button><button onclick="javascript:hr_set(-1)">-</button>
<input type=text size=4 id=hr value=60><button onclick="javascript:hr_set()">set</button><br>
            <h3>Media Show</h3>
            <button onclick="javascript:media_play('%s')">&lt;&lt;</button>
            <button onclick="javascript:media_play('%s')">&gt;&gt;</button><br><br>
            <div id=medialist>
            %s
            </div>
        </td>

        </table>
        <br><hr>

        <button onclick="javascript:http_get('/osctest')">osc test</button>
        <button onclick="javascript:http_get('/displaytest')">display test</button>
        <br>
        </center><pre id=debug></pre>
        </body>
        </html>
        """ % (
            MODEL_NAME,
            MODEL_NAME,
            mediafilesdelete,
            BRIGHTNESS,
            mediaprevious,
            medianext,
            mediafilescontrol,
        )  #"<br>\n".join(soundfiles))
    def POST(self):
        print "POST in AdminUIFormHandler"
        reqdata = web.data()
        print "Request POST data obtained from the client before redirection" + reqdata
        jsonInputData = json.loads(reqdata)
        print "JSON INPUT DATA =" + repr(jsonInputData)

        UserID = jsonInputData["UserID"]
        print "UserID= " + UserID
        # FullName   =  jsonInputData["UserFullName"]
        # Role       =  jsonInputData["UserRole"]
        RoomNumber = jsonInputData["UserRoomNumber"]
        print "Room Number: " + RoomNumber
        # WorkPhone  =  jsonInputData["UserWorkPhone"]
        # Password   =  jsonInputData["UserPassword"]
        Operation = jsonInputData["UserOperation"]
        print "Operation = " + Operation

        if Operation == "Modify":
            method = "PUT"
            url = '/user/' + UserID
        elif Operation == "Add":
            method = "POST"
            url = '/users/' + UserID
        elif Operation == "Delete":
            method = "DELETE"
            url = '/user/' + UserID

        endpointhost = "localhost"
        basepath = '/user/' + UserID
        responsedata = ""

        if not web.ctx.environ.has_key(
                'HTTP_AUTHORIZATION'
        ) or not web.ctx.environ['HTTP_AUTHORIZATION'].startswith('Basic '):
            return web.Unauthorized()
        else:
            hash = web.ctx.environ['HTTP_AUTHORIZATION'][6:]
            remoteUser, remotePasswd = base64.b64decode(hash).split(':')

        auth = base64.encodestring("%s:%s" % (remoteUser, remotePasswd))
        headers = {"Authorization": "Basic %s" % auth}
        data = reqdata  #jsonInputData
        #data = web.http.urlencode(jsonInputData)
        print "URL encoded data before sending=" + repr(data)
        try:
            session = HttpSession.makeHttpSession(endpointhost, basepath,
                                                  remoteUser, remotePasswd)
            # encodeddata = session.encode_multipart_formdata(jsonInputData)
            # (responsetype, responsedata)=session.doHTTP_PUT( resource='/user/'+UserID,data=None, data_type='application/JSON', expect_status=200, expect_reason="OK")
            # (responsetype, responsedata)=session.doHTTP_GET( resource='/users', expect_status=200, expect_reason="OK")
            connection = httplib.HTTPConnection('localhost', timeout=30)
            connection.request(method, url, body=data, headers=headers)
            # connection.endheaders()
            # connection.send(jsonInputData)
            response = connection.getresponse()
            responsedata = response.read()
        # connection.close()
        # req = urllib2.Request(url, data)
        # response = urllib2.urlopen(req)
        # responsedata = response.read()
        except session.HTTPSessionError, e:
            #AdminUIHandlerUtils.printHTMLHeaders()
            # AdminUIHandlerUtils.generateErrorResponsePage(AdminUIHandlerUtils.HTTP_ERROR,e.code, e.reason)
            # AdminUIHandlerUtils.printStackTrace()
            returnString = '{"redirect":"' + e.code + "-" + e.reason + '"}'
            print returnString
            return returnString
Exemple #21
0
def view(consumer_id, repo_id, module_name, version=None, recurse_deps=True,
         view_all_matching=False):
    """
    produces data for the "releases.json" view

    :param consumer_id: unique ID for a consumer
    :type  consumer_id: str
    :param repo_id:     unique ID for a repo
    :type  repo_id:     str
    :param module_name: name of a module in form "author/title"
    :type  module_name: str
    :param version:     optional version
    :type  version:     str
    :param recurse_deps: Whether or not a module should have it's full dependency chain
                         recursively added to it's own
    :type recurse_deps: bool
    :param view_all_matching: whether or not all matching modules should be returned or just
                              just the first one
    :type view_all_matching: bool

    :return:    data structure defining dependency data for the given module and
                its download path, identical to what the puppet forge v1 API
                generates, except this structure is not yet JSON serialized
    :rtype:     dict
    """
    # Build the list of repositories that should be queried
    if repo_id == constants.FORGE_NULL_AUTH_VALUE:
        if consumer_id == constants.FORGE_NULL_AUTH_VALUE:
            # must provide either consumer ID or repo ID
            raise web.Unauthorized()
        repo_ids = get_bound_repos(consumer_id)
    else:
        repo_ids = [repo_id]

    dbs = None
    return_data = None
    try:
        # Get the list of database files to query
        dbs = get_repo_data(repo_ids)

        # Build list of units to return
        ret = []
        # If a version was specified filter by that specific version of the module
        if version:
            for unit in unit_generator(dbs, module_name):
                if unit.version == version:
                    ret.append(unit)
                    break
        else:
            units = list(unit_generator(dbs, module_name))
            # if view_all_matching then return all modules matching the query, otherwise
            # only return the first matching module (for forge v1 & v2 api compliance)
            if view_all_matching:
                ret = units
            else:
                if units:
                    ret.append(max(units))

        # calculate dependencies for the units being returned & build the return structure
        return_data = {}
        for unit in ret:
            populated_unit = unit.build_dep_metadata(recurse_deps)
            for unit_name, unit_details in populated_unit.iteritems():
                return_data.setdefault(unit_name, []).extend(unit_details)

        if not return_data:
            raise web.NotFound()

    finally:
        # Close all the database files. If closing one raises an error we still need to
        # close the others so that file handles aren't left open.
        if dbs:
            error_raised = None
            for repo_id, dbs_data in dbs.iteritems():
                try:
                    dbs_data['db'].close()
                except Exception, e:
                    error_raised = e

            if error_raised:
                raise error_raised
Exemple #22
0
def init_job(code, need_more_data=False, parent=None, auth_code=''):
    print '----> MIGIC CODE:', code
    if code == '':
        #return render.info('参数错误',goto='/') # info页面要做微信端优化
        #raise web.seeother('/wx/init_fair')
        if need_more_data:
            return None, None, 0, 0
        else:
            return None

    if len(code) < 20:  # 小于20说明是自定义code,如果不在列表里,则拒绝 2020-04-09
        if code in CODE_MIGIC.keys():  # 用于非微信环境进入
            openid = code
        else:
            raise web.Unauthorized(
                'Unauthorized visit.')  # 这应该会显示 not found   2020-04-09
    else:
        urllib3.disable_warnings()
        http = urllib3.PoolManager(num_pools=2, timeout=180, retries=False)
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' \
            'appid=%s&' \
            'secret=%s&' \
            'code=%s&' \
            'grant_type=authorization_code' % \
            (wx_appid, wx_secret, code, )
        r = http.request('GET', url)
        if r.status == 200:
            data = r.data
            t = json.loads(data)
            #print t

            http.clear()

            if t.has_key('openid'):
                openid = t['openid']
            else:
                #print '===========Error==============', data, wx_secret, wx_appid
                if need_more_data:
                    return None, None, 0, 0
                else:
                    return None
        else:
            http.clear()

            if need_more_data:
                return None, None, 0, 0
            else:
                return None

    # 取得ticket
    ticket = get_ticket()
    if ticket == '':
        print 'get ticket fail!'
        #raise web.seeother('/wx/init_fair')
        #return None
        ticket = get_ticket(True)

    uname = ''

    # 检查用户是否已注册
    #db_user = db.app_user .find_one({'openid':openid})
    db_user = app_user_helper.get_user_info(openid, q_type='openid')
    is_new_user = 0
    is_our_fan = True
    if db_user == None:
        # 未注册,新建用户记录
        is_new_user = 1
        # 用户基本信息
        info = get_info(openid)
        if info.has_key('errcode'):
            get_ticket(True)
            info = get_info(openid)
        print info

        unionid = info.get('unionid', '')

        coupon = []

        new_set = {
            'openid': openid,
            'unionid': unionid,
            'region_id': setting.region_id,  # 增加 region_id
            'type': 'wx_pub',  # 用户类型
            'address': [],
            'coupon': coupon,  # 送优惠券
            'app_id': '',  # 微信先注册,没有app_id
            'reg_time': app_helper.time_str(),
            'wx_nickname': info.get('nickname', '游客'),
            'wx_headimgurl': info.get('headimgurl', ''),
            'wx_info': info,
            'refresh_headimg': REFRESH_HEADIMG,
            'last_status': int(time.time()),
            'app_order_num': 0  # 20160927 lf 未下单
        }
        # 用户中心注册用户接口
        app_user_helper.new_user_info(openid, 'openid', new_set)

        is_our_fan = not (info.get('nickname', u'游客') == u'游客'
                          )  # 是否是公众号粉丝,通过是否是游客判断

        # 添加用户关系 2016-03-31
        # 只有新注册用户添加
        if parent not in [None, '']:
            from libs import user_tree
            parent_u = user_tree.owner2unionid(parent)
            if parent_u != None and unionid != parent_u:
                user_tree.add_parent(unionid, parent_u)
                print '======> TREE:', unionid, parent_u

    else:
        # 记录今天访问次数
        last_date = db_user.get('last_visit_date')
        today_date = app_helper.time_str(format=1)  # 格式 2016-01-01
        if last_date != today_date:
            update_set = {
                'last_visit_date': today_date,
                'today_visit_count': 1,
                'todat_visit_first_tick': int(time.time()),
                'todat_push_image_text': 0,
            }
        else:
            update_set = {
                'today_visit_count': db_user.get('today_visit_count', 0) + 1,
            }

        # 更新 region_id
        if db_user.get('region_id') != setting.region_id:
            update_set['region_id'] = setting.region_id

        if not openid_is_fun(openid) \
            or db_user.get('wx_nickname', '')=='' \
            or db_user.get('refresh_headimg',0)<=0: # 没有关注

            # 用户基本信息
            info = get_info(openid)
            if info.has_key('errcode'):
                get_ticket(True)
                info = get_info(openid)
            print info

            unionid = info.get('unionid', '')

            # 补充微信用户信息

            update_set['unionid'] = unionid
            update_set['wx_nickname'] = info.get('nickname', '游客')
            update_set['wx_headimgurl'] = info.get('headimgurl', '')
            update_set['wx_info'] = info
            update_set['refresh_headimg'] = REFRESH_HEADIMG

            #db.app_user .update_one({'openid':openid}, {'$set': update_set})
            app_user_helper.update_user_info(openid,
                                             q_type='openid',
                                             update_set=update_set)
            is_our_fan = not (info.get('nickname', u'游客') == u'游客')
        else:
            unionid = db_user.get('unionid', '')
            is_our_fan = True
            # 刷新refresh_headimg
            db.app_user.update_one({'openid': openid}, {
                '$set': update_set,
                '$inc': {
                    'refresh_headimg': -1
                }
            })

        uname = db_user.get('uname', '')

    # 生成 session ------------------

    rand2 = app_helper.my_rand(16)
    now = time.time()
    secret_key = 'f6102bff8451236b8ca1'
    session_id = hashlib.sha1(
        "%s%s%s%s" % (rand2, now, web.ctx.ip.encode('utf-8'), secret_key))
    session_id = session_id.hexdigest()

    db.app_sessions.insert_one({
        'session_id': session_id,
        'openid': openid,
        'unionid': unionid,
        'ticket': ticket,
        'uname': uname,
        'login': 1,
        'rand': rand2,
        'ip': web.ctx.ip,
        'attime': now,
        'type': 'wx',
        'auth_code': auth_code,  # 20190516 记录来源
    })

    print "session >>>>>>>>>> ", session_id, openid, uname, auth_code
    if need_more_data:  # 返回是否是粉丝
        return session_id, is_our_fan, is_new_user, openid
    else:
        return session_id