Example #1
0
def Report(requestData):
    
    TAG = Const.Tags.Urls.MODERATION_REPORT
    
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:
        clientUser = securityProperties.userObject
        clientContentId = securityProperties.jsonRequestData[Const.Views.Report.JsonRequestKey.CONTENT_ID]
        
        # check that the content exists in the database
        clientContent = QueryManager.GetObjectByID(OnlineContent, clientContentId)
        if (not clientContent):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                       messageCode=Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND)  
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                                        Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND)
        
        # get the content type that the user is reporting
        contentType = clientContent.contentType
        
        # check if this user has already tried to create this report
        userDupeReports = ReportModel.objects.filter(fromUser=clientUser,
                                                contentID=clientContentId)
        
        # If so, log the hit and return an error to client
        if (userDupeReports):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, 
                                       messageCode=Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) 
             
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, 
                                                        Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) 
        
        # Create the report
        ReportModel.objects.create(fromUser=clientUser,
                                   contentID=Utils.UUIDToBinary(clientContentId),
                                   contentType=contentType)  
        
        # Log the hit and return
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                   messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                    Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL)    
                
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR)
Example #2
0
def UploadLive(requestData):
    TAG = Const.Tags.Urls.UPLOAD_LIVE

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:       
        clientUser = securityProperties.userObject
        clientSession = securityProperties.userSession
        clientThreadText= securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_TEXT]
        clientThreadKey = securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_URL]
        clientThreadARN = securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_ARN]
 
        # check if this user is posting too fast
        if (settings.RATE_LIMIT_LIVE and RateLimiter.UserLiveRateLimitExceeded(clientUser.id)): 
                  
            # log the warning and return if too many threads
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadLive.RATE_LIMIT_EXCEEDED)

            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                                        Const.DataCollection.MessageCodes.UploadLive.RATE_LIMIT_EXCEEDED) 

        # Save the live thread in the DB
        # Save title as an empty string if it is empty
        if (Utils.StringIsEmpty(clientThreadText)):
            clientThreadText = ''
               
        Thread.objects.create(fromUser=clientUser,
                              fromSession=clientSession,
                              contentType=Const.Tags.ContentTypes.THREAD,
                              text=clientThreadText,
                              key=clientThreadKey,
                              arn=clientThreadARN)
                     

        QueryManager.CheckAndPruneThreads()           
       
        # FOR RELEASE 1.1
        # return the list of threads after a successful thread upload    
        jsonString = GetThreadListJsonString()

        # log and return on success   
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadLive.POST_SUCCESSFUL)         
       
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    jsonString, 'application/json')
        
    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadLive.POST_FAILED_SERVER_ERROR)  

        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.UploadLive.POST_FAILED_SERVER_ERROR)
Example #3
0
    def _GetContent(self):

        # check online and archive tables
        if (QueryManager.ContentIsOnline(self.contentID)):
            self.content = OnlineContent.objects.get(id=self.contentID)
        elif (QueryManager.ContentIsArchived(self.contentID)):
            self.content = ArchivedContent.objects.get(id=self.contentID)
            self.archived = True
        else:
            print('Content does not exist in online or archive tables')
            sys.exit(0)

        # Display a warning note to user about archived content
        if (self.archived):
            print('Note: Specified content is archived (not online). Therefore\
                    content can only be displayed (no moderation actions can be\
                    taken)')
Example #4
0
    def _PrintLocalPost(self):
        if (self.archived):
            lp = QueryManager.GetObjectByID(ArchivedLocalPost, self.contentID)
        else:
            lp = QueryManager.GetObjectByID(LocalPost, self.contentID)

        Utils.PrintStartLine()
        print('LOCALPOST (CID ', self.contentID, ')')
        print('TimeCreated: ',
              Utils.GetPrettyFormatTimestamp(self.content.timeCreated))
        print('FromUser: '******'GPS: (', lp.latitude, ' , ', lp.longitude, ')')
        print('Text: ', lp.text)

        # Gather and print the mod info if the setting is set
        if (self.showModInfo):
            self._PrintModInfo(self.contentID)
        Utils.PrintEndLine()
Example #5
0
    def _PrintMessage(self):
        if (self.archived):
            ms = QueryManager.GetObjectByID(ArchivedMessage, self.contentID)
        else:
            ms = QueryManager.GetObjectByID(Message, self.contentID)

        Utils.PrintStartLine()
        print('MESSAGE (CID ', self.contentID, ')')
        print('TimeCreated: ',
              Utils.GetPrettyFormatTimestamp(self.content.timeCreated))
        print('FromUser: '******'ToUser: '******'Text: ', ms.text)

        # Gather and print the mod info if the setting is set
        if (self.showModInfo):
            self._PrintModInfo(self.contentID)
        Utils.PrintEndLine()
Example #6
0
    def _PrintReply(self):
        if (self.archived):
            re = QueryManager.GetObjectByID(ArchivedReply, self.contentID)
        else:
            re = QueryManager.GetObjectByID(Reply, self.contentID)

        Utils.PrintStartLine()
        print('REPLY (CID ', self.contentID, ')')
        print('TimeCreated: ',
              Utils.GetPrettyFormatTimestamp(self.content.timeCreated))
        print('FromUser: '******'OpName: ', re.name)
        print('HasImage: ', bool(re.url))
        print('Text: ', re.text)

        # Gather and print the mod info if the setting is set
        if (self.showModInfo):
            self._PrintModInfo()
        Utils.PrintEndLine()
Example #7
0
    def _PrintModInfo(self, contentID):
        numReports = Report.objects.filter(
            cid=Utils.UUIDToBinary(contentID)).count()
        online = False
        archived = False
        modActionType = ''

        if (QueryManager.ContentIsOnline(contentID)):
            online = True
        if (QueryManager.ContentIsArchived(contentID)):
            archived = True

        # Get the mod action associated with the piece of content, if there is one
        modActionType = QueryManager.GetMostRecentModActionResult(contentID)

        print('NumReports: ', numReports)
        print('Online: ', online)
        print('Archived: ', archived)
        print('Most recent mod action: ', 'N/A' if not modActionType else
              modActionType)  # ternary operator in python ;)
Example #8
0
 def _GetTableDataForReport(self, report):
     
     # Init data
     cid = Utils.StipUUIDDashes(report['contentID'])
     modActionID = report['modAction_id']  
     numReports = report['num_reports']
     contentType = report['contentType']
     timeCreated = ''
     fromUser = ''
     modActionType = ''
     online = False
 
     # Get the mod action from this report group if it exists                 
     try:
         modActionType = ModAction.objects.get(pk=modActionID).result
     except ObjectDoesNotExist:
         pass
     
     # Try to lookup the content from the online table
     onlineContent = QueryManager.GetObject(OnlineContent, id=cid)
     
     # If it is there, then use the info from it
     if (onlineContent):
         online = True
         contentType = onlineContent.contentType
         timeCreated = Utils.GetPrettyFormatTimestamp(onlineContent.timeCreated)
         fromUser = onlineContent.fromUser.id
         return [cid, contentType, timeCreated, fromUser, numReports, modActionType, online]
             
     # if the content is not online, then check the archives
     # (Only if the --excludeoffline flag is not set)       
     elif (not self.excludeOffline):                    
 
         # Try to get the archived content
         archivedContent = QueryManager.GetObject(ArchivedContent, pk=cid)
         
         if (archivedContent):
             contentType = archivedContent.contentType
             timeCreated = Utils.GetPrettyFormatTimestamp(archivedContent.timeCreated)
             fromUser = archivedContent.fromUser.id
             return [cid, contentType, timeCreated, fromUser, numReports, modActionType, online]
Example #9
0
def SubscribeLive(requestData):
    TAG = Const.Tags.Urls.SUBSCRIBE_LIVE
        
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:        
        instanceID = securityProperties.jsonRequestData[Const.Views.SubscribeLive.JsonRequestKey.INSTANCE_ID]
        threadID = securityProperties.jsonRequestData[Const.Views.SubscribeLive.JsonRequestKey.THREAD_ID]

        # Check that the thread exists
        if (not QueryManager.ContentIsOnline(threadID)):
            # If not, return 404
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.THREAD_NOT_FOUND)
                       
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND,
                                                        Const.DataCollection.MessageCodes.SubscribeLive.THREAD_NOT_FOUND)
        
        # try to subscribe to the thread
        googleResponseCode = GCMManager.SubscribeUserToThread(instanceID, threadID)
        
        # check the response. If it was not successful, return an error
        if (googleResponseCode != Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK):
                DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_BAD_REQUEST,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.GCM_SUBSCRIBE_FAILED)
                       
                return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_BAD_REQUEST,
                                                            Const.DataCollection.MessageCodes.SubscribeLive.GCM_SUBSCRIBE_FAILED)
            

        # log and return on success          
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_SUCCESSFUL)
                       
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                    Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_SUCCESSFUL)
    
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_FAILED_SERVER_ERROR)
 
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_FAILED_SERVER_ERROR)
Example #10
0
def _ArchiveThread(content):
    
    # Get the online thread and all of its replies 
    onlineThread = Thread.objects.get(id=content.id)
    onlineReplies = Reply.objects.filter(parentThread=onlineThread)
    
    # Check if the thread is already archived and retrieve it if it is 
    archivedThread = QueryManager.GetObject(ArchivedThread, id=content.id)
    
    # If the thread is not archived already, then archive it 
    if (not archivedThread):
        archivedContent = ArchivedContent.objects.create(id=onlineThread.id,
                                                        timeOriginalCreated=onlineThread.timeCreated,
                                                        fromUser=onlineThread.fromUser,
                                                        fromSession=onlineThread.fromSession,
                                                        key=onlineThread.key,
                                                        contentType=onlineThread.contentType)
        
        archivedThread = ArchivedThread.objects.create(archivedContent=archivedContent,
                                                       arn=onlineThread.arn,
                                                       text=onlineThread.text) 
        
    # Archive each online reply and link it back to the archived parent
    # thread
    for reply in onlineReplies:
        # check if each reply is archived. If it is not, then archive it
        archivedReply = QueryManager.GetObject(ArchivedReply, id=reply.id)

        if (not archivedReply):
            ArchivedReply.objects.create(id=reply.id,
                                        timeOriginalCreated=reply.timeCreated,
                                        fromUser=reply.fromUser,
                                        fromSession=reply.fromSession,
                                        key=reply.key,
                                        contentType=reply.contentType,
                                        fav=reply.fav,
                                        parentThread=archivedThread,
                                        text=reply.text)
Example #11
0
    def _PrintThread(self):
        if (self.archived):
            th = QueryManager.GetObjectByID(ArchivedThread, self.contentID)
        else:
            th = QueryManager.GetObjectByID(Thread, self.contentID)

        Utils.PrintStartLine()
        print('THREAD (CID ', self.contentID, ')')
        print('TimeCreated: ',
              Utils.GetPrettyFormatTimestamp(self.content.timeCreated))
        print('FromUser: '******'Title: ', th.title)
        print('OpName: ', th.name)
        print('NumReplies: ', th.replyCount)
        print('Text: ', th.text)

        # Gather and print the mod info if the setting is set
        if (self.showModInfo):
            self._PrintModInfo(self.contentID)
        Utils.PrintEndLine()

        if (self.showFullThread):
            self._PrintThreadReplies(self.contentID)
Example #12
0
    def _PrintThreadReplies(self):
        replies = QueryManager.GetThreadReplies(self.contentID)

        print('PRINITING REPLIES FOR THEAD (CID ', self.contentID, ')')

        for re in replies:
            print(
                '--------------------------------------------------------------------------------'
            )
            print('REPLY (CID ', Utils.BinaryToUUID(re.cid.id), ')')
            print('TimeCreated: ',
                  Utils.GetPrettyFormatTimestamp(re.timeCreated))
            print('FromUser: '******'OpName: ', re.name)
            print('HasImage: ', bool(re.url))
            print('Text: ', re.text)

        Utils.PrintEndLine()
Example #13
0
def GetThreadListJsonString():
    
    # get the threads by time created
    threads = QueryManager.GetLiveThreadsByTimeLastActive()
        
    # Get the stuff we need from the thread, package and return to the client
    clientThreadsToReturn = []
    for index, thread in enumerate(threads):
        objectToReturn = _GetThreadClientObject(id=Utils.BinaryToUUID(thread.id),
                                                text=thread.text, 
                                                time=thread.timeCreated, 
                                                key=thread.key,
                                                order=index,
                                                replies=thread.replyCount,
                                                unique=thread.uniquePostersCount,
                                                arn=thread.arn) 
        clientThreadsToReturn.append(objectToReturn.getOrderedDict())   
           
    return json.dumps(clientThreadsToReturn)
Example #14
0
def _ArchiveReply(content):
    import JokrBackend.DataCollection.QueryManager as QueryManager

    # Check if the reply exists in the archive
    # If it does not, then continue. Otherwise, do nothing
    if (not QueryManager.ContentIsArchived(content.id)):
        
        # Get the online reply    
        onlineReply = Reply.objects.get(pk=content.id)
        
        # Check and get the parent thread if it is archived
        try:
            archivedThread = ArchivedThread.objects.get(pk=onlineReply.parentThread)
                    
        # If the parent thread is not archived, we need to archive it first
        # before we can archive this reply.
        except ObjectDoesNotExist:
            
            # Get the online parent thread
            onlineThread = Thread.objects.get(pk=onlineReply.parentThread)

            # Archive the online thread
            archivedThread = ArchivedThread.objects.create(id=onlineThread.id,
                                                  timeOriginalCreated=onlineThread.timeCreated,
                                                  fromUser=onlineThread.fromUser,
                                                  fromSession=onlineThread.fromSession,
                                                  key=onlineThread.key,
                                                  contentType=onlineThread.contentType,
                                                  fav=onlineThread.fav,
                                                  arn=onlineThread.arn,
                                                  text=onlineThread.text) 
            
        # Archive the reply and link it to the archived thread
        ArchivedReply.objects.create(id=onlineReply.id,
                                    timeOriginalCreated=onlineReply.timeCreated,
                                    fromUser=onlineReply.fromUser,
                                    fromSession=onlineReply.fromSession,
                                    key=onlineReply.key,
                                    contentType=onlineReply.contentType,
                                    fav=onlineReply.fav,
                                    parentThread=archivedThread,
                                    text=onlineReply.text)
Example #15
0
 def handle(self, *args, **options): 
     
     self.userID = options['uuid'][0]
     self.scriptAction = options['action']
     
     # Get the user object
     self.user = QueryManager.GetObject(User, id=self.userID)
     
     # Exit if not found
     if (not self.user):
         print('User not found with that UUID. Exiting...')
         sys.exit(0)
     
     # Take appropriate action
     if (self.scriptAction == Const.Scripts.Moderation.ArgNames.MODUSER_ACTION_DISPLAY):
         self._DisplayUser()
     elif (self.scriptAction == Const.Scripts.Moderation.ArgNames.MODUSER_ACTION_BAN):
         self._BanUser()
     elif (self.scriptAction == Const.Scripts.Moderation.ArgNames.MODUSER_ACTION_SEARCH):
         self._SearchUser()
Example #16
0
 def _BanUser(self):
     
     Utils.PrintStartLine()
     print('Creating a new user ban...')
     print('Enter the ban length in hours (whole numbers only): ')
     
     # Take the ban length. No partial hours, only whole numbers
     banLength = input()
     
     # Check that ban length is good
     if (Utils.IsPositiveInt(banLength)):
                 
         # Check if this user is currently banned . If so, then exit
         if (QueryManager.UserIsBanned(self.user)):
             print('This user is currently under a ban already. Please run\
              this script on the user to verify')
             sys.exit(0)
             
         # Otherwise, confirm and create the ban
         else:
             print('Are you sure you want to ban user ', self.userID,\
                   ' for ', banLength, ' hours? (y/n)')
             response = input()
             
             if (response == 'Y' or response == 'y'):
                 Ban.objects.create(bannedUser=self.user,
                                    timeBanExpires=int(banLength) * Const.SECONDS_IN_HOUR)
             
                 print('Ban created successfully.  Please run this script on\
                     the user to verify')
             
             else:
                 print('Okay, exiting now')
     
     else:
         print('Ban length must be a positive int. Exiting.')
         sys.exit(0)
         
     Utils.PrintEndLine()
Example #17
0
def GetReply(requestData):
    TAG = Const.Tags.Urls.GET_REPLY

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:

        clientUser = securityProperties.userObject
        clientThreadID = securityProperties.jsonRequestData[
            Const.Views.GetReply.JsonRequestKey.THREAD_ID]

        # Retrieve the thread and replies from the database
        thread = QueryManager.GetObjectByID(Thread, clientThreadID)
        threadReplies = Reply.objects.filter(parentThread=thread)

        if (not thread):
            DataCollector.UpdateURLHit(
                hitID=securityProperties.hitID,
                responseCode=Const.HttpResponseFactory.ResponseCodes.
                ClientError.CODE_NOT_FOUND,
                messageCode=Const.DataCollection.MessageCodes.GetReply.
                THREAD_NOT_FOUND)

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.ClientError.
                CODE_NOT_FOUND,
                Const.DataCollection.MessageCodes.GetReply.THREAD_NOT_FOUND)

        # Package the thread replies and return
        clientReplyListToReturn = []
        for reply in threadReplies:
            replyClientObject = GetReplyClientObject(text=reply.text,
                                                     time=reply.timeCreated,
                                                     id=Utils.BinaryToUUID(
                                                         reply.id),
                                                     key=reply.key)
            clientReplyListToReturn.append(replyClientObject.getDict())

        jsonString = json.dumps(clientReplyListToReturn)

        # log and return on success
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                   responseCode=Const.HttpResponseFactory.
                                   ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.
                                   MessageCodes.GetReply.REQUEST_SUCCESSFUL)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR,
            messageCode=Const.DataCollection.MessageCodes.GetReply.
            REQUEST_FAILED_SERVER_ERROR)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            GetReply.REQUEST_FAILED_SERVER_ERROR)
Example #18
0
def UploadReply(requestData):
    TAG = Const.Tags.Urls.UPLOAD_REPLY
     
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:
        clientUser = securityProperties.userObject
        clientSession = securityProperties.userSession
        clientThreadID = securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.THREAD_ID]
        clientReplyText= securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.REPLY_TEXT]
        clientReplyKey = securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.REPLY_URL]

        # Moderation - check if this user is posting replies too fast
        if (settings.RATE_LIMIT_LIVE and RateLimiter.UserReplyRateLimitExceeded(clientUser.id)):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadReply.RATE_LIMIT_EXCEEDED)  
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                                        Const.DataCollection.MessageCodes.UploadReply.RATE_LIMIT_EXCEEDED)
        
        # Find the parent thread to reply to in the DB  
        threadToReplyTo = QueryManager.GetObjectByID(Thread, clientThreadID)
        
        if (not threadToReplyTo):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadReply.THREAD_NOT_FOUND) 
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                                        Const.DataCollection.MessageCodes.UploadReply.THREAD_NOT_FOUND)

        # These fields are optional. Make sure that they go into the DB
        # as an empty string if they are not present 
        if (Utils.StringIsEmpty(clientReplyText)):
            clientReplyText = ''
        if (Utils.StringIsEmpty(clientReplyKey)):
            clientReplyKey = ''

        # Save the reply in the DB
        newReply = Reply.objects.create(fromUser=clientUser,
                             fromSession=clientSession,
                             contentType=Const.Tags.ContentTypes.REPLY,
                             parentThread=threadToReplyTo,
                             text=clientReplyText,
                             key=clientReplyKey)
        
        # Broadcast the reply out to this thread's subscribers using GCM
        # Create the client reply object
        newReplyClientObject = GetReplyClientObject(text=newReply.text, 
                                                    time=newReply.timeCreated, 
                                                    id=Utils.BinaryToUUID(newReply.id), 
                                                    key=newReply.key) 
        
        # Turn it into JSON and send it off
        googleResponseCode = GCMManager.BroadcastReplyToSubscribers(parentThreadID=clientThreadID,
                                               newReplyJSON=newReplyClientObject.getDict()) 
        
        # Check the response code from google
        # If it is not successful, return and log a warning, but still
        # return a 200 code to the client (since the reply saved ok)
        if (googleResponseCode != Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK):
                DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.MessageCodes.UploadReply.GCM_BROADCAST_FAILED)
                       
                return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                            Const.DataCollection.MessageCodes.UploadReply.GCM_BROADCAST_FAILED)
        
        
        # log and return on success
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadReply.POST_SUCCESSFUL) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    Const.DataCollection.MessageCodes.UploadReply.POST_SUCCESSFUL)
    
    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadReply.POST_FAILED_SERVER_ERROR)  
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.UploadReply.POST_FAILED_SERVER_ERROR)
Example #19
0
def CheckUserIdentity(securityProperties, urlTag, currentTime):

    # /security/login/ requires the user's UUID parameter
    if (urlTag == Const.Tags.Urls.SECURITY_LOGIN):

        # Get the user object from the DB
        try:
            # If the client supplied a userID,
            if (securityProperties.userID):
                # Get the user object using the userID
                securityProperties.userObject = QueryManager.GetObjectByID(
                    User, securityProperties.userID)

            # Otherwise, log the error as having a blank uuid
            else:
                securityProperties.errorsList.append(
                    Const.DataCollection.MessageCodes.Security.NO_CLIENT_ID)

        # this means the uuid was not in the DB
        except ObjectDoesNotExist:
            securityProperties.errorsList.append(
                Const.DataCollection.MessageCodes.Security.BAD_CLIENT_ID)

    # Otherwise, check the session using the session token
    # The session token is required for all URLs except:
    #    /security/create/
    #    /security/login/
    elif (urlTag != Const.Tags.Urls.SECURITY_CREATE):
        try:
            # If the client supplied a session token,
            if (securityProperties.sessionToken):
                # Get the user session from the token
                userSession = Session.objects.get(
                    token=securityProperties.sessionToken)

                # Check if the session is expired. If so, log the error
                if (userSession.timeExpires <= currentTime):
                    securityProperties.errorsList.append(
                        Const.DataCollection.MessageCodes.Security.
                        EXPIRED_SESSION)

                # Save the user object and user session
                securityProperties.userObject = userSession.fromUser
                securityProperties.userSession = userSession

            # Otherwise, if no token, log the error
            else:
                securityProperties.errorsList.append(
                    Const.DataCollection.MessageCodes.Security.NO_SESSION_TOKEN
                )

        # If the user's token was not in the database at all, log the error
        except ObjectDoesNotExist:
            securityProperties.errorsList.append(
                Const.DataCollection.MessageCodes.Security.BAD_SESSION_TOKEN)

    # Check if this user is banned from this url/service
    if (_UserIsBannedFromURL(urlTag, securityProperties.userObject)):
        securityProperties.errorsList.append(
            Const.DataCollection.MessageCodes.Security.BANNED_FROM_SERVICE)

    return securityProperties