Send an email alert after registering django

Im sending a confirmation email after the registration process in my django app. I need to find out, for security reasons, how I can verify the im code sending the URL without adding a new code field to the user model. So far I am sending random code in the url and username, which is verified, but not the code.

Register VIEW

def registrar_usuario_view(request): alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" code = ''.join(random.choice(alphabet) for i in range(16)) print code if request.method == 'POST': f = RegisterForm(request.POST) if f.is_valid(): usuario = f.cleaned_data['usuario'] email = f.cleaned_data['email'] clave = f.cleaned_data['clave'] confirmar_clave = f.cleaned_data['confirmar_clave'] captcha = f.cleaned_data['captcha'] u = User.objects.create_user(username = usuario, email = email, password = clave) u.is_active = False u.save() # Mandamos mail de activacion to = email html_content = """<h3>Bienvenido Sr/a: %s </h3><p>Para confirmar su registro en el sitio Margonari Servicios Inmobiliarios le solicitamos haga click en el siguiente <a href='http://localhost:8000/confirmacion/%s/%s'>enlace de confirmacion</a><br><p><b>Gracias por formar parte de Margonari Servicios Inmobiliarios.</b></p><br> <small>Este es un mensaje enviado automaticamente. Por favor no responda a esta direccion de mail.</small>"""%(usuario, code, usuario) msg = EmailMultiAlternatives('Administracion Margonari', html_content, ' from@server.com ', [to]) msg.attach_alternative(html_content, 'text/html') #Definimos el contenido como html msg.send() #Enviamos el correo messages.add_message(request, messages.SUCCESS, """Los datos han sido ingresados correctamente. Le enviamos un correo de confirmacion a la direccion que nos proporciono. Por favor verifique su casilla de correo no deseado. Muchas gracias.""") ctx = {'form':f} return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request)) else: ctx = {'form':f} return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request)) f = RegisterForm() ctx = {'form':f} return render_to_response('users/registrar_usuario.html', ctx, context_instance = RequestContext(request)) 

VIEW CONFIRMATION

 def confirmacion_view(request, code, user): user = User.objects.get(username = user) user.is_active = True user.save() return HttpResponseRedirect('/') 

URL

 url(r'^confirmacion/(?P<code>.*)/(?P<user>.*)/$', 'confirmacion_view', name = 'vista_confirmacion'), 
+6
source share
1 answer

Django provides a mechanism for creating tokens; there is no need to reinvent the wheel. Since I don’t use function-based representations, and I don’t need to reorganize your code here (I would do it in CBVs), I will just give a sample on how you can use it.

 from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes new_user = User.objects.create_user(username=usuario, email=email, password=clave) new_user.save() token = default_token_generator.make_token(new_user) uid = urlsafe_base64_encode(force_bytes(new_user.pk)) 

Then you can send the token to the user, the token should look like this:

 url(r'^users/validate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activationview, name='user-activation-link') 

Somewhere in your activation window:

 from django import http uidb64 = request.GET.get('uidb64') token = request.GET.get('token') if uidb64 is not None and token is not None: from django.utils.http import urlsafe_base64_decode uid = urlsafe_base64_decode(uidb64) try: from django.contrib.auth import get_user_model from django.contrib.auth.tokens import default_token_generator user_model = get_user_model() user = user_model.objects.get(pk=uid) if default_token_generator.check_token(user, token) and user.is_active == 0: # Do success stuff... return http.HttpResponseRedirect(a_success_url) except: pass return http.HttpResponseRedirect(a_failure_url) 
+9
source

Source: https://habr.com/ru/post/973778/


All Articles