예제 #1
0
def SignUpAPI(request):
    if request.method == 'POST':
        # POST METHOD: Aca valido la informacion de creacion de usuario
        # Obtengo los parametros del JSON enviado
        params = api.json_to_dict(request.body)
        information = {}
        
        # Si los parametros son invalidos
        if params is None:
                # ERROR PARAMETROS INVALIDOS
                api.set_error(information,6,_("Invalid parameters"))
                return api.render_to_json(information);
                
        
        # Obtengo la informacon ingresada
        information['username'] = params.get('username', '')
        password = params.get('password', '')
        vpassword = params.get('vpassword', '')
        information['email'] = params.get('email', '')
        information['name'] = params.get('name', '')
        information['lastname'] = params.get('lastname', '')
        information['country'] = params.get('country', '')
        # NO ERROR!
        api.set_error(information,0)
        leave_open = params.get('remember',None)
        
        # Valido los datos.
        if not User.isValidUsername(information['username']):
            # ERROR NOMBRE DE USUARIO INVALIDO
            api.set_error(information,1,_("Invalid username"))
        elif not User.isValidPassword(password):
            # Marco el error de password invaludo
            # ERROR CLAVE INVALIDA
            api.set_error(information,2,_("Invalid password"))
        elif password != vpassword:
            # Marco el error de passwords distintas
            # ERROR CLAVES NO SON IDENTICAS
            api.set_error(information,3,_("Passwords don't match"))
        elif not User.isValidEmail(information['email']):
            # Marco el error de password invaludo
            # ERROR EMAIL INVALIDO
            api.set_error(information,4,_('Invalid mail'))
        else:
            user = User.add(information['username'],password,information['email'],information['name'], information['lastname']);
            if  user == None:
                # Marco el error de usuario ya existente
                # ERROR USUARIO YA EXISTE
                api.set_error(information,5,_("Username already exists"))
        
        
        if information['error-code'] != 0:
            # Hubo un error al crear el usuario. Envio el diccionario en formato json
            return api.render_to_json(information);
        else:
            # Se creo un usuario, redirijo pero seteo la cookie para identificar
            response = api.render_to_json(information)
            Crypt.set_secure_cookie(response,'user_id',information['username'],expires=True) # Expira al cerrar el navegador
            return response
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #2
0
def SlidesAPI(request):
	if request.method == 'GET':
		slideList = []
		slidesQuerySet = Slide.getSlides(3)
		for slide in slidesQuerySet:
			slideList.append(slide.getDictionary())
		
		return render_to_json(slideList)
	elif request.method == 'POST':
		returnData = {}
		# Obtengo los parametros del JSON enviado
		try:
			for obj in serializers.deserialize("json", request.body):
				deserialized_object = obj
		except DeserializationError: #Lo unico que causa error de deserializacion es el formato de la fecha
			returnData['error_code'] = 2 # ERROR FECHA INVALIDA
			returnData['error_description'] = _("Invalid date")
			return render_to_json(returnData);
			
		returnData['error_code'] = 0 # NO ERROR!
		returnData['error_description'] = ""
		if objectShouldBeSaved(deserialized_object,returnData):
			#We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
			deserialized_object.object.id = None
			deserialized_object.object.pk = None
			deserialized_object.save()

		return render_to_json(returnData);
def SlidesAPI(request):
    if request.method == 'GET':
        slideList = []
        slidesQuerySet = Slide.getSlides(3)
        for slide in slidesQuerySet:
            slideList.append(slide.getDictionary())

        return render_to_json(slideList)
    elif request.method == 'POST':
        returnData = {}
        # Obtengo los parametros del JSON enviado
        try:
            for obj in serializers.deserialize("json", request.body):
                deserialized_object = obj
        except DeserializationError:  #Lo unico que causa error de deserializacion es el formato de la fecha
            returnData['error_code'] = 2  # ERROR FECHA INVALIDA
            returnData['error_description'] = _("Invalid date")
            return render_to_json(returnData)

        returnData['error_code'] = 0  # NO ERROR!
        returnData['error_description'] = ""
        if objectShouldBeSaved(deserialized_object, returnData):
            #We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
            deserialized_object.object.id = None
            deserialized_object.object.pk = None
            deserialized_object.save()

        return render_to_json(returnData)
예제 #4
0
def NewsDeleteAPI(request):
	if request.method == 'POST':
		# POST METHOD:
		# Obtengo los parametros del JSON enviado
		information = {}
		if request.get_signed_cookie('user_admin',None) is None:
			api.set_error(information,5,_("You are not allowed to change news"))
			return api.render_to_json(information);
		
		params = api.json_to_dict(request.body)
		
		
		# Si los parametros son invalidos
		if params is None:
			# ERROR PARAMETROS INVALIDOS
			api.set_error(information,6,_("Invalid parameters"))
			return api.render_to_json(information);
		
		# Obtengo la informacon ingresada
		pk = params.get('pk', None)
		if pk is None:
			api.set_error(information,1,_("You must specify a new to delete"))
			return api.render_to_json(information)
		else:
			if New.remove(pk):
				api.set_error(information,0)
			else:
				api.set_error(information,2,_("The new you are trying to delete does not exist"))
		
		return api.render_to_json(information)
	else:
		return HttpResponseNotAllowed(['POST'])
def EventMembershipDeleteAPI(request):
    if request.method == 'POST':
        eventPk = request.POST.get('eventPk')
        userPk = request.POST.get('username')
        returnData = {}
        api.set_error(returnData, 0, _(" "))
        #Revisar esto
        """if request.get_signed_cookie('user_normal',None) is None:
			api.set_error(returnData,5,_("You are not allowed to unsuscribe"))
			return render_to_json(returnData);"""

        if eventPk == None:
            api.set_error(returnData, 1, _("Event not found"))
            return render_to_json(returnData)
        if userPk == None:
            api.set_error(returnData, 2, _("User not found"))
            return render_to_json(returnData)
        else:
            try:
                membership = EventMembership.objects.filter(event=eventPk,
                                                            user=userPk).get()
                membership.delete()
                return render_to_json(returnData)
            except EventMembership.DoesNotExist:
                api.set_error(returnData, 3, _("Membership not found"))
                return render_to_json(returnData)
    else:
        return HttpResponseNotAllowed(['GET'], ['POST'])
예제 #6
0
def EventMembershipDeleteAPI(request):
	if request.method == 'POST':
		eventPk = request.POST.get('eventPk')
		userPk = request.POST.get('username')
		returnData = {}
		api.set_error(returnData,0,_(" "))
		#Revisar esto 
		"""if request.get_signed_cookie('user_normal',None) is None:
			api.set_error(returnData,5,_("You are not allowed to unsuscribe"))
			return render_to_json(returnData);"""
		
		if eventPk == None:
			api.set_error(returnData,1,_("Event not found"))
			return render_to_json(returnData);
		if userPk == None:
			api.set_error(returnData,2,_("User not found"))
			return render_to_json(returnData);
		else:
			try:
				membership = EventMembership.objects.filter(event=eventPk,user=userPk).get()
				membership.delete()
				return render_to_json(returnData);
			except EventMembership.DoesNotExist:
				api.set_error(returnData,3,_("Membership not found"))
				return render_to_json(returnData);
	else:
		return HttpResponseNotAllowed(['GET'],['POST'])
def EventDeleteAPI(request):
    if request.method == 'POST':
        eventPk = request.POST.get('pk')
        returnData = {}
        if request.get_signed_cookie('user_admin', None) is None:
            api.set_error(returnData, 5,
                          _("You are not allowed to change events"))
            return api.render_to_json(returnData)

        if eventPk == None:
            returnData['error-code'] = 1  # Event Not Found!
            returnData['error-description'] = _("Event not found")
            return render_to_json(returnData)
        else:
            try:
                event = Event.objects.filter(pk=eventPk).get()
                event.delete()
                returnData['error-code'] = 0
                returnData['error-description'] = ""
                return render_to_json(returnData)
            except Event.DoesNotExist:
                returnData['error-code'] = 1  # Event Not Found!
                returnData['error-description'] = _("Event not found")
                return render_to_json(returnData)
    else:
        return HttpResponseNotAllowed(['GET'], ['POST'])
def NewsDeleteAPI(request):
    if request.method == 'POST':
        # POST METHOD:
        # Obtengo los parametros del JSON enviado
        information = {}
        if request.get_signed_cookie('user_admin', None) is None:
            api.set_error(information, 5,
                          _("You are not allowed to change news"))
            return api.render_to_json(information)

        params = api.json_to_dict(request.body)

        # Si los parametros son invalidos
        if params is None:
            # ERROR PARAMETROS INVALIDOS
            api.set_error(information, 6, _("Invalid parameters"))
            return api.render_to_json(information)

        # Obtengo la informacon ingresada
        pk = params.get('pk', None)
        if pk is None:
            api.set_error(information, 1,
                          _("You must specify a new to delete"))
            return api.render_to_json(information)
        else:
            if New.remove(pk):
                api.set_error(information, 0)
            else:
                api.set_error(
                    information, 2,
                    _("The new you are trying to delete does not exist"))

        return api.render_to_json(information)
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #9
0
def EventDeleteAPI(request):
	if request.method == 'POST':
		eventPk = request.POST.get('pk')
		returnData = {}
		if request.get_signed_cookie('user_admin',None) is None:
			api.set_error(returnData,5,_("You are not allowed to change events"))
			return api.render_to_json(returnData);
		
		if eventPk == None:
			returnData['error-code'] = 1 # Event Not Found!
			returnData['error-description'] = _("Event not found")
			return render_to_json(returnData);
		else:
			try:
				event = Event.objects.filter(pk=eventPk).get()
				event.delete()
				returnData['error-code'] = 0
				returnData['error-description'] = ""
				return render_to_json(returnData);
			except Event.DoesNotExist:
				returnData['error-code'] = 1 # Event Not Found!
				returnData['error-description'] = _("Event not found")
				return render_to_json(returnData);
	else:
		return HttpResponseNotAllowed(['GET'],['POST'])
예제 #10
0
def EventsByUserAPI(request):
	if request.method == 'GET':
		userPk = request.GET.get('pk')
		try:
			user = User.getByPk(userPk)
			memberships = EventMembership.objects.filter(user=user)
		except:
			returnData = {}
			returnData['error_code'] = 2 # User Not Found!
			returnData['error_description'] = _("User not found")
			return render_to_json(returnData);
	
		if memberships.count() == 0:
			return render_to_json( [] );
		
		retVal = []
		
		for membership in memberships:
			data = Event.objects.filter(pk=membership.event.pk)
			retVal.append( {"eventHead" : data[0].head, "eventBody" : data[0].body, 
							"eventGame" : data[0].game, "eventDate" : str(data[0].date),
							"eventPk" : data[0].pk, "membershipTeamName" : membership.teamName, 
							"membershipPaid" : membership.paid} )
		
		
		response = HttpResponse( json.dumps(retVal), content_type='application/json')
		return response
def EventsByUserAPI(request):
    if request.method == 'GET':
        userPk = request.GET.get('pk')
        try:
            user = User.getByPk(userPk)
            memberships = EventMembership.objects.filter(user=user)
        except:
            returnData = {}
            returnData['error_code'] = 2  # User Not Found!
            returnData['error_description'] = _("User not found")
            return render_to_json(returnData)

        if memberships.count() == 0:
            return render_to_json([])

        retVal = []

        for membership in memberships:
            data = Event.objects.filter(pk=membership.event.pk)
            retVal.append({
                "eventHead": data[0].head,
                "eventBody": data[0].body,
                "eventGame": data[0].game,
                "eventDate": str(data[0].date),
                "eventPk": data[0].pk,
                "membershipTeamName": membership.teamName,
                "membershipPaid": membership.paid
            })

        response = HttpResponse(json.dumps(retVal),
                                content_type='application/json')
        return response
def EventsAPI(request):
    #QUERY ALL EVENTS
    if request.method == 'GET':
        eventPk = request.GET.get('pk')
        #Sin params
        if eventPk == None:
            data_from_query = Event.objects.all()
            if (data_from_query.count() == 0):
                return HttpResponse("", content_type='application/json')

            data = serializers.serialize("json", data_from_query)
            return HttpResponse(data, content_type='application/json')
        else:
            try:
                data = serializers.serialize("json",
                                             Event.objects.filter(pk=eventPk))
                response = HttpResponse(data, content_type='application/json')
                return response
            except Event.DoesNotExist:
                returnData = {}
                returnData['error_code'] = 3  # Event Not Found!
                returnData['error_description'] = _("Event not found")
                return render_to_json(returnData)

    #ADD EVENT
    elif request.method == 'POST':
        returnData = {}

        if request.get_signed_cookie('user_admin', None) is None:
            api.set_error(returnData, 5,
                          _("You are not allowed to change events"))
            return api.render_to_json(returnData)

        returnData['error_code'] = 0  # NO ERROR!
        returnData['error_description'] = ""
        # Obtengo los parametros del JSON enviado
        try:
            for obj in serializers.deserialize("json", request.body):
                deserialized_object = obj.object
        except DeserializationError:  #Lo unico que causa error de deserializacion es el formato de la fecha
            returnData['error_code'] = 1  # ERROR FECHA INVALIDA
            returnData['error_description'] = _("Invalid date")
            return render_to_json(returnData)

        #PK=-1 => ADD
        if (deserialized_object.pk == -1):
            #We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
            deserialized_object.id = None
            deserialized_object.pk = None
            deserialized_object.save()
            return render_to_json(returnData)
        else:
            return editEvent(deserialized_object, returnData)
    else:
        return HttpResponseNotAllowed(['GET'], ['POST'])
예제 #13
0
def EventsAPI(request):
	#QUERY ALL EVENTS
	if request.method == 'GET':
		eventPk = request.GET.get('pk')
		#Sin params
		if eventPk == None:
			data_from_query = Event.objects.all();
			if (data_from_query.count() == 0):
				return HttpResponse("", content_type='application/json')
				
			data = serializers.serialize("json", data_from_query)
			return HttpResponse(data, content_type='application/json')
		else:
			try:
				data = serializers.serialize("json",Event.objects.filter(pk=eventPk))
				response = HttpResponse(data, content_type='application/json')
				return response
			except Event.DoesNotExist:
				returnData = {}
				returnData['error_code'] = 3 # Event Not Found!
				returnData['error_description'] = _("Event not found")
				return render_to_json(returnData);
				
	#ADD EVENT
	elif request.method == 'POST':
		returnData = {}
		
		if request.get_signed_cookie('user_admin',None) is None:
			api.set_error(returnData,5,_("You are not allowed to change events"))
			return api.render_to_json(returnData);
		
		returnData['error_code'] = 0 # NO ERROR!
		returnData['error_description'] = ""
		# Obtengo los parametros del JSON enviado
		try:
			for obj in serializers.deserialize("json", request.body):
				deserialized_object = obj.object
		except DeserializationError: #Lo unico que causa error de deserializacion es el formato de la fecha
			returnData['error_code'] = 1 # ERROR FECHA INVALIDA
			returnData['error_description'] = _("Invalid date")
			return render_to_json(returnData);
		
		#PK=-1 => ADD
		if (deserialized_object.pk==-1):
			#We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
			deserialized_object.id = None
			deserialized_object.pk = None
			deserialized_object.save()	
			return render_to_json(returnData);
		else:
			return editEvent(deserialized_object,returnData)
	else:
		return HttpResponseNotAllowed(['GET'],['POST'])
예제 #14
0
def LogOutAPI(request):
    if request.method == 'GET':
        information = {}
        if request.get_signed_cookie('user_id', None) is None:
            api.set_error(information, 1, _("There is no user logged in"))
            return api.render_to_json(information)
        else:
            api.set_error(information, 0)
            response = api.render_to_json(information)
            response.delete_cookie('user_id')
            return response
    else:
        return HttpResponseNotAllowed(['GET'])
예제 #15
0
def LogOutAPI(request):
    if request.method == 'GET':
        information = {}
        if request.get_signed_cookie('user_id',None) is None:
            api.set_error(information,1,_("There is no user logged in"))
            return api.render_to_json(information)
        else:
            api.set_error(information,0)
            response = api.render_to_json(information)
            response.delete_cookie('user_id')
            return response
    else:
        return HttpResponseNotAllowed(['GET'])
예제 #16
0
def SignInAPI(request):
    if request.method == 'POST':
        # POST METHOD: Aca valido la informacion de inicio de sesion
        params = api.json_to_dict(request.body)
        information = {}

        # Si los parametros son invalidos
        if params is None:
            api.set_error(information, 6, _("Invalid parameters"))
            return api.render_to_json(information)

        information['username'] = params.get('username', '')
        password = params.get('password', '')
        remember = params.get('remember', False)

        valid = User.isValidLogin(information['username'], password)
        if not valid:
            # ERROR NOMBRE DE USUARIO INEXISTENTE O CONTRASENA INCORRECTA
            api.set_error(
                information, 1,
                _("Username does not exist or password is incorrect"))
            return api.render_to_json(information)
        else:
            # NO HUBO ERRORES!
            user = User.getByUsername(information['username'])
            api.set_error(information, 0)
            response = api.render_to_json(information)
            if not remember:
                Crypt.set_secure_cookie(
                    response, 'user_id', information['username'],
                    expires=True)  # Expira al cerrar el navegador
                if user.permission == 'AD':
                    Crypt.set_secure_cookie(
                        response,
                        'user_admin',
                        information['username'] + 'AD',
                        expires=True)  # Expira al cerrar el navegador
            else:
                Crypt.set_secure_cookie(response,
                                        'user_id',
                                        information['username'],
                                        expires=False)  # No expira la cookie
                if user.permission == 'AD':
                    Crypt.set_secure_cookie(
                        response,
                        'user_admin',
                        information['username'] + 'admin',
                        expires=False)  # Expira al cerrar el navegador
            return response
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #17
0
def PasswordRecoverResetAPI(request):
    if request.method == 'GET':
        information = {}
        cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
        if cookie is None:
            api.set_error(information,1,_("You haven't start the password recovery process"))
            return api.render_to_json(information)
        else:
            api.set_error(information,0)
            response = api.render_to_json(information)
            response.delete_cookie('lpwd_ok')
            return response
    else:
        return HttpResponseNotAllowed(['GET'])
def EventMembershipAPI(request):
    #Query the corresponding membership to the passed eventID. Returns the membership in json format
    if request.method == 'GET':
        data = ""
        if 'eventPk' in request.GET.keys():
            eventPk = request.GET['eventPk']
            if 'userPk' in request.GET.keys():
                userPk = request.GET['userPk']
                data = serializers.serialize(
                    "json", EventMembership.getByUserAndEvent(eventPk, userPk))
            else:
                eventPk = request.GET['eventPk']
                data = serializers.serialize(
                    "json", EventMembership.getByEvent(eventPk))
        elif 'userPk' in request.GET.keys():
            userPk = request.GET['userPk']
            data = serializers.serialize("json",
                                         EventMembership.getByUser(userPk))

        response = HttpResponse(data, content_type='application/json')
        return response
    elif request.method == 'POST':
        returnData = {}
        returnData['error_code'] = 0  # NO ERROR!
        returnData['error_description'] = ""
        try:
            for obj in serializers.deserialize("json", request.body):
                deserialized_object = obj.object
        except DeserializationError:
            returnData['error_code'] = 1
            returnData['error_description'] = _("Invalid JSON")
            return render_to_json(returnData)

        if deserialized_object is None:
            returnData['error_code'] = 2  # ERROR objeto vacio
            returnData['error_description'] = _("Invalid parameters")
            return render_to_json(returnData)

        #PK=-1 => ADD
        if (deserialized_object.pk == -1):
            #ADD
            deserialized_object.id = None
            deserialized_object.pk = None
            return addMembership(request, deserialized_object, returnData)
        else:
            #EDIT
            return editMembership(deserialized_object, returnData)
    else:
        return HttpResponseNotAllowed(['GET'], ['POST'])
예제 #19
0
def PasswordRecoverResetAPI(request):
    if request.method == 'GET':
        information = {}
        cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
        if cookie is None:
            api.set_error(information, 1,
                          _("You haven't start the password recovery process"))
            return api.render_to_json(information)
        else:
            api.set_error(information, 0)
            response = api.render_to_json(information)
            response.delete_cookie('lpwd_ok')
            return response
    else:
        return HttpResponseNotAllowed(['GET'])
예제 #20
0
def EventSearchAPI(request):
	if request.method == 'GET':
		all = False
		n = 0
		if 'n' in request.GET.keys():
			try:
				n = int(request.GET['n'])
			except ValueError:
				all = True
		else:
			all = True
		returnData = {}
		try:
			events = Event.objects.all().order_by('-date')
			if all:
				data = serializers.serialize("json", events)
			else:
				data = serializers.serialize("json", events[0:n])
			return HttpResponse(data, content_type='application/json')
		except Event.DoesNotExist:
			returnData['error-code'] = 1 # Event Not Found!
			returnData['error-description'] = _("Event not found")
			return render_to_json(returnData);
	else:
		return HttpResponseNotAllowed(['POST'])
def EventSearchAPI(request):
    if request.method == 'GET':
        all = False
        n = 0
        if 'n' in request.GET.keys():
            try:
                n = int(request.GET['n'])
            except ValueError:
                all = True
        else:
            all = True
        returnData = {}
        try:
            events = Event.objects.all().order_by('-date')
            if all:
                data = serializers.serialize("json", events)
            else:
                data = serializers.serialize("json", events[0:n])
            return HttpResponse(data, content_type='application/json')
        except Event.DoesNotExist:
            returnData['error-code'] = 1  # Event Not Found!
            returnData['error-description'] = _("Event not found")
            return render_to_json(returnData)
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #22
0
def SessionInfoApi(request):
    if request.method == 'GET':
        information = {}
        username = request.get_signed_cookie('user_id', None)
        if username != None:
            user = User.getByUsername(username)
            information['permission'] = user.permission
            information['pk'] = user.pk
            information['username'] = username
            information['loggedIn'] = True
            return api.render_to_json(information)
        else:
            information['loggedIn'] = False
            return api.render_to_json(information)

    else:
        return HttpResponseNotAllowed(['GET'])
예제 #23
0
def EventMembershipAPI(request):
	#Query the corresponding membership to the passed eventID. Returns the membership in json format
	if request.method == 'GET':
		data=""
		if 'eventPk' in request.GET.keys():
			eventPk = request.GET['eventPk']
			if 'userPk' in request.GET.keys():
				userPk = request.GET['userPk']
				data = serializers.serialize("json", EventMembership.getByUserAndEvent(eventPk,userPk))
			else:
				eventPk = request.GET['eventPk']
				data = serializers.serialize("json", EventMembership.getByEvent(eventPk))
		elif 'userPk' in request.GET.keys():
			userPk = request.GET['userPk']
			data = serializers.serialize("json", EventMembership.getByUser(userPk))
			
		response = HttpResponse(data, content_type='application/json')
		return response
	elif request.method == 'POST':
		returnData = {}
		returnData['error_code'] = 0 # NO ERROR!
		returnData['error_description'] = ""
		try:
			for obj in serializers.deserialize("json", request.body):
				deserialized_object = obj.object
		except DeserializationError: 
			returnData['error_code'] = 1 
			returnData['error_description'] = _("Invalid JSON")
			return render_to_json(returnData);
		
		if deserialized_object is None:
			returnData['error_code'] = 2 # ERROR objeto vacio
			returnData['error_description'] = _("Invalid parameters")
			return render_to_json(returnData)
			
		#PK=-1 => ADD
		if (deserialized_object.pk==-1):
			#ADD
			deserialized_object.id = None
			deserialized_object.pk = None
			return addMembership(request,deserialized_object,returnData)
		else:
			#EDIT
			return editMembership(deserialized_object,returnData)
	else:
		return HttpResponseNotAllowed(['GET'],['POST'])
def FeaturesAPI(request):
    if request.method == 'GET':
        featuresList = []
        featuresQuerySet = Feature.getFeatures(3)
        for feature in featuresQuerySet:
            featuresList.append(feature.getDictionary())

        return render_to_json(featuresList)
예제 #25
0
def FeaturesAPI(request):
	if request.method == 'GET':
		featuresList = []
		featuresQuerySet = Feature.getFeatures(3)
		for feature in featuresQuerySet:
			featuresList.append(feature.getDictionary())
		
		return render_to_json(featuresList)
예제 #26
0
def SessionInfoApi(request):
    if request.method == 'GET':
        information = {}
        username = request.get_signed_cookie('user_id',None)
        if username != None:
            user = User.getByUsername(username)
            information['permission'] = user.permission
            information['pk'] = user.pk
            information['username'] = username
            information['loggedIn'] = True
            return api.render_to_json(information);
        else:
            information['loggedIn'] = False
            return api.render_to_json(information);
        
    else: 
        return HttpResponseNotAllowed(['GET'])  
예제 #27
0
def PasswordRecoverFormAPI(request, username):
    if request.method == 'POST':
        # POST METHOD: Realizo la validacion de los datos ingresados y cambio la contrasenia
        information = {}
        params = api.json_to_dict(request.body)

        # Si los parametros son invalidos
        if params is None:
            api.set_error(information, 6, _('Invalid parameters'))
            return api.render_to_json(information)

        cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
        if cookie is None:
            api.set_error(information, 1,
                          _("You haven't start the password recovery process"))
            return api.render_to_json(information)
        else:
            information['username'] = cookie.split('|')[0]
            password = params.get('password', '')
            vpassword = params.get('vpassword', '')
            api.set_error(information, 0)
            if not User.isValidPassword(password):
                # Marco el error de password invaludo
                api.set_error(information, 2, _("Invalid password"))
            elif password != vpassword:
                # Marco el error de passwords distintas
                api.set_error(information, 3, _("Passwords don't match"))
            else:
                user = User.getByUsername(information['username'])
                if user is None:
                    # Marco el error de usuario inexistente
                    api.set_error(information, 4, _("Username does not exist"))

            if information['error-code'] != 0:
                # Hubo errores
                return api.render_to_json(information)
            else:
                # TODO OK!!
                user.updateUserPassword(password)
                response = api.render_to_json(information)
                response.delete_cookie('lpwd_ok')
                return response

    else:
        return HttpResponseNotAllowed(['POST'])
def NewsViewerAPI(request):
    if request.method == 'GET':
        information = {}
        newpk = request.GET.get('pk', None)
        if newpk is None:
            api.set_error(information, 1, _("No new was specify"))
            return api.render_to_json(information)
        try:
            new = New.objects.filter(pk=newpk).get()
        except:
            api.set_error(information, 2, _("The new does not exist"))
            return api.render_to_json(information)

        information = new.toDic()
        api.set_error(information, 0, '')
        return api.render_to_json(information)
    else:
        return HttpResponseNotAllowed(['GET'])
예제 #29
0
def NewsViewerAPI(request):
	if request.method == 'GET':
		information = {}
		newpk = request.GET.get('pk',None)
		if newpk is None:
			api.set_error(information,1,_("No new was specify"))
			return api.render_to_json(information)
		try:
			new = New.objects.filter(pk=newpk).get()
		except:
			api.set_error(information,2,_("The new does not exist"))
			return api.render_to_json(information)
		
		information = new.toDic()
		api.set_error(information,0,'')
		return api.render_to_json(information)
	else:
		return HttpResponseNotAllowed(['GET'])
예제 #30
0
def PasswordRecoverFormAPI(request, username):
    if request.method == 'POST':
        # POST METHOD: Realizo la validacion de los datos ingresados y cambio la contrasenia
        information = {}
        params = api.json_to_dict(request.body)
        
        # Si los parametros son invalidos
        if params is None:
                api.set_error(information,6,_('Invalid parameters'))
                return api.render_to_json(information);
        
        cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
        if cookie is None:
            api.set_error(information,1,_("You haven't start the password recovery process"))
            return api.render_to_json(information)
        else:
            information['username'] = cookie.split('|')[0]
            password = params.get('password', '')
            vpassword = params.get('vpassword', '')
            api.set_error(information,0)
            if not User.isValidPassword(password):
                # Marco el error de password invaludo
                api.set_error(information,2,_("Invalid password"))
            elif password != vpassword:
                # Marco el error de passwords distintas
                api.set_error(information,3,_("Passwords don't match"))
            else:
                user = User.getByUsername(information['username'])
                if user is None:
                    # Marco el error de usuario inexistente
                    api.set_error(information,4,_("Username does not exist"))
                    
            if information['error-code'] != 0:
                # Hubo errores
                return api.render_to_json(information)
            else:
                # TODO OK!!
                user.updateUserPassword(password)
                response = api.render_to_json(information)
                response.delete_cookie('lpwd_ok')
                return response
                
    else:
        return HttpResponseNotAllowed(['POST'])
def editEvent(obj, returnData):
    try:
        event = Event.objects.get(pk=obj.pk)
        event = obj
        event.save()
    except Event.DoesNotExist:
        returnData['error_code'] = 2  # ERROR event not found
        returnData['error_description'] = _("Invalid event key")

    return render_to_json(returnData)
예제 #32
0
def editEvent(obj,returnData):
	try:
		event = Event.objects.get(pk=obj.pk)
		event = obj
		event.save()
	except Event.DoesNotExist:
		returnData['error_code'] = 2 # ERROR event not found
		returnData['error_description'] = _("Invalid event key")
	
	return render_to_json(returnData)
def editMembership(obj, returnData):
    try:
        cookie_value = request.get_signed_cookie(key='user_id', default=None)
        membership = EventMembership.objects.get(pk=obj.pk)
        membership = obj
        membership.save()
    except EventMembership.DoesNotExist:
        returnData['error_code'] = 5  # ERROR membership not found
        returnData['error_description'] = _("Invalid membership key")

    return render_to_json(returnData)
예제 #34
0
def UserEditProfile(request):
	returnData = {}

	# Obtengo los parametros del JSON enviado
	try:
		deserialized_object = json.loads(request.body)[0]
	except DeserializationError: 
		returnData['error_code'] = 1 
		returnData['error_description'] = _("Error en la deserializacion del usuario")
		return render_to_json(returnData);
	
	#PK=-1 => ADD
	if (deserialized_object[u'username']==-1):
		#We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
		deserialized_object.id = None
		deserialized_object.pk = None
		deserialized_object.save()	
		return render_to_json(returnData);
	else:
		return userEdit(deserialized_object,returnData)
예제 #35
0
def addMembership(request,obj,returnData):
	cookie_value = request.get_signed_cookie(key='user_id', default=None)
	user = User.getByUsername(cookie_value)
	if user is None:
		returnData['error_code'] = 3 # ERROR invalid user
		returnData['error_description'] = _("Invalid user")
		return render_to_json(returnData)

	try:
		event = Event.objects.filter(pk=obj.event.pk)[0]
	except Event.DoesNotExist:
		returnData['error_code'] = 4 # ERROR invalid event
		returnData['error_description'] = _("Invalid event")
		return render_to_json(returnData)
		
	memb = obj
	memb.user=user
	memb.event = event		
	
	memb.save()
	return render_to_json(returnData)
예제 #36
0
def UserEditProfile(request):
    returnData = {}

    # Obtengo los parametros del JSON enviado
    try:
        deserialized_object = json.loads(request.body)[0]
    except DeserializationError:
        returnData['error_code'] = 1
        returnData['error_description'] = _(
            "Error en la deserializacion del usuario")
        return render_to_json(returnData)

    #PK=-1 => ADD
    if (deserialized_object[u'username'] == -1):
        #We set the objects id's to None to create a new entry. (DJANGO 1.5.X BUG)
        deserialized_object.id = None
        deserialized_object.pk = None
        deserialized_object.save()
        return render_to_json(returnData)
    else:
        return userEdit(deserialized_object, returnData)
def addMembership(request, obj, returnData):
    cookie_value = request.get_signed_cookie(key='user_id', default=None)
    user = User.getByUsername(cookie_value)
    if user is None:
        returnData['error_code'] = 3  # ERROR invalid user
        returnData['error_description'] = _("Invalid user")
        return render_to_json(returnData)

    try:
        event = Event.objects.filter(pk=obj.event.pk)[0]
    except Event.DoesNotExist:
        returnData['error_code'] = 4  # ERROR invalid event
        returnData['error_description'] = _("Invalid event")
        return render_to_json(returnData)

    memb = obj
    memb.user = user
    memb.event = event

    memb.save()
    return render_to_json(returnData)
예제 #38
0
def userEdit(obj, returnData):
    try:
        user = User.objects.get(pk=obj[u'username'])
        user.firstname = obj[u'firstname']
        user.lastname = obj[u'lastname']
        user.email = obj[u'email']
        user.save()
    except User.DoesNotExist:
        returnData['error_code'] = 2
        returnData['error_description'] = _("User not found")

    return render_to_json(returnData)
예제 #39
0
def editMembership(obj,returnData):
	try:
		cookie_value = request.get_signed_cookie(key='user_id', default=None)
		membership = EventMembership.objects.get(pk=obj.pk)
		membership = obj
		membership.save()
	except EventMembership.DoesNotExist:
		returnData['error_code'] = 5 # ERROR membership not found
		returnData['error_description'] = _("Invalid membership key")
	
	
	return render_to_json(returnData)
예제 #40
0
def PasswordRecoverAPI(request):
    information = {}
    cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
    if request.method == 'GET':
        # GET METHOD: Si la cookie ya esta seteada, informo que ya esta en "tramite" el cambio de clave
        # si no esta seteada, leo los parametros, los valido.
        # En caso de ser parametos validos, seteo la cookie, envio el mail de recuperacion y informo el exito
        if cookie is None:
            information['recover-cookie'] = False
            return api.render_to_json(information)
        else:
            information['username'] = cookie.split('|')[0]
            information['email'] = cookie.split('|')[1]
            information['recover-cookie'] = True
            return api.render_to_json(information)
    
    elif request.method == 'POST':
        # POST METHOD: Si la cookie ya esta seteada, informo que ya esta en "tramite" el cambio de clave
        # si no esta seteada, informo lo contrario.
        if cookie != None:
            api.set_error(information,1,_("We have already send a password recovery email for your username."))
            return api.render_to_json(information)
        else:
            
            params = api.json_to_dict(request.body)
            if params is None:
                # ERROR PARAMETROS INVALIDOS
                api.set_error(information,6,_('Invalid parameters'))
                return api.render_to_json(information);
            
            information['username'] = params.get('username', None)
            
            if not User.isValidUsername(information['username']):
                api.set_error(information,2,_('Invalid username'))
                return api.render_to_json(information)
            
            else:
                user = User.getByUsername(information['username'])
                
                if user is None:
                    api.set_error(information,3,_("You haven't start the password recovery process"))
                    return api.render_to_json(information)
                
                else:
                    information['email'] = user.email;
                    api.set_error(information,0)
                    
                    response = api.render_to_json(information)
                    Crypt.set_secure_cookie(response,'lpwd_ok',information['username']+ '|' + information['email'] , expires=False,  time=7200)
                    api.sendRecoveryEmail(user);
                    return response
                
            return render_to_response('passwd_recover.html',information,RequestContext(request))
    else:
        return HttpResponseNotAllowed(['POST','GET'])
예제 #41
0
def userEdit(obj,returnData):
	try:
		user = User.objects.get(pk=obj[u'username'])
		user.firstname = obj[u'firstname']
		user.lastname = obj[u'lastname']
		user.email = obj[u'email']
		user.save()
	except User.DoesNotExist:
		returnData['error_code'] = 2 
		returnData['error_description'] = _("User not found")
	
	return render_to_json(returnData)
        
예제 #42
0
def SignInAPI(request):
    if request.method == 'POST':
        # POST METHOD: Aca valido la informacion de inicio de sesion
        params = api.json_to_dict(request.body)
        information = {}
    
        # Si los parametros son invalidos
        if params is None:
            api.set_error(information,6,_("Invalid parameters"))
            return api.render_to_json(information);
        
        information['username'] = params.get('username', '')
        password = params.get('password', '')
        remember = params.get('remember',False)
        
        valid = User.isValidLogin(information['username'], password)
        if not valid:
            # ERROR NOMBRE DE USUARIO INEXISTENTE O CONTRASENA INCORRECTA
            api.set_error(information,1,_("Username does not exist or password is incorrect"))
            return api.render_to_json(information)
        else:
            # NO HUBO ERRORES!
            user = User.getByUsername(information['username'])
            api.set_error(information,0)
            response = api.render_to_json(information)
            if not remember:
                Crypt.set_secure_cookie(response,'user_id',information['username'],expires=True) # Expira al cerrar el navegador
                if user.permission == 'AD':
                    Crypt.set_secure_cookie(response,'user_admin',information['username']+'AD',expires=True) # Expira al cerrar el navegador
            else:
                Crypt.set_secure_cookie(response,'user_id',information['username'],expires=False) # No expira la cookie
                if user.permission == 'AD':
                    Crypt.set_secure_cookie(response,'user_admin',information['username']+'admin',expires=False) # Expira al cerrar el navegador
            return response
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #43
0
def UserProfileAPI(request, username):
    information = {}
    cookie_value = request.get_signed_cookie(key='user_id', default=None)
    if request.method == 'GET':
        # GET METHOD: Devuelve la informacion del usuario recibido en el parametro user.
        # Si la cookie de sesion no esta seteada devuelve error
        if cookie_value is None:
            api.set_error(information, 1, _("You are not logged in"))
            return api.render_to_json(information)
        else:
            if username is None:
                api.set_error(information, 2,
                              _("You haven't specified the username"))
                return api.render_to_json(information)

            user = User.getByUsername(username)

            if user is None:
                api.set_error(information, 3, _("User does not exist"))
                return api.render_to_json(information)

            api.set_error(information, 0)
            information = dict(information.items() + user.toDic().items())
            return api.render_to_json(information)

    elif request.method == 'POST':
        # POST METHOD: Cambia la informacion del usuario. Si el usuario no es el que inicio sesion esto no podra llevarse a cabo
        params = api.json_to_dict(request.body)
        if params is None:
            # ERROR PARAMETROS INVALIDOS
            api.set_error(information, 6, _('Invalid parameters'))
            return api.render_to_json(information)

        if cookie_value == None:
            api.set_error(information, 1, _("You are not logged in"))
            return api.render_to_json(information)
        else:
            if username != cookie_value:
                api.set_error(
                    information, 2,
                    _("You don't have permision to change this data"))
                return api.render_to_json(information)

            user = User.getByUsername(username)
            if user is None:
                api.set_error(information, 3, _("User does not exist"))
                return api.render_to_json(information)

            email = params.get('email', None)
            password = params.get('password', None)
            vpassword = params.get('vpassword', None)
            firstname = params.get('firstname', None)
            lastname = params.get('lastname', None)

            if email != None:
                if not User.isValidEmail(email):
                    api.set_error(information, 4, _('Invalid email'))
                    return api.render_to_json(information)
                else:
                    user.updateUserEmail(email)  # Must save after update

            if firstname != None:
                user.updateUserFirstname(firstname)  # Must save after update
            if lastname != None:
                user.updateUserLastname(lastname)  # Must save after update

            if password != None:
                if not User.isValidPassword(password):
                    api.set_error(information, 5, _('Invalid password'))
                    return api.render_to_json(information)
                elif password != vpassword:
                    # Marco el error de passwords distintas
                    # ERROR CLAVES NO SON IDENTICAS
                    api.set_error(information, 7, _("Passwords don't match"))
                    return api.render_to_json(information)
                else:
                    user.updateUserPassword(password)  # Must save after update

            user.save()
            api.set_error(information, 0)
            return api.render_to_json(information)
    else:
        return HttpResponseNotAllowed(['POST', 'GET'])
예제 #44
0
def SignUpAPI(request):
    if request.method == 'POST':
        # POST METHOD: Aca valido la informacion de creacion de usuario
        # Obtengo los parametros del JSON enviado
        params = api.json_to_dict(request.body)
        information = {}

        # Si los parametros son invalidos
        if params is None:
            # ERROR PARAMETROS INVALIDOS
            api.set_error(information, 6, _("Invalid parameters"))
            return api.render_to_json(information)

        # Obtengo la informacon ingresada
        information['username'] = params.get('username', '')
        password = params.get('password', '')
        vpassword = params.get('vpassword', '')
        information['email'] = params.get('email', '')
        information['name'] = params.get('name', '')
        information['lastname'] = params.get('lastname', '')
        information['country'] = params.get('country', '')
        # NO ERROR!
        api.set_error(information, 0)
        leave_open = params.get('remember', None)

        # Valido los datos.
        if not User.isValidUsername(information['username']):
            # ERROR NOMBRE DE USUARIO INVALIDO
            api.set_error(information, 1, _("Invalid username"))
        elif not User.isValidPassword(password):
            # Marco el error de password invaludo
            # ERROR CLAVE INVALIDA
            api.set_error(information, 2, _("Invalid password"))
        elif password != vpassword:
            # Marco el error de passwords distintas
            # ERROR CLAVES NO SON IDENTICAS
            api.set_error(information, 3, _("Passwords don't match"))
        elif not User.isValidEmail(information['email']):
            # Marco el error de password invaludo
            # ERROR EMAIL INVALIDO
            api.set_error(information, 4, _('Invalid mail'))
        else:
            user = User.add(information['username'], password,
                            information['email'], information['name'],
                            information['lastname'])
            if user == None:
                # Marco el error de usuario ya existente
                # ERROR USUARIO YA EXISTE
                api.set_error(information, 5, _("Username already exists"))

        if information['error-code'] != 0:
            # Hubo un error al crear el usuario. Envio el diccionario en formato json
            return api.render_to_json(information)
        else:
            # Se creo un usuario, redirijo pero seteo la cookie para identificar
            response = api.render_to_json(information)
            Crypt.set_secure_cookie(
                response, 'user_id', information['username'],
                expires=True)  # Expira al cerrar el navegador
            return response
    else:
        return HttpResponseNotAllowed(['POST'])
예제 #45
0
def UserProfileAPI(request, username):
    information={}
    cookie_value = request.get_signed_cookie(key='user_id', default=None)
    if request.method == 'GET':
        # GET METHOD: Devuelve la informacion del usuario recibido en el parametro user.
        # Si la cookie de sesion no esta seteada devuelve error
        if cookie_value is None:
            api.set_error(information,1,_("You are not logged in"))
            return api.render_to_json(information)
        else:
            if username is None:
                api.set_error(information,2,_("You haven't specified the username"))
                return api.render_to_json(information)
            
            user = User.getByUsername(username)
            
            if user is None:
                api.set_error(information,3,_("User does not exist"))
                return api.render_to_json(information);
            
            api.set_error(information,0)
            information = dict(information.items() + user.toDic().items())
            return api.render_to_json(information);

    elif request.method == 'POST':
        # POST METHOD: Cambia la informacion del usuario. Si el usuario no es el que inicio sesion esto no podra llevarse a cabo
        params = api.json_to_dict(request.body)
        if params is None:
            # ERROR PARAMETROS INVALIDOS
            api.set_error(information,6,_('Invalid parameters'))
            return api.render_to_json(information);
        
        if cookie_value == None:
            api.set_error(information,1,_("You are not logged in"))
            return api.render_to_json(information)
        else:
            if username != cookie_value:
                api.set_error(information,2,_("You don't have permision to change this data"))
                return api.render_to_json(information);
        
    
            user = User.getByUsername(username)
            if user is None:
                api.set_error(information,3,_("User does not exist"))
                return api.render_to_json(information);
            
            email = params.get('email', None)
            password = params.get('password', None)
            vpassword = params.get('vpassword', None)
            firstname = params.get('firstname', None)
            lastname = params.get('lastname', None)
            
            if email != None:
                if not User.isValidEmail(email):
                    api.set_error(information,4,_('Invalid email'))
                    return api.render_to_json(information);
                else:
                    user.updateUserEmail(email) # Must save after update
            
            if firstname != None:
                user.updateUserFirstname(firstname) # Must save after update
            if lastname != None:
                user.updateUserLastname(lastname) # Must save after update
            
            if password != None:
                if not User.isValidPassword(password):
                    api.set_error(information,5,_('Invalid password'))
                    return api.render_to_json(information);
                elif password != vpassword:
                    # Marco el error de passwords distintas
                    # ERROR CLAVES NO SON IDENTICAS
                    api.set_error(information,7,_("Passwords don't match"))
                    return api.render_to_json(information);             
                else:
                    user.updateUserPassword(password) # Must save after update
            
            user.save()
            api.set_error(information,0)
            return api.render_to_json(information)
    else:
        return HttpResponseNotAllowed(['POST','GET'])
def NewsAPI(request):
    if request.method == 'GET':
        begin = request.GET.get('begin', 0)
        end = request.GET.get('end', 10)
        information = {}
        news = New.getList(begin, end)
        return api.render_to_json(map(New.toDic, news))
    elif request.method == 'POST':
        # POST METHOD:
        # Obtengo los parametros del JSON enviado
        information = {}
        admin = request.get_signed_cookie('user_admin', None)
        if admin is None:
            api.set_error(information, 5,
                          _("You are not allowed to change news"))
            return api.render_to_json(information)

        params = api.json_to_dict(request.body)

        # Si los parametros son invalidos
        if params is None:
            # ERROR PARAMETROS INVALIDOS
            api.set_error(information, 6, _("Invalid parameters"))
            return api.render_to_json(information)

        # Obtengo la informacon ingresada
        pk = params.get('pk', None)
        information['header'] = params.get('header', '')
        information['subheader'] = params.get('subheader', '')
        information['body'] = params.get('body', '')
        information['image'] = params.get('image', '')
        # NO ERROR!
        api.set_error(information, 0)

        # Valido los datos.
        if information['header'] == '':
            # ERROR TITULO EN BLANCO
            api.set_error(information, 1, _("Header can't be blank"))
        elif information['image'] == '':
            # ERROR IMAGEN EN BLANCO
            api.set_error(information, 2, _("Image can't be blank"))
        else:
            if pk is None:
                new = New.add(information['header'], information['subheader'],
                              information['body'], information['image'])
            else:
                try:
                    new = New.objects.filter(pk=pk).get()
                except:
                    api.set_error(
                        information, 4,
                        _("The new you are trying to edit does not exist"))
                    return api.render_to_json(information)
                new.updateHeader(information['header'])
                new.updateSubHeader(information['subheader'])
                new.updateBody(information['body'])
                new.updateImage(information['image'])
                new.save()

            if new == None:
                # ERROR AL CREAR NOTICIA
                api.set_error(information, 3, _("Error creating new"))

        return api.render_to_json(information)
    else:
        return HttpResponseNotAllowed(['POST', 'GET'])
예제 #47
0
def NewsAPI(request):
	if request.method == 'GET':
		begin = request.GET.get('begin',0)
		end = request.GET.get('end',10)
		information = {}
		news = New.getList(begin,end)
		return api.render_to_json(map(New.toDic,news))
	elif request.method == 'POST':
		# POST METHOD:
		# Obtengo los parametros del JSON enviado
		information = {}
		admin = request.get_signed_cookie('user_admin',None)
		if admin is None:
			api.set_error(information,5,_("You are not allowed to change news"))
			return api.render_to_json(information);
				
		params = api.json_to_dict(request.body)
		
		# Si los parametros son invalidos
		if params is None:
			# ERROR PARAMETROS INVALIDOS
			api.set_error(information,6,_("Invalid parameters"))
			return api.render_to_json(information);
		
		# Obtengo la informacon ingresada
		pk = params.get('pk', None)
		information['header'] = params.get('header', '')
		information['subheader'] = params.get('subheader', '')
		information['body'] = params.get('body', '')
		information['image'] = params.get('image', '')
		# NO ERROR!
		api.set_error(information,0)
		
		# Valido los datos.
		if information['header'] == '':
			# ERROR TITULO EN BLANCO
			api.set_error(information,1,_("Header can't be blank"))
		elif information['image'] == '':
			# ERROR IMAGEN EN BLANCO
			api.set_error(information,2,_("Image can't be blank"))
		else:
			if pk is None:
				new = New.add(information['header'],information['subheader'],information['body'],information['image'])
			else:
				try:
					new = New.objects.filter(pk=pk).get()
				except:
					api.set_error(information,4,_("The new you are trying to edit does not exist"))
					return api.render_to_json(information);
				new.updateHeader(information['header'])
				new.updateSubHeader(information['subheader'])
				new.updateBody(information['body'])
				new.updateImage(information['image'])
				new.save()
					
			if  new == None:
				# ERROR AL CREAR NOTICIA
				api.set_error(information,3,_("Error creating new"))
				
		return api.render_to_json(information);
	else:
		return HttpResponseNotAllowed(['POST','GET'])
예제 #48
0
def PasswordRecoverAPI(request):
    information = {}
    cookie = request.get_signed_cookie(key='lpwd_ok', default=None)
    if request.method == 'GET':
        # GET METHOD: Si la cookie ya esta seteada, informo que ya esta en "tramite" el cambio de clave
        # si no esta seteada, leo los parametros, los valido.
        # En caso de ser parametos validos, seteo la cookie, envio el mail de recuperacion y informo el exito
        if cookie is None:
            information['recover-cookie'] = False
            return api.render_to_json(information)
        else:
            information['username'] = cookie.split('|')[0]
            information['email'] = cookie.split('|')[1]
            information['recover-cookie'] = True
            return api.render_to_json(information)

    elif request.method == 'POST':
        # POST METHOD: Si la cookie ya esta seteada, informo que ya esta en "tramite" el cambio de clave
        # si no esta seteada, informo lo contrario.
        if cookie != None:
            api.set_error(
                information, 1,
                _("We have already send a password recovery email for your username."
                  ))
            return api.render_to_json(information)
        else:

            params = api.json_to_dict(request.body)
            if params is None:
                # ERROR PARAMETROS INVALIDOS
                api.set_error(information, 6, _('Invalid parameters'))
                return api.render_to_json(information)

            information['username'] = params.get('username', None)

            if not User.isValidUsername(information['username']):
                api.set_error(information, 2, _('Invalid username'))
                return api.render_to_json(information)

            else:
                user = User.getByUsername(information['username'])

                if user is None:
                    api.set_error(
                        information, 3,
                        _("You haven't start the password recovery process"))
                    return api.render_to_json(information)

                else:
                    information['email'] = user.email
                    api.set_error(information, 0)

                    response = api.render_to_json(information)
                    Crypt.set_secure_cookie(response,
                                            'lpwd_ok',
                                            information['username'] + '|' +
                                            information['email'],
                                            expires=False,
                                            time=7200)
                    api.sendRecoveryEmail(user)
                    return response

            return render_to_response('passwd_recover.html', information,
                                      RequestContext(request))
    else:
        return HttpResponseNotAllowed(['POST', 'GET'])