Authentication system in the forum application #5: Activate the user with a verification link and Decode token

in #utopian-io6 years ago

Repository

https://github.com/python

What Will I Learn?

  • Activate the user with a verification link
  • Decode token and make the user profile

Requirements

  • Basic Python
  • Install Python 3
  • Install Django

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the previous tutorial series, this tutorial is still related to the forum application with Django. as you know we have learned a lot in the forum application. well, in this tutorial series we focus on the authentication system. In the previous tutorial, we have successfully sent an email from our local server with help from mailtrap.io, you can see the configuration and how to implement it in our application in the previous tutorial. In this tutorial, we will continue to send the email feature, via the email that we send. we will receive an activation link. We just start this tutorial.

Activate the user with a verification link

In the previous section, we have sent a verification link to the user's email. now our job is to create a function that creates a verification link that can change the value of active_user. for those of you who don't know the verification link I mean, you can see the picture below:

Screenshot_6.png

As you can see in the picture above we will use the link to verify the user. The link contains tokens that we will use for activation. If we can see the URL that will be accessed, we can see that there is some data that is passed at the URL

Example:

http://127.0.0.1:8000/accounts/activate/b'MTA'/55v-941bae90549060219693

We can see the URL above our domain is http://127.0.0.1:8000 and the URL is /accounts/activate/ at this URL we have passed parameters such as the path we defined in the previous tutorial.

Screenshot_7.png

We can use these parameters for us to use as activating the user in the backend. We will use the uid parameter and the token in the activate() function as we defined it in the URL.

Make a activate() function

We have defined the activate() function in the URL. This function will be used to activate the user based on the activation link that we have sent to the user's email. Of course, the activation link is different for each user. In this section, we will make the function. we can see in the example below:

account/views.py

from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_text
from django.contrib.auth.models import User

def Activate(request, uidb64, token):
    uid = force_text(urlsafe_base64_decode(uidb64).decode())
    user = User.objects.get(pk=uid)

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_validated = True
        user.save()
        return redirect(reverse('home'))

From the code above we will do many things. I will describe the following one by one:

  • Accept parameter
    As I said before in this function we will receive two parameters, uidb64 and token. later uidb4 will be used to identify users and token will be used to view user data.

  • Decode token

Then after we receive the parameters given, we will start using tokens to view user data. but before that we will decode the token Because when the token is generated we encode user data, we can see in the picture below:

Screenshot_8.png

to decode a token we can use the urlsafe_base64_decode () function, to use this function, we must import it first from the module django.utils.http and import it like this from django.utils.http import urlsafe_base64_decode. After decoding we will use the results in string form so we can use force_text () well to use the force_text () function you also have to import it like this from django.utils.encoding import force_bytes, force_text.

  • Get user data

Well after we get the user data that we have decoded then we can retrieve the data based on uid, like the following User.objects.get(pk=uid). Well to retrieve user data we need access to the model, so we must first import the model from django.contrib.auth.models import User. e import with the User name then we can use User.objects.get(pk=uid) With the get () function and we oper something unique from the user model, the uid get(pk=uid).

  • Check the token

Now our task has been completed with the uidb64 parameter, now we will use the token parameters to check whether the token is valid. So we will use 2 checks, the first we will check whether the account exists user is not None and then we will check whether the token is valid account_activation_token.check_token(user, token). If both of these conditions are true that means our features are running well.
to check the token we can use check_token () in this function we will pass the two parameters. the first is data to be checked user and the second is token token.

  • Change active user to true

As I have said several times, the purpose of activating users via email is to make active_user TRUE. active_user will be our reference to distinguish between verified and unverified users. to make the user verified we only need to change the is_active key to TRUE such as the following user.is_active = TRUE.

  • Verify email

After verifying the user, we will also verify the email. The verification that we will use is changing the email_validated key in the class model profile to TRUE as follows user.profile.email_validated = TRUE.

Screenshot_9.png

Well after that we will save the user with the user.save () function. After we complete our assignment, we will try to send an email to the new user when he has registered. the following is the demonstration:

The user gets a verification email after registering:

ezgif.com-video-to-gif (3).gif

We can see the user gets an activation link, now we will open the activation link and we will see the results whether the user is active. the following is the demonstration:

Screenshot_11.png

We can see in the picture above we get an error message on our application, this is because when we want to set email_validate to True user.profile.email_validated = True we don't have data in the user profile.

Save the profile module

We will save the profile when we have activated it to avoid the error we saw in the previous section. For that we will add a function to store the user profile in the model class, for more details we can see the example below:

forums/models.py


from django.dispatch import receiver // import receiver
from django.db.models.signals import post_save // import post_save

class Profile(models.Model):
    user    = models.OneToOneField(User, on_delete=models.CASCADE)
    activation_key  = models.CharField(max_length=255, default=1)
    email_validated = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username
## Receiver
@receiver(post_save, sender=User, dispatch_uid="save_new_user_profile")
def save_profile(sender, instance, created, **kwargs):
    user = instance
    if created:
        profile = Profile(user=user)
        profile.save()
  • Well, what you need to pay attention to is here we will receive @receiver (). We will receive sender = User. After we receive the parameter in @reciever () we will create a function to save the save_profile () profile. but we must import the receiver like this from django.dispatch import receiver.

  • We can use help from post_save to get the data posted. before using it we must import it first from django.db.models.signals import post_save. In this function, we will receive 4 parameters, namely sender, instance, created, **kwargs.

  • I will use the instance parameter to access the user that has been created user = instance and use the created parameter to check whether the user has been made or not, If it is already created we will save the profile profile.save().

Curriculum

  • Forum app

django#1, django#2, django#3, django#4, django#5, django#6, django#7, django#8, django#8, django#9, django#10, django#11

Proof of work done

https://github.com/milleaduski/forums-django

Sort:  

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 8000 upvotes. Your next target is to reach 9000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.16
TRX 0.17
JST 0.029
BTC 69895.86
ETH 2516.56
USDT 1.00
SBD 2.54