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 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 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'])
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'])
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'])
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'])
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'])
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'])
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 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 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 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 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'])
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'])
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'])
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'])
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'])
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 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 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'])
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'])
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'])
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'])
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 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'])