Exemple #1
0
def api_nexus_message_update(request):
    # TODO
    # add signed API call to request a nonce
    # and then in this call, check for nonce and for nonce time < 2 hours
    session = DBSession()

    if ("message" not in request.params):
        return {"error": _("No 'message' parameter found")}
    else:
        message = simplejson.loads(request.params["message"], encoding="utf-8")

        # Get the nonce
        try:
            nonce = message["message_nonce"]
        except KeyError:
            return {"error": "You think you can get in without following the rules?  No cookie for you!"}

        # Check the nonce
        if (not ConsumerNonce.checkNonce(nonce)):
            return {"error": "Nonce not correct."}
        
        # Get the consumer key
        consumer = ConsumerKeySecret.getByConsumerKey(message["message_key"])
        if ("message_title" not in message):
            return {"error": _("No 'message_title' found in POSTed message.")}
        elif ("message_content" not in message):
            return {"error": _("No 'message_content' found in POSTed message.")}
        elif ("message_hash" not in message):
            return {"error": _("No 'message_hash' found in POSTed message.")}
        elif ("message_time" not in message):
            return {"error": _("No 'message_time' found in POSTed message.")}
        elif ("message_type" not in message):
            return {"error": _("No 'message_type' found in POSTed message.")}

        computed_hash = hashlib.sha256(unicode(message["message_title"]).encode("utf-8") + unicode(message["message_content"]).encode("utf-8")).hexdigest()

        if (computed_hash != message["message_hash"]):
            return {"error": _("The computed hash (%s) does not match the hash sent with the POST (%s)." % (computed_hash, message["message_hash"]))}

        if (NexusMessage.getByMessageHash(computed_hash)):
            return {"error": "The message with hash '%s' already exists in the Nexus" % message["message_hash"]}


        m = NexusMessage()
        m.title = message["message_title"]

        # Strip any potential HTML tags in the content
        m.content = re.sub(r'<[^>]*?>', '', message["message_content"]) 
        m.message_hash = message["message_hash"]
        m.message_type = message["message_type"]
        m.created_time = message["message_time"]
        m.priority = message["message_priority"]

        if (request.params.has_key("message_attachment")):
            attachment = request.params.get("message_attachment")

            if not hasattr(attachment, 'file'):
                raise TypeError("Not a valid file field")

            attachmentsDir = request.registry.settings["attachments.data_dir"]

            #attachmentDataBase64 = message["message_attachment"]
            #attachmentData = base64.b64decode(attachmentDataBase64)
            message_attachment_path = os.path.join(attachmentsDir, message["message_hash"])
            attachment_original_filename = message["message_attachment_original_filename"]

            fullPath, extension = os.path.splitext(attachment_original_filename)
            fp = open(message_attachment_path + extension, "wb")
            while True:
                data = attachment.file.read(8192)
                if not data:
                    break

                fp.write(data)
            fp.close()

            # Resize if an image
            if (m.message_type == 2):
                size = 200, 200
                try:
                    # Probably needs some validation here...
                    im = Image.open(message_attachment_path + extension)
                    im.thumbnail(size)
                    im.save(message_attachment_path + "_tn" + extension)
                except IOError, e:
                    pass

            m.attachment_original_filename = attachment_original_filename
            m.attachment_path = message_attachment_path
        else:
Exemple #2
0
def api_request_token(request):
    session = DBSession()
    auth_header = {}
    matchdict = request.matchdict
    appType = matchdict.get("appType", False)

    if ('Authorization' in request.headers):
        auth_header = {'Authorization': request.headers['Authorization']}
    
    req = oauth2.Request.from_request(
        request.method,
        request.url,
        headers = auth_header,
        parameters = dict([(k,v) for k,v in request.params.iteritems()]))

    consumer = ConsumerKeySecret.getByConsumerKey(req.get("oauth_consumer_key"))

    #if (request.logged_in != consumer.id):
    #    request.session.flash(_("You are trying to request a token using credentials that do not belong to you."))
    #    return HTTPForbidden(location = route_url("home", request))

    try:
        oauth_server.verify_request(req, consumer, None)

        # Check that this user doesn't already have an access token
        consumerToken = Token.getByConsumerID(consumer.id)
        if consumerToken:
            if (consumerToken.token_type == consumerToken.ACCESS):
                return Response(simplejson.dumps({'result': route_url('api_access_token', request)}))
            elif (consumerToken.token_type == consumerToken.AUTHORIZATION):
                # TODO
                # Check that the token hasn't already expired
                token = oauth2.Token(consumerToken.token, consumerToken.token_secret)
                if (appType == "android"):
                    return Response(token.to_string())
                else:
                    return Response(simplejson.dumps({'result': route_url('api_authorize_token', request, appType = appType) + '?' + token.to_string()}))

        nonce = ConsumerNonce.getByNonce(req.get("oauth_nonce"))
        if (nonce):
            return simplejson.dumps({"error": "Nonce is already registered for an authorization token; please generate another request token, or wait five minutes and try again."})
        else:
            nonce = ConsumerNonce()
            nonce.consumer_id = consumer.id
            nonce.timestamp = req.get("oauth_timestamp")
            nonce.nonce = req.get("oauth_nonce")
            session.add(nonce)

        randomData = hashlib.sha1(str(random.random())).hexdigest()
        key = generateRandomKey()
        secret = generateRandomKey()
        token = oauth2.Token(key, secret)
        token.callback_confirmed = True

        tokenData = Token()
        tokenData.token = key
        tokenData.token_secret = secret
        tokenData.consumer_id = consumer.id
        tokenData.timestamp = time.time()
        tokenData.callback_url = req.get("oauth_callback")
        tokenData.setAuthorizationType()
        session.add(tokenData)

        if (appType == "android"):
            return Response(token.to_string())
        elif (appType == "desktop"):
            result = {'result': route_url('api_authorize_token', request, appType = appType) + '?' + token.to_string()}
            return Response(simplejson.dumps(result))
    except oauth2.Error, e:
        return Response(simplejson.dumps({"oauth2 error": str(e)}))
Exemple #3
0
    req = oauth2.Request.from_consumer_and_token(consumer, 
        token = token, 
        http_method = request.method, 
        http_url = request.url, 
        parameters = dict([(k, v) for k,v in req.iteritems()]))

    try:
        oauth_server.verify_request(req, consumer, token)
    except oauth2.Error, e:
        return {"Oauth error": str(e)}
    except KeyError, e:
        return {"KeyError error": str(e)}
    except Exception, e:
        return {"General error": str(e)}

    nonce = ConsumerNonce()
    nonce.consumer_id = consumer.id
    nonce.timestamp = time.time()
    nonce.nonce = generateRandomKey()
    session.add(nonce)

    return {"nonce": nonce.nonce}

@view_config(route_name = "api_nexus_message_update", renderer="json", request_method = "POST")
def api_nexus_message_update(request):
    # TODO
    # add signed API call to request a nonce
    # and then in this call, check for nonce and for nonce time < 2 hours
    session = DBSession()

    if ("message" not in request.params):