예제 #1
0
def readConfiguration():
    """
    Reads configuration file and returns content as a dictionary.

    @rtype: C{dict}
    @return: Returns dictionary with all the values
    """
    
    configPath = '%s/configuration.json' % settings.BOOKI_ROOT

    try:
        f = open(configPath, 'r')
        data = f.read()
        f.close()
    except IOError:
        raise ConfigurationError("Can't read file %s." % configPath)
    except:
        raise ConfigurationError("Unknown error.")

    try:
        confData = simplejson.loads(data)
    except:
        return None

    return confData
예제 #2
0
def readConfiguration():
    """
    Reads configuration file and returns content as a dictionary.

    @rtype: C{dict}
    @return: Returns dictionary with all the values
    """

    configPath = '%s/configuration.json' % settings.BOOKI_ROOT

    try:
        f = open(configPath, 'r')
        data = f.read()
        f.close()
    except IOError:
        raise ConfigurationError("Can't read file %s." % configPath)
    except:
        raise ConfigurationError("Unknown error.")

    try:
        confData = simplejson.loads(data)
    except:
        return None

    return confData
예제 #3
0
def signin(request):
    """
    Django View. Gets called when user wants to signin or create new account.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    """

    from booki.utils.json_wrapper import simplejson
    from booki.utils.misc import isUserLimitReached
    from booki.editor.models import BookiGroup

    from django.core.exceptions import ObjectDoesNotExist
    from django.contrib import auth

    limitReached = isUserLimitReached()

    if request.POST.get("ajax", "") == "1":
        ret = {"result": 0}

        if request.POST.get("method",
                            "") == "register" and config.getConfiguration(
                                'FREE_REGISTRATION') and not limitReached:

            def _checkIfEmpty(key):
                return request.POST.get(key, "").strip() == ""

            def _doChecksForEmpty():
                if _checkIfEmpty("username"): return 2
                if _checkIfEmpty("email"): return 3
                if _checkIfEmpty("password") or _checkIfEmpty("password2"):
                    return 4
                if _checkIfEmpty("fullname"): return 5

                return 0

            ret["result"] = _doChecksForEmpty()

            if ret["result"] == 0:  # if there was no errors
                import re

                def _doCheckValid():
                    # check if it is valid username
                    # - from 2 to 20 characters long
                    # - word, number, ., _, -
                    mtch = re.match('^[\w\d\_\.\-]{2,20}$',
                                    request.POST.get("username", "").strip())
                    if not mtch: return 6

                    # check if it is valid email
                    if not bool(email_re.match(request.POST["email"].strip())):
                        return 7

                    if request.POST.get("password", "") != request.POST.get(
                            "password2", "").strip():
                        return 8
                    if len(request.POST.get("password", "").strip()) < 6:
                        return 9

                    if len(request.POST.get("fullname", "").strip()) > 30:
                        return 11

                    # check if this user exists
                    try:
                        u = auth.models.User.objects.get(
                            username=request.POST.get("username", "").strip())
                        return 10
                    except auth.models.User.DoesNotExist:
                        pass

                    return 0

                ret["result"] = _doCheckValid()

                if ret["result"] == 0:
                    ret["result"] = 1

                    user = None

                    try:
                        user = auth.models.User.objects.create_user(
                            username=request.POST["username"].strip(),
                            email=request.POST["email"].strip(),
                            password=request.POST["password"].strip())
                    except IntegrityError:
                        ret["result"] = 10
                    except:
                        ret["result"] = 10
                        user = None

                    # this is not a good place to fire signal, but i need password for now
                    # should create function createUser for future use

                    if user:
                        user.first_name = request.POST["fullname"].strip()

                        import booki.account.signals
                        booki.account.signals.account_created.send(
                            sender=user, password=request.POST["password"])

                        try:
                            user.save()

                            # groups

                            for groupName in simplejson.loads(
                                    request.POST.get("groups")):
                                if groupName.strip() != '':
                                    sid = transaction.savepoint()

                                    try:
                                        group = BookiGroup.objects.get(
                                            url_name=groupName)
                                        group.members.add(user)
                                    except:
                                        transaction.savepoint_rollback(sid)
                                    else:
                                        transaction.savepoint_commit(sid)

                            user2 = auth.authenticate(
                                username=request.POST["username"].strip(),
                                password=request.POST["password"].strip())
                            auth.login(request, user2)
                        except:
                            transaction.rollback()
                            ret["result"] = 666
                        else:
                            transaction.commit()
                    else:
                        transaction.rollback()

        if request.POST.get("method", "") == "signin":
            user = auth.authenticate(username=request.POST["username"].strip(),
                                     password=request.POST["password"].strip())

            if user:
                auth.login(request, user)
                ret["result"] = 1

                from django.core.urlresolvers import reverse
                ret["redirect"] = reverse('view_profile', args=[user.username])
            else:
                try:
                    usr = auth.models.User.objects.get(
                        username=request.POST["username"])
                    # User does exist. Must be wrong password then
                    ret["result"] = 3
                except auth.models.User.DoesNotExist:
                    # User does not exist
                    ret["result"] = 2

        try:
            resp = HttpResponse(simplejson.dumps(ret), mimetype="text/json")
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return resp

    from django.core.urlresolvers import reverse
    redirect = request.GET.get('redirect', '')

    if (redirect == reverse('frontpage')):
        redirect = ''

    if request.GET.get('next', None):
        redirect = request.GET.get('next')

    joinGroups = []
    for groupName in request.GET.getlist("group"):
        try:
            joinGroups.append(BookiGroup.objects.get(url_name=groupName))
        except BookiGroup.DoesNotExist:
            pass

    try:
        resp = render_to_response(
            'account/signin.html', {
                'request': request,
                'redirect': redirect,
                'joingroups': joinGroups,
                'limit_reached': limitReached
            })
    except:
        transaction.rollback()
        raise
    else:
        transaction.commit()

    return resp
예제 #4
0
파일: views.py 프로젝트: Rogaton/Booki
def dispatcher(request, **sputnik_dict):
    """
    Main Sputnik dispatcher. Every Sputnik request goes through this dispatcher. 

    Input arguments are passed through C{request.POST}:
      - C{request.POST['messages']} 
          List of messages client is sending to server.
      - C{request.POST['clientID']} 
          Unique client ID for this connection.

    This is just another Django view.

    @todo: Change logging and error handling.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type sputnik_dict: C{dict}
    @param sputnik_dict: Mapping of channels with specific python modules.
    @rtype: C{HttpResponse}
    @return: Return C{django.http.HttpResponse} object.
    """

    try:
        inp =  request.POST
    except IOError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    results = []

    clientID = None
    messages = simplejson.loads(inp.get("messages", "[]"))

    if inp.has_key("clientID") and inp["clientID"]:
        clientID = inp["clientID"]


    for message in messages:
        ret = None
        for mpr in sputnik_dict['map']:
            mtch = re.match(mpr[0], message["channel"])

            if mtch:
                a =  mtch.groupdict()
                _m = __import__(mpr[1])

                for nam in mpr[1].split('.')[1:]:
                    _m = getattr(_m, nam)

                if _m:
                    # should do hasattr first and then getattr
                    fnc = getattr(_m, "remote_%s" % message['command'])

                    if not hasattr(request, "sputnikID"):
                        request.sputnikID = "%s:%s" % (request.session.session_key, clientID)
                        request.clientID  = clientID

                    if fnc:
                        ret = fnc(request, message, **a)
                        if not ret:
                            ret = {}

                        ret["uid"] = message.get("uid")
                        break
                    else:
                        import logging
                        logging.getLogger("booki").error("Could not find function '%s' for Sputnik channel '%d'!" % (message['command'], message['channel']))

        if ret:
            results.append(ret)
        else:
            import logging
            logging.getLogger("booki").error("Sputnik - %s." % simplejson.dumps(message))

    n = 0

    while True:
        v = None

        try:
            if clientID and clientID.find(' ') == -1:
                v = sputnik.rpop("ses:%s:%s:messages" % (request.session.session_key, clientID))
        except:
            if n > 20:
                break


            import logging
            logging.getLogger("booki").debug("Sputnik - Coult not get the latest message from the queue session: %s clientID:%s" %(request.session.session_key, clientID))

#            from booki.utils.log import printStack
#            printStack(None)


        n += 1

        if not v: break
        try:
            results.append(simplejson.loads(v))
        except:

            import logging
            logging.getLogger("booki").debug(v)

#            from booki.utils.log import printStack
#            printStack(None)


    import time, decimal
    try:
        if request.sputnikID and request.sputnikID.find(' ') == -1:
            sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())
    except:

        import logging
        logging.getLogger("booki").debug("Sputnik - CAN NOT SET TIMESTAMP.")

#        from booki.utils.log import printStack
#        printStack(None)


    # this should not be here!
    # timeout old edit locks

    locks = {}

    _now = time.time() 
    try:
        for k in sputnik.rkeys("ses:*:last_access"):
            tm = sputnik.get(k)

            if type(tm) in [type(' '), type(u' ')]:
                try:
                    tm = decimal.Decimal(tm)
                except:
                    continue

        # timeout after 2 minute
            if  tm and decimal.Decimal("%f" % _now) - tm > 60*2:
                sputnik.removeClient(request, k[4:-12])
    except:
        import logging
        logging.getLogger("booki").debug("Sputnik - can not get all the last accesses")

#        from booki.utils.log import printStack
#        printStack(None)


    ret = {"result": True, "messages": results}

    try:
        return HttpResponse(simplejson.dumps(ret), mimetype="text/json")
    except:
        transaction.rollback()
    finally:
        transaction.commit()
예제 #5
0
파일: views.py 프로젝트: MechanisM/Booktype
def signin(request):
    """
    Django View. Gets called when user wants to signin or create new account.

    @type request: C{django.http.HttpRequest}
    @param request: Django Request
    """


    from booki.utils.json_wrapper import simplejson

    from booki.editor.models import BookiGroup

    from django.core.exceptions import ObjectDoesNotExist
    from django.contrib import auth

    if request.POST.get("ajax", "") == "1":
        ret = {"result": 0}

        if request.POST.get("method", "") == "register":
            def _checkIfEmpty(key):
                return request.POST.get(key, "").strip() == ""

            def _doChecksForEmpty():
                if _checkIfEmpty("username"): return 2
                if _checkIfEmpty("email"): return 3
                if _checkIfEmpty("password") or _checkIfEmpty("password2"): return 4
                if _checkIfEmpty("fullname"): return 5

                return 0

            ret["result"] = _doChecksForEmpty()

            if ret["result"] == 0: # if there was no errors
                import re

                def _doCheckValid():
                    # check if it is valid username
                    # - from 2 to 20 characters long
                    # - word, number, ., _, -
                    mtch = re.match('^[\w\d\_\.\-]{2,20}$', request.POST.get("username", "").strip())
                    if not mtch:  return 6

                    # check if it is valid email
                    if not bool(email_re.match(request.POST["email"].strip())): return 7

                    if request.POST.get("password", "") != request.POST.get("password2", "").strip(): return 8
                    if len(request.POST.get("password", "").strip()) < 6: return 9

                    if len(request.POST.get("fullname", "").strip()) > 30: return 11

                    # check if this user exists
                    try:
                        u = auth.models.User.objects.get(username=request.POST.get("username", "").strip())
                        return 10
                    except auth.models.User.DoesNotExist:
                        pass

                    return 0

                ret["result"] = _doCheckValid()

                if ret["result"] == 0:
                    ret["result"] = 1

                    user = None

                    try:
                        user = auth.models.User.objects.create_user(username=request.POST["username"].strip(),
                                                                    email=request.POST["email"].strip(),
                                                                    password=request.POST["password"].strip())
                    except IntegrityError:
                        ret["result"] = 10

                    # this is not a good place to fire signal, but i need password for now
                    # should create function createUser for future use

                    if user:
                        import booki.account.signals
                        booki.account.signals.account_created.send(sender = user, password = request.POST["password"])

                        user.first_name = request.POST["fullname"].strip()

                        try:
                            user.save()

                            # groups

                            for groupName in simplejson.loads(request.POST.get("groups")):
                                if groupName.strip() != '':
                                    sid = transaction.savepoint()

                                    try:
                                        group = BookiGroup.objects.get(url_name=groupName)
                                        group.members.add(user)
                                    except:
                                        transaction.savepoint_rollback(sid)
                                    else:
                                        transaction.savepoint_commit(sid)

                            user2 = auth.authenticate(username=request.POST["username"].strip(), password=request.POST["password"].strip())
                            auth.login(request, user2)
                        except:
                            transaction.rollback()
                            ret["result"] = 666
                        else:
                            transaction.commit()

        if request.POST.get("method", "") == "signin":
            user = auth.authenticate(username=request.POST["username"].strip(), password=request.POST["password"].strip())

            if user:
                auth.login(request, user)
                ret["result"] = 1

                from django.core.urlresolvers import reverse
                ret["redirect"] = reverse('view_profile', args=[user.username])
            else:
                try:
                    usr = auth.models.User.objects.get(username=request.POST["username"])
                    # User does exist. Must be wrong password then
                    ret["result"] = 3
                except auth.models.User.DoesNotExist:
                    # User does not exist
                    ret["result"] = 2

        transaction.commit()
        return HttpResponse(simplejson.dumps(ret), mimetype="text/json")

    from django.core.urlresolvers import reverse
    redirect = request.GET.get('redirect', '')

    if(redirect == reverse('frontpage')): 
        redirect = ''
    
    if request.GET.get('next', None):
        redirect = request.GET.get('next')


    joinGroups = []
    for groupName in request.GET.getlist("group"):
        try:
            joinGroups.append(BookiGroup.objects.get(url_name=groupName))
        except BookiGroup.DoesNotExist:
            pass

    try:
        return render_to_response('account/signin.html', {"request": request, 'redirect': redirect, 'joingroups': joinGroups})
    except:
        transaction.rollback()
    finally:
        transaction.commit()
예제 #6
0
def jsonlookup(d, key):
    from booki.utils.json_wrapper import simplejson

    d2 = simplejson.loads(d)

    return d2[key]
예제 #7
0
def jsonlookup(d, key):
    from booki.utils.json_wrapper import simplejson

    d2 = simplejson.loads(d)

    return d2[key]
예제 #8
0
def dispatcher(request, **sputnik_dict):
    """
    Main Sputnik dispatcher. Every Sputnik request goes through this dispatcher. 

    Input arguments are passed through C{request.POST}:
      - C{request.POST['messages']} 
          List of messages client is sending to server.
      - C{request.POST['clientID']} 
          Unique client ID for this connection.

    This is just another Django view.

    @todo: Change logging and error handling.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type sputnik_dict: C{dict}
    @param sputnik_dict: Mapping of channels with specific python modules.
    @rtype: C{HttpResponse}
    @return: Return C{django.http.HttpResponse} object.
    """

    try:
        inp =  request.POST
    except IOError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    results = []

    clientID = None

    try:
        messages = simplejson.loads(inp.get("messages", "[]"))
    except ValueError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    if inp.has_key("clientID") and inp["clientID"]:
        clientID = inp["clientID"]


    for message in messages:
        ret = None
        for mpr in sputnik_dict['map']:
            mtch = re.match(mpr[0], message["channel"])

            if mtch:
                a =  mtch.groupdict()
                _m = __import__(mpr[1])

                for nam in mpr[1].split('.')[1:]:
                    _m = getattr(_m, nam)

                if _m:
                    # should do hasattr first and then getattr
                    fnc = getattr(_m, "remote_%s" % message['command'])

                    if not hasattr(request, "sputnikID"):
                        request.sputnikID = "%s:%s" % (request.session.session_key, clientID)
                        request.clientID  = clientID

                    if fnc:
                        ret = fnc(request, message, **a)
                        if not ret:
                            ret = {}

                        ret["uid"] = message.get("uid")
                        break
                    else:
                        import logging
                        logging.getLogger("booki").error("Could not find function '%s' for Sputnik channel '%d'!" % (message['command'], message['channel']))

        if ret:
            results.append(ret)
        else:
            import logging
            logging.getLogger("booki").error("Sputnik - %s." % simplejson.dumps(message))

    n = 0

    while True:
        v = None

        try:
            if clientID and clientID.find(' ') == -1:
                v = sputnik.rpop("ses:%s:%s:messages" % (request.session.session_key, clientID))
        except:
            if n > 20:
                break


            import logging
            logging.getLogger("booki").debug("Sputnik - Coult not get the latest message from the queue session: %s clientID:%s" %(request.session.session_key, clientID))

#            from booki.utils.log import printStack
#            printStack(None)


        n += 1

        if not v: break
        try:
            results.append(simplejson.loads(v))
        except:

            import logging
            logging.getLogger("booki").debug(v)

#            from booki.utils.log import printStack
#            printStack(None)


    import time, decimal
    try:
        if request.sputnikID and request.sputnikID.find(' ') == -1:
            sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())
    except:

        import logging
        logging.getLogger("booki").debug("Sputnik - CAN NOT SET TIMESTAMP.")

#        from booki.utils.log import printStack
#        printStack(None)


    # this should not be here!
    # timeout old edit locks

    locks = {}

    _now = time.time() 
    try:
        for k in sputnik.rkeys("ses:*:last_access"):
            tm = sputnik.get(k)

            if type(tm) in [type(' '), type(u' ')]:
                try:
                    tm = decimal.Decimal(tm)
                except:
                    continue

        # timeout after 2 minute
            if  tm and decimal.Decimal("%f" % _now) - tm > 60*2:
                sputnik.removeClient(request, k[4:-12])
    except:
        import logging
        logging.getLogger("booki").debug("Sputnik - can not get all the last accesses")

#        from booki.utils.log import printStack
#        printStack(None)


    ret = {"result": True, "messages": results}

    try:
        return HttpResponse(simplejson.dumps(ret), mimetype="text/json")
    except:
        transaction.rollback()
    finally:
        transaction.commit()