<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ronak Chitlangya on Medium]]></title>
        <description><![CDATA[Stories by Ronak Chitlangya on Medium]]></description>
        <link>https://medium.com/@ronakchitlangya1997?source=rss-1e6d9a36feee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SI3Zj2nklRXrpLk2yvR57A.jpeg</url>
            <title>Stories by Ronak Chitlangya on Medium</title>
            <link>https://medium.com/@ronakchitlangya1997?source=rss-1e6d9a36feee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:06:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ronakchitlangya1997/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pytest — A beginner Guide]]></title>
            <link>https://medium.com/@ronakchitlangya1997/pytest-a-beginner-guide-f9d4919cd427?source=rss-1e6d9a36feee------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9d4919cd427</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[pytest]]></category>
            <dc:creator><![CDATA[Ronak Chitlangya]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 11:29:21 GMT</pubDate>
            <atom:updated>2023-07-17T11:29:21.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pytest — A beginner Guide</h3><p>We shall learn about the Python-based Test Framework in this tutorial. Automated testing is supported by a number of Python frameworks and packages. However, we shall learn about Pytest in this article.</p><blockquote><strong><em>Pytest</em></strong><em> </em><strong><em>-</em></strong></blockquote><p>One of the most popular Python-based testing frameworks is Pytest, an open-source testing framework. Unit testing, functional testing, and API testing are all supported by pytest. You will want Python 3.5 or later to run it.</p><blockquote><strong><em>Installation -</em></strong></blockquote><pre>pip install pytest</pre><p>That’s it, pytest is installed.</p><blockquote><strong><em>Pytest syntax -</em></strong></blockquote><ol><li>File name should we start with “<strong>test</strong>”. For example: test_exmaple.py or example_test.py. Let’s see some examples of valid and invalid pytest file names:</li></ol><pre>test_example.py - valid<br>example_test.py - valid<br>testexample.py -invalid<br>exampletest.py -invalid</pre><p>2. Test function names<strong> </strong>should start with “<strong>test_</strong>”. For example: test_file or testfile.</p><pre>def test_file_example1(): - valid<br>def testfile_example(): - valid<br>def file1_method1(): - invalid</pre><p>Now, we are clear with pytest naming syntax. Let’s create the project -</p><pre>- demo_project/<br>  - test_example.py</pre><blockquote><strong><em>Write first basic test in pytest</em> -</strong></blockquote><pre>import pytest<br><br>def test_file_exmaple1():<br>    input_value = 5<br>    assert input_value*5 == 25</pre><p>To run this test first go in to the demo_project directory and then, run this command:</p><pre>pytest test_example.py</pre><p>This command run all the test cases that lie in test_example.py file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvKi3itJubYW7G_Xs13Nhg.png" /></figure><p>Here in test_exmaple.py file.</p><p>F says failure</p><p>Dot(.) says success.</p><p>In the failures section, you can see the failed method(s) and the line of failure. Here 6*5==25 which is false.</p><p>To get the more information about the test case use this command:</p><pre>pytest test_example.py -v</pre><blockquote><strong><em>Assert in Pytest -</em></strong></blockquote><p>Pytest assert test if condition in your code is return true, if not program will raise an error and stop the method execution.</p><blockquote><strong><em>Run multiple test files</em></strong><em> -</em></blockquote><p>Currently, inside our directory we have only one file test_example.py. Suppose we have multiple file test_example1.py, test_example2.py. To run all the tests of all the files, we need to just run the pytest command:</p><pre>py.test</pre><blockquote><strong><em>Run tests by marker -</em></strong></blockquote><p>Pytest allows us to set attributes for the test methods using pytest markers, @pytest.mark.</p><p>Here we will apply marker names to test methods and run specific tests based on marker names.</p><pre>@pytest.mark.&lt;name&gt; </pre><p>Now, we will define the marker name and run the test by using marker name.</p><p>test_example.py</p><pre>import pytest<br><br>@pytest.mark.setexample<br>def test_file_example1():<br>    input_value = 5<br>    assert input_value*5 == 25<br><br><br>def test_file_example1_a():<br>    input_value = 6<br>    assert input_value*5 == 25</pre><p>test_example1.py</p><pre>import pytest<br><br>@pytest.mark.setexample<br>def test_string_A():<br>    assert &#39;ABC&#39; == &#39;ABC&#39;</pre><p>To run all the mark test use this command:</p><pre># py.test -m &lt;name&gt;<br>py.test -m setexample</pre><blockquote><strong><em>Pytest Xfail / Skip Tests -</em></strong></blockquote><p>In some circumstances, we don’t want to execute some test cases or we can say that test cases is not relevant for some time due to some reasons.</p><p>In those situation pytest given an option to Xfail the test or skip the tests.</p><ul><li>Xfailed test — They will be executed, but it will not be included in the calculation of passed or failed tests. Details of these tests will not be printed even if the test fails. We can xfail tests using the following marker:</li></ul><pre>@pytest.mark.xfail</pre><ul><li>skip test — A test will not be run if it is marked as skipped. We can skip tests using the following mark:</li></ul><pre>@pytest.mark.skip</pre><p>Edit the test_example.py file with the below code:</p><pre>import pytest<br><br>def test_file_example1():<br>    input_value = 5<br>    assert input_value*5 == 25<br><br>@pytest.mark.xfail<br>def test_file_example1_a():<br>    input_value = 6<br>    assert input_value*5 == 25<br><br>@pytest.mark.skip<br>def test_file_example1_b():<br>    input_value = 6<br>    assert input_value*6 == 25</pre><p>Execute the test using the following command :</p><pre>pytest .\test_example.py -v</pre><p>Upon execution, the above command will generate the following result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbNUM1-IZ7tJBMIezU3WVg.png" /></figure><blockquote><strong><em>Run tests in parallel -</em></strong></blockquote><p>We know a test suite have multiple files and number of test cases which will take a large amount of time to run. Pytest allow to run test cases in parallel.</p><p>To run the test cases in parallel first, we have to install the pytest-xdist library:</p><pre>pip install pytest-xdist</pre><p>After successfully install the library, we can run multiple test cases at same time using this command:</p><pre># py.test -n &lt;num&gt;<br>py.test -n 6</pre><p>Where num represent the number of workers. In the above command, there will be 6 workers to run the test cases.</p><blockquote><strong><em>Pytest Fixtures</em></strong></blockquote><p>Fixtures are the functions that will be executed prior to each test method to which they are applied. Therefore, we define fixtures rather than using the same code in every test. Fixtures are used to provide data to the tests such as database connections, URLs to test and some sort of input data.</p><p>A method is marked as a fixture by :</p><pre>@pytest.fixture</pre><p>A test method can use a Pytest fixture by mentioning the fixture name as an input parameter.</p><p>Create a new file test_example_fixture.py with following code:</p><pre>import pytest<br><br>@pytest.fixture<br>def input_value():<br>   input = 5<br>   return input<br><br>def test_file_example1(input_value):<br>    input_value = 5<br>    assert input_value*5 == 25<br><br>def test_file_example1_a(input_value):<br>    input_value = 6<br>    assert input_value*5 == 25</pre><p>Now run the test and see the result :</p><pre>pytest .\test_example_fixture.py -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8pXitGbMfFm0caWTtMTAw.png" /></figure><p>To use the same fixture against multiple test files, we will create fixture methods in conftest.py file.</p><p>Let’s see this by the below Pytest example. Create 2 files conftest.py and test_example_fixture.py with the following code:</p><p>conftest.py :</p><pre>import pytest<br><br>@pytest.fixture<br>def input_value():<br>   input = 5<br>   return input</pre><p>test_example_fixture.py :</p><pre>def test_file_example1(input_value):<br>    input_value = 5<br>    assert input_value*5 == 25<br><br>def test_file_example1_a(input_value):<br>    input_value = 6<br>    assert input_value*5 == 25</pre><p>Now run the test and see the result. The result is same as the previous one.</p><pre>pytest .\test_example_fixture.py -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*t8pXitGbMfFm0caWTtMTAw.png" /></figure><blockquote><strong><em>Pytest Parameterized</em></strong></blockquote><p>The purpose of parameterizing a test is to run a test against several sets of inputs. We can do this by :</p><pre>@pytest.mark.parametrize</pre><p>we will see the example of parameterizing below. First create the test_multipication.py file and copy the below code in test_multipication.py file.</p><pre>import pytest<br><br>@pytest.mark.parametrize(&quot;input, output&quot;,[(5,25),(6,30)])<br>def test_file_example1(input, output):<br>    assert input*5 == output</pre><p>Now run the test and see the result.</p><pre>pytest .\test_example_fixture.py -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2KeYBMNRXDRE9LPvWcYTQ.png" /></figure><blockquote><strong><em>Stop test case execution after n of failure :</em></strong></blockquote><p>If there is a situation where we need to stop the execution of a test suite after a certain number of test case failures, pytest provides the ability to do so by using maxfail.</p><p>The syntax to stop the execution of test suite after n number of test fails is as follows :</p><pre>pytest --maxfail = &lt;num&gt;</pre><blockquote><strong><em>Conclusion:</em></strong></blockquote><p>In this article, we have learned about pytest framework and how to use Fixtures, Marks, Parametrization, skip, Xfail and etc. Now you should be able to start writing test cases using pytest.</p><p>I hope this article has helped you.</p><p><em>Thanks!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9d4919cd427" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost your development-productivity to 10X with the all-exciting ChatGPT.]]></title>
            <link>https://medium.com/@ronakchitlangya1997/boost-your-development-productivity-to-10x-with-the-all-exciting-chatgpt-4cdac6f728ee?source=rss-1e6d9a36feee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cdac6f728ee</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Ronak Chitlangya]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 05:35:31 GMT</pubDate>
            <atom:updated>2023-02-20T05:35:31.706Z</atom:updated>
            <content:encoded><![CDATA[<p>When you are start reading this blog, you may have already used or heard about ChatGPT. It is a chatbot language model developed by OpenAI. And based on my own experience, I was quite impressed by a lot of its features. Overall, it can solve coding challenges, debug your code, write all kinds of scripts, write essay, stories, etc.</p><blockquote><strong><em>What is ChatGPT?</em></strong></blockquote><p>ChatGPT is an open-source text-based conversational artificial intelligence (AI) platform that uses natural language processing (NLP) to generate responses to your questions and prompts. It is based on the GPT (Generative Pre-training Transformer) architecture. The model was trained on a massive dataset allowing it to accurately mimic the way people speak and write in a variety of contexts.</p><p>This article will talk about the how to use ChatGPT for programming projects.</p><blockquote><strong><em>Getting Started with ChatGPT</em></strong></blockquote><p>To get started with ChatGPT, you must first create an account. This is done through the <a href="https://openai.com/blog/chatgpt/">ChatGPT </a>website. This page will appear once your account has been created :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0QOoE_wosROei1OkT9F8w.png" /></figure><p>The first task after creating an account is to learn how to use ChatGPT. For this we will type anything which we want to know in input box. It will give the output. For example, we will writing the “What is ChatGPT”..</p><p>After we have to press enter and we will get the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TSaws__-0kppaGKACoZuw.png" /></figure><p>Now, we’ll do some tasks on ChatGPT to make developer life easier. There are numerous methods in which ChatGPT can be used to save hours worth of development efforts. So, in this blog, we’ll look at how the ChatGPT can help developers:</p><ul><li><strong>Explaining code : </strong>ChatGPT can help you explain the code. Let’s look at some code that you want to understand using ChatGPT. For example, we will take some python code and understand them through ChatGPT :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWWaJUVyIzPreplprV6XIA.png" /></figure><ul><li><strong>Rewriting code using the correct style : </strong>We can use ChatGPT for rewriting the code in correct style. For this, we will take some random python code which is not written in proper manner and ask ChatGPT to rewrite the code :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CD5DHBpP4esXDrKwTAhEAw.png" /></figure><ul><li><strong>Simplifying code : </strong>This is one of my favourite techniques for simplifying the complex code. This trick is extremely useful for begineers who are facing difficulties to reading the code. For example, we can take some Python code, such as list and dict comprehension, and ask ChatGPT to simplify it:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3qEjwrNCnea-YKXtKnTqQ.png" /><figcaption>Simplify format of list comprehension</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIpC2Tzvkyeda_c-tpRWXg.png" /><figcaption>Simplify format of dict comprehension</figcaption></figure><ul><li><strong>Translating code : </strong>ChatGPT can also assist you with code translation from one language to another. For example, we will convert the following Python code to JavaScript :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mumUwuabAjg5xD2nGgIDg.png" /><figcaption>Python code into JavaScript</figcaption></figure><ul><li><strong>Finding bugs : </strong>By using ChatGPT, we can also find bug in our code. This method is extremely useful when trying to locate a bug. For example :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOfPzVLFcvWPDw9NGS_-GA.png" /></figure><p>There are many features in ChatGPT, and it is difficult to cover them all in a single tutorial.</p><blockquote><strong><em>Limitation of ChatGPT :</em></strong></blockquote><ul><li><strong>Wrong Answers : </strong>ChatGPT is a large language model that is continuously being trained to increase the accuracy of responses. However, because it is a new technology, the model has not yet received adequate training. As a result, the AI chatbot may provide incorrect answers.</li><li><strong>Limitation in Training Data :</strong>ChatGPT, like many AI models, has limitations in its training data. Both the constraints in training data and bias in the data can create a negative impact on the model’s output.</li><li><strong>Outdated Data : </strong>The most recent training data is from September 2021. An entire year has passed since then. Programming languages may have been updated, libraries may have gained new functionality, and the world has changed. This means that Chat-GPT is using an out-of-date set of data.</li></ul><blockquote><strong><em>Conclusion</em></strong></blockquote><p>ChatGPT is a powerful and easy-to-use platform that makes life easier for developers but there is also many drawbacks. Specially for beginner it is very helpful but, i do not recommend using it at first. If you find any trouble to resolve the issue try once yourself and in the last you can take the help of ChatGPT.</p><p>So, in this article, we learned about ChatGPT, how to use it, and its limitations.</p><p>I hope this article helped you. I will try to experiment with this model more in the future, and I’d love to hear what you’ve build with it. Please comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cdac6f728ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social Authentication (Email) using Django and React JS]]></title>
            <link>https://medium.com/@ronakchitlangya1997/social-authentication-email-using-django-and-react-js-e1cc8456262d?source=rss-1e6d9a36feee------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1cc8456262d</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[social-authentication]]></category>
            <category><![CDATA[email-authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ronak Chitlangya]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 09:54:14 GMT</pubDate>
            <atom:updated>2023-01-10T09:54:14.714Z</atom:updated>
            <content:encoded><![CDATA[<p>The majority of websites now regularly implement OAuth2 for logging. Therefore, it is crucial for developers to understand how to build social authentication and how the frontend and backend work together.</p><p>In this blog, we will implement social authentication using Django and React JS. We will create backend using Django REST Framework and frontend using React JS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WnveHW82acGucTmh.png" /><figcaption>Block Diagram for Social Authentication with React JS and Django</figcaption></figure><blockquote><strong><em>Backend — Django</em></strong></blockquote><p>We will first set up the project.</p><p>Create the Virtual environment:</p><pre>## Create the Virtual Environment.<br>python -m venv &lt;Virtual Environment Name&gt;</pre><p>Activate the Virtual environment:</p><pre># Activate the Virtual Environment.<br>&lt;Virtual Environment Name&gt;\scripts\activate</pre><p>If you found any error to activate the virtual environment run the command before activate the virtual environment:</p><pre>Set-ExecutionPolicy Unrestricted -Scope Process</pre><p>We install libraries like Django, the Django REST framework, drf-social-oauth2, and Django CORS headers after activating the virtual environment. The DRF packages are used to build the API, while drf-social-oauth2 allows for social platform authentication, and Django CORS headers are used to prevent CORS-related problems.</p><pre># Python Packages<br>pip install Django<br>pip install djangorestframework<br>pip install drf-social-oauth2<br>pip install django-cors-headers</pre><p>Once this is done, we will create the Project.</p><pre># Create the Project.<br>django-admin startproject social_backend</pre><p>Then, we will create the first app inside the project.</p><pre># Create the app.<br>python manage.py startapp authentification</pre><p>Now, we have to change the project settings. Go into settings.py file and make the following modifications:</p><pre>...........<br><br># Application definition<br>INSTALLED_APPS = [<br>     ........<br>     # Register your app<br>    &#39;rest_framework&#39;,<br>    &#39;corsheaders&#39;,<br>    &#39;oauth2_provider&#39;,<br>    &#39;social_django&#39;,<br>]<br><br>......<br><br>CORS_ORIGIN_ALLOW_ALL = True<br><br>.....<br><br>MIDDLEWARE = [<br>    &#39;corsheaders.middleware.CorsMiddleware&#39;,<br>    ..............<br>]<br><br>TEMPLATES = [<br>    {<br>        ...<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                ...<br>                &#39;social_django.context_processors.backends&#39;,<br>                &#39;social_django.context_processors.login_redirect&#39;,<br>            ],<br>        },<br>    }<br>]<br><br><br>REST_FRAMEWORK = {<br>    ...<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        ...<br>        &#39;oauth2_provider.contrib.rest_framework.OAuth2Authentication&#39;,<br>        &#39;drf_social_oauth2.authentication.SocialAuthentication&#39;,<br>    ),<br>}<br><br>AUTHENTICATION_BACKENDS = (<br>    # Google OAuth2<br>   &#39;social_core.backends.google.GoogleOAuth2&#39;,<br>   &#39;drf_social_oauth2.backends.DjangoOAuth2&#39;,<br>   &#39;django.contrib.auth.backends.ModelBackend&#39;,<br>)<br><br><br># Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google.<br>SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [<br>    &#39;https://www.googleapis.com/auth/userinfo.email&#39;,<br>    &#39;https://www.googleapis.com/auth/userinfo.profile&#39;,<br>]<br><br>...........</pre><p>Let’s look what we have done. First, we have registered DRF, social django, oauth2 provider, CORS, and our app name (you will write your app name) in INSTALLED APPS. In order to prevent the CORS-related problem, we have built a custom CORS header middleware and set the CORS ORIGIN ALLOW ALL = True. The default authentication CLASSES have then been added to the REST FRAMEWORK AUTHENTICATION Backend condition. After that, we added the SOCIAL AUTH GOOGLE OAUTH2 SCOPE to request Google’s authorization.</p><p>After written all the oauth2 condition, we will create a client id and client secret key from Google Developer console.</p><p>Go to this link <a href="https://console.developers.google.com/apis/credentials">https://console.developers.google.com/apis/credentials</a> and create a new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxXy3Jz7DPX-YMkeOzyK_w.png" /><figcaption>Click on Create Project button to make a new project.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3Y775FMzWhP9CUvxZJQFw.png" /><figcaption>Click on Create button to create a Project.</figcaption></figure><p>Now, click on create credentials and then select OAuth client ID. On the new screen and click on Configure Consent Screen button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HmlTXB2w3FzVsyW9Tsm0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7g4hMXZUQEyUkaPgkOCSLg.png" /></figure><p>On the next page fill all the details such as App name, user support email, Developer contact information, leave all other fields empty and click on save and continue button.</p><p>After come to dashboard click on CREATE CREDENTIALS &gt;&gt; OAuth client ID and fill all these fields:</p><pre>Application Type: Web Application<br>Name: Gmaillogin<br>Authorized JavaScript origins : http://localhost:3000<br>Authorised redirect URIs: http://localhost:3000</pre><p>Click the “create” button after filling out all of the fields, then note down your client’s secret and client ID.</p><p>Now, we will paste the client id and client secret in our settings.py file.</p><pre>......<br><br># Google configuration<br>SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = &lt;Google client id&gt;<br>SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = &lt;Google client secret&gt;<br><br>....</pre><p>After add the configuration in settings.py file, we will write the code in our authentication/views.py file for testing.</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework.permissions import IsAuthenticated<br>from rest_framework import status<br>  <br>  <br>class HomeView(APIView):<br>    permission_classes = (IsAuthenticated, )<br>  <br>    def get(self, request):<br>        content = {&#39;message&#39;: &#39;Welcome to the Social Authentication (Email) page using React Js and Django!&#39;}<br>        return Response(content)</pre><p>After created the HomeView class in views.py file, we will create the URL for HomeView in authentication/urls.py file:</p><pre>from . import views<br>  <br>urlpatterns = [<br>    path(&#39;home/&#39;, views.HomeView.as_view(), name =&#39;home&#39;),<br>]</pre><p>After, we will register our app URL and create the URL for Social AUTH in our social_backend/urls.py file:</p><pre>from django.urls import path, include<br><br>urlpatterns = [<br>    ......<br>    path(&#39;auth/&#39;, include(&#39;authentication.urls&#39;)),<br>    path(&#39;api-auth/&#39;, include(&#39;drf_social_oauth2.urls&#39;,namespace=&#39;drf&#39;)),<br>]</pre><p>Now all things is set on backend.</p><blockquote><strong><em>Frontend — React JS</em></strong></blockquote><p>There are several other ways to connect Django to your front end, however in this tutorial we’ll be utilising React JS to create the front end. We have already created the API’s for social authentication using DRF.</p><p>Let’s setup the React app using this command:</p><pre>// Create the react app.<br><br>npx create-react-app frontend</pre><p>Install the following packages:</p><pre>// Install the packages.<br><br>npm i bootstrap<br>npm i axios<br>npm i react-router-dom<br>npm i gapi-script<br>npm i react-google-login</pre><p>After setup the project run this command to run the react app:</p><pre>// To run the react app.<br><br>npm start</pre><p>Then open <a href="http://localhost:3000/">http://localhost:3000/</a> to see your app.</p><p>After run the server successfully, we move further to design the application. So first, we will create the component folder inside the src folder.</p><p>After create the component folder in src, we will create the login.js, logout.js, navigation.js and home.js. Basically, we have created the different file for different use.</p><p>So first, we will write the code for navigation bar in navigations.js file.</p><pre>import Nav from &#39;react-bootstrap/Nav&#39;;<br>import Navbar from &#39;react-bootstrap/Navbar&#39;;<br>import React, { useState, useEffect} from &#39;react&#39;;<br><br>export function Navigation() {<br>  const [isAuth, setIsAuth] = useState(false);<br><br>  useEffect(() =&gt; {<br>    if (localStorage.getItem(&#39;access_token&#39;) !== null) {<br>      setIsAuth(true);<br>    }<br>  }, [isAuth]);<br><br>  return (<br>    <br>    &lt;div&gt;<br>    &lt;Navbar bg=&quot;dark&quot; variant=&quot;dark&quot;&gt;<br>          &lt;Navbar.Brand href=&quot;/&quot;&gt;JWT Authentification&lt;/Navbar.Brand&gt;<br>          &lt;Nav className=&quot;me-auto&quot;&gt;<br>          {isAuth ?<br>            &lt;Nav.Link href=&quot;/&quot;&gt;Home&lt;/Nav.Link&gt;<br>            : null}<br>          &lt;/Nav&gt;<br>          &lt;Nav&gt;<br>          {isAuth ?<br>            &lt;Nav.Link href=&quot;/logout&quot;&gt;Logout&lt;/Nav.Link&gt;:<br>            &lt;Nav.Link href=&quot;/login&quot;&gt;Login&lt;/Nav.Link&gt;<br>          }<br>          &lt;/Nav&gt;<br>      &lt;/Navbar&gt;<br>      &lt;/div&gt;<br>  );<br>}</pre><p>To deign the navigation page. First, we have imported all the packages and then define Navigation function. Inside the navigation function, we have used the useState to store the value in isAuth variable. Initially, we have set the value false. Then used the useEffect and check access token is present or not in localStoarge. If it is not present than change isAuth variable value from false to true.</p><p>Then, we have return the HTML code to design the navigation bar and used the ternary operator condition which check isAuth is true or false. If it is true, it shows the Home and Logout button on navigation bar otherwise it show login button like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ciPwiH7EN8UDXXqR3U7eQ.png" /></figure><p>After written navigation page code, we have to add route condition and import all the JS file that present inside the component folder in our app.js file.</p><pre>import &#39;./App.css&#39;;<br>import {BrowserRouter, Routes, Route} from &#39;react-router-dom&#39;;<br>import {Login} from &quot;./component/login&quot;;<br>import {Home} from &quot;./component/Home&quot;;<br>import {Navigation} from &#39;./component/navigation&#39;;<br>import {Logout} from &#39;./component/logout&#39;;<br>function App() {<br>    return &lt;BrowserRouter&gt;<br>    &lt;Navigation&gt;&lt;/Navigation&gt;<br>        &lt;Routes&gt;<br>            &lt;Route path=&quot;/&quot; element={&lt;Home/&gt;}/&gt;<br>            &lt;Route path=&quot;/login&quot; element={&lt;Login/&gt;}/&gt;<br>            &lt;Route path=&quot;/logout&quot; element={&lt;Logout/&gt;}/&gt;<br>        &lt;/Routes&gt;<br>    &lt;/BrowserRouter&gt;;<br>}<br><br>export default App;</pre><p>First, we imported all the packages and files into the App.js file. After that, we wrote the route conditions for login, logout, and home page.</p><p>After design the Navigation and app file, we will write the code for login functionality in login.js file.</p><pre><br>import axios from &quot;axios&quot;;<br>import {Navigate} from &quot;react-router-dom&quot;;<br>import {useState} from &quot;react&quot;;<br>import GoogleLogin from &quot;react-google-login&quot;;<br>import {gapi} from &quot;gapi-script&quot;;<br>import {useEffect} from &quot;react&quot;;<br>import &#39;bootstrap/dist/css/bootstrap.css&#39;;<br><br><br>export const Login = () =&gt; {<br>    const clientId = &lt;Your Google client Id&gt;;<br><br>      const onSuccess = async (res) =&gt; {<br>        console.log(&#39;succzddgsfgess:&#39;, res.accessToken);<br>        const user = {<br>              &quot;grant_type&quot;:&quot;convert_token&quot;,<br>              &quot;client_id&quot;:&lt;DRF CLIENT ID&gt;,<br>              &quot;client_secret&quot;: &lt;DRF CLIENT SECRET&gt;,<br>              &quot;backend&quot;:&quot;google-oauth2&quot;,<br>              &quot;token&quot;: res.accessToken<br>            };<br>            //console.log(user)<br>            const {data} = await axios.post(&#39;http://localhost:8000/api-auth/convert-token/&#39;, user ,{headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;<br>            }}, {withCredentials: true});<br><br>            //console.log(data, data[&#39;access_token&#39;])<br>            axios.defaults.headers.common[&#39;Authorization&#39;] = `Bearer ${data[&#39;access_token&#39;]}`;<br>            localStorage.clear();<br>            localStorage.setItem(&#39;access_token&#39;, data.access_token);<br>            localStorage.setItem(&#39;refresh_token&#39;, data.refresh_token);<br>            window.location.href = &#39;/&#39;<br>      }<br><br>      const onFailure = (err) =&gt; {<br>        console.log(&#39;failed:&#39;, err);<br>      };<br><br>    <br><br>    return(<br>        &lt;div className=&quot;Auth-form-container&quot;&gt;<br>          &lt;GoogleLogin<br>            clientId={clientId}<br>            buttonText=&quot;Sign in with Google&quot;<br>            onSuccess={onSuccess}<br>            onFailure={onFailure}<br>            cookiePolicy={&#39;single_host_origin&#39;}<br>            <br>        /&gt;<br>        &lt;/div&gt;<br><br>    )<br>}</pre><p>Let’s look what we have done. First, we have initialize the React JS and Google Login packages. Second, we have create the function which name is Login. Inside the login function we have created the onSuccess function. Inside the onSuccess function, we have written the axios post method to fetch the access token and refresh token. After fetch the token, we have store this tokens in local storage and navigate to the particular location which you want. For this case, I have route to my home URL. Then, we have design the GoogleLogin button. Whenever, we click on Sign in With Google button, it will fetch the access token from google of particular id which, we have selected. If it is success to fetch the access token from google, it will run the onSuccess function and if it is fail, it will run the onFailure function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fOHzerZwKjlPRgpF_9Uyg.png" /></figure><p>After design the Login page, let’s move on to write the code for home page in our home.js file.</p><pre>import {useEffect, useState} from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br><br>export const Home = () =&gt; {<br>    const [message, setMessage] = useState(&#39;&#39;);<br><br>    useEffect(() =&gt; {<br>        if(localStorage.getItem(&#39;access_token&#39;) === null){<br>            window.location.href = &#39;/login&#39;  <br>        }<br>        else{<br>            (async () =&gt; {<br>            try {<br>                const {data} = await axios.get(&#39;http://localhost:8000/auth/home/&#39;, {<br>                headers: {<br>                  &#39;Authorization&#39;: &#39;Bearer &#39; + localStorage.getItem(&#39;access_token&#39;),<br>                  &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                }<br>              });<br><br>              setMessage(data.message);<br>            } catch (e) {<br>                console.log(&#39;not auth&#39;)<br>            }<br>        })()};<br>    }, []);<br><br><br><br>    return &lt;div className=&quot;form-signin mt-5 text-center&quot;&gt;<br>        &lt;h3&gt;Hi {message}&lt;/h3&gt;<br>        <br>    &lt;/div&gt;<br>}</pre><p>Let’s look what we have done. First, we have initialize the React JS packages. Second, we have create the function which name is Home. Inside the Home, we have used the useState to store the message data and useEffect which called when every time the component renders. Inside useEffect, we have written if else condition to check the access token is present or not. If access token is null in localStorage then, we will redirect to login page otherwise if we have token, we will create the get request to fetch the data from home API and set the message. Then, we have written the HTML code to display the message and our home page looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRE0wzuIY5wsFQY9dsbV3A.png" /></figure><p>Now, we will write the code for logout functionality in logout.js file.</p><pre>import {useEffect} from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br><br>export const Logout = () =&gt; {<br><br>    useEffect(() =&gt; {<br>        localStorage.clear();<br>        axios.defaults.headers.common[&#39;Authorization&#39;] = &quot;&quot;;<br>        window.location.href = &#39;/login&#39;<br>    }, []);<br><br>    return (<br>        &lt;div&gt;&lt;/div&gt;<br>    )<br>}</pre><p>Let’s look what we have done. First, we have initialize the react js packages and axios. Second, we have create the function which name is Logout. Inside the Logout we have written the code to remove the access and refresh token from localStorage and navigate to login page.</p><p>This is some basic stuff if you need to build an social authentication (Email) system with React and Django.</p><p><strong>Conclusion:</strong></p><p>In this article, we’ve learnt how to use Django Rest Framework to create social authentication APIs, React JS to design the front end, and Axios to invoke the API.</p><p>I hope this article has helped you.</p><p><em>Thanks for coding along with me!</em></p><p>Visit GitHub to view the Frontend and Backend code: https://github.com/Ronakchitlangya1997/Social-Authentication-Email-using-Django-and-React-JS</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1cc8456262d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication With React JS and Django]]></title>
            <link>https://medium.com/@ronakchitlangya1997/jwt-authentication-with-react-js-and-django-c034aae1e60d?source=rss-1e6d9a36feee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c034aae1e60d</guid>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ronak Chitlangya]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 07:16:57 GMT</pubDate>
            <atom:updated>2023-04-24T07:09:34.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*G-5rGvR2WxcfGnot.jpg" /></figure><p>As a full-stack developer, it is crucial to understand how to build an authentication system using backend and manage the flow of authentication in frontend.</p><p>In this blog, we will build an authentication system. To build the backend, we will using the Django Framework and for frontend React JS framework.</p><blockquote><strong>What JSON Web Tokens (JWT)?</strong></blockquote><p>JSON Web Token is a open standard for transferring authorization details between client and server. In JWT all the information is self contained, we don’t need to store them in server.</p><p>For Example: A user comes to our web application and login with username and password. After verifying the credentials, sever provides the two JSON web tokens. One of them is an Access Token and other is Refresh Token. After get the token server stores the token and pass the access token in the authorization header. The server verify the token and identify the user. Access token is valid for short time (depending on the configurations). In such a case if token is invalid or expire, we will use the refresh token to generate the new access token.</p><blockquote><strong>Backend — Django</strong></blockquote><p>First, We will set up the project.</p><p>Create the Virtual environment:</p><pre>## Create the Virtual Environment.</pre><pre>python -m venv &lt;Virtual Environment Name&gt;</pre><p>Activate the Virtual environment:</p><pre># Activate the Virtual Environment.</pre><pre>&lt;Virtual Environment Name&gt;\scripts\activate</pre><p>If you found any error to activate the virtual environment run the command before activate the virtual environment:</p><pre>Set-ExecutionPolicy Unrestricted -Scope Process</pre><p>After activate the virtual environment, we install the packages such as Django, Django REST framework, Django REST framework simple JWT and Django CORS headers. The DRF packages is used to create the API, while DRF simple JWT gives as ability to generate the JWT Token and Django CORS headers is used to avoid CORS related issues.</p><pre># Python Packages</pre><pre>pip install Django<br>pip install djangorestframework<br>pip install djangorestframework-simplejwt<br>pip install django-cors-headers</pre><p>Once this is done, We will create the Project.</p><pre># Create the Project.</pre><pre>django-admin startproject backend</pre><p>Then, we will create the first app inside the project.</p><pre># Create the app.</pre><pre>python manage.py startapp authentification</pre><p>Now, we have to change the project setting. Go into settings.py file and make the following modifications:</p><pre>from datetime import timedelta</pre><pre>.....</pre><pre>INSTALLED_APPS = [<br>     ...........<br>     # Register your app<br>     &#39;corsheaders&#39;,<br>     &#39;rest_framework&#39;,<br>     &#39;rest_framework_simplejwt.token_blacklist&#39;<br>]</pre><pre>.....</pre><pre>CORS_ORIGIN_ALLOW_ALL = True</pre><pre>.....</pre><pre>MIDDLEWARE = [<br>    &#39;corsheaders.middleware.CorsMiddleware&#39;,<br>    ...........<br>]</pre><pre>.....</pre><pre>REST_FRAMEWORK = {<br>     &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>      ],<br>}</pre><pre>.....</pre><pre>SIMPLE_JWT = {<br>     &#39;ACCESS_TOKEN_LIFETIME&#39;: timedelta(minutes=10),<br>     &#39;REFRESH_TOKEN_LIFETIME&#39;: timedelta(days=1),<br>     &#39;ROTATE_REFRESH_TOKENS&#39;: True,<br>     &#39;BLACKLIST_AFTER_ROTATION&#39;: True<br>}</pre><p>Let’s look what we have done. First, we have register our app name (You will write your app name), DRF, DRF simple JWT and CORS in INSTALLED_APPS. Second, we have set the CORS_ORIGIN_ALLOW_ALL = True and added the custom CORS header middleware in MIDDLEWARE to avoid the CORS related issue. Then, we have added the authentication JWT Class in REST_FRAMEWORK and added the SIMPLE_JWT token configurations to implement an access/refresh logic.</p><p>After add the configuration in settings.py file, we will create the URL for access token and refresh token in backend/urls.py file.</p><pre>from django.contrib import admin<br>from django.urls import path, include<br>from rest_framework_simplejwt import views as jwt_views</pre><pre>urlpatterns = [<br>     .....<br>     path(&#39;token/&#39;, <br>          jwt_views.TokenObtainPairView.as_view(), <br>          name =&#39;token_obtain_pair&#39;),<br>     path(&#39;token/refresh/&#39;, <br>          jwt_views.TokenRefreshView.as_view(), <br>          name =&#39;token_refresh&#39;)<br>]</pre><p>Now, we are almost ready to test whether it is works or not. Before run the project we have to apply the migration and create the user. Run this command to apply the migration:</p><pre># Apply the migration.</pre><pre>python manage.py migrate</pre><p>Once this is done. we will create the user using this command:</p><pre># Create the user.</pre><pre>python manage.py createsuperuser</pre><p>Fill all the fields and now, we will start the development server using this command:</p><pre># Runserver</pre><pre>python manage.py runserver</pre><p>After run the server, we will navigate to this <a href="http://localhost:8000/token/">http://localhost:8000/token/</a>, we will see this page which contains the form with username and password field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlEx9yUpKYxoxFSAGLiMZw.png" /></figure><p>Fill this form with your created username and password, you should see the access and refresh token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuWarrdzQFvpiTj0HI8gcA.png" /></figure><p>We all know, access token is invalid after some time. So by the use of refresh token we will generate the new access token and refresh token as well. To generate the new access token with the help of refresh token, we will navigate to this URL <a href="http://localhost:8000/token/refresh/">http://localhost:8000/token/refresh/</a>, we will see this page which contains the form with Refresh field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUuZx8SuIoh069UoEm2UTQ.png" /></figure><p>Fill this form with Refresh Token, you should see the new access and refresh token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqqF1RX8seoBISgi5YZgNQ.png" /></figure><p>Now, we will create the views for testing. so, we will go in views.py file in our app directory and write the following code:</p><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework.permissions import IsAuthenticated</pre><pre>class HomeView(APIView):<br>     <br>   permission_classes = (IsAuthenticated, )</pre><pre>   def get(self, request):</pre><pre>       content = {&#39;message&#39;: &#39;Welcome to the JWT <br>                   Authentication page using React Js and Django!&#39;}</pre><pre>   return Response(content)</pre><p>Let’s look what we have done. First, we have import the modules and created the class based view using simple APIView then, we have set the permission class for authenticated user. Second, we have created the get method and set the response.</p><p>Now, we will create the URL for HomeView. To create the URL first, we have to create the urls.py file in our app directory.</p><pre>from django.urls import path<br>from . import views</pre><pre>urlpatterns = [<br>     path(&#39;home/&#39;, views.HomeView.as_view(), name =&#39;home&#39;)<br>]</pre><p>Second, we have to register the urls.py file path in our project directory urls.py file.</p><pre>urlpatterns = [<br>    ......<br>    path(&#39;&#39;, include(&#39;&lt;app name&gt;.urls&#39;)),<br>]</pre><p>Now, we will use the POSTMAN to hit this URL <a href="http://localhost:8000/home/">http://localhost:8000/home/</a> with get request and we get authentication credential not provided message because in our HomeView we have set the permission class is IsAuthenticated means this page is only for authenticated user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBlNilbWV6jtZ0bV3DqJLQ.png" /></figure><p>So, we have to provide the access token in authorization to get the result. Now again, we will create the get request with access token. To set the access token in POSTMAN, we have to click on Authorization button and set the token type is Bearer Token and paste the access token. After hit the API we will get this output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEM673QNWD3I55BV5mWn4Q.png" /></figure><p>Now, we have to add the logout functionality because we all know access token is valid for some time.</p><p>By the use of refresh token, we will generate the new access token. But, what happens when user wants to log out. The client can forgot both token. For example we have remove both the access and refresh token from localStorage. But, if refresh token is stolen, then another client use this token and use it. To prevent this, we will create the logout API, by using we can invalid the refresh token.</p><p>To create logout API, we will write the LogoutView in our views.py file in app directory:</p><pre>class LogoutView(APIView):</pre><pre>     permission_classes = (IsAuthenticated,)</pre><pre>     def post(self, request):<br>          <br>          try:</pre><pre>               refresh_token = request.data[&quot;refresh_token&quot;]</pre><pre>               token = RefreshToken(refresh_token)</pre><pre>               token.blacklist()</pre><pre>               return Response(status=status.HTTP_205_RESET_CONTENT)</pre><pre>          except Exception as e:</pre><pre>               return Response(status=status.HTTP_400_BAD_REQUEST)</pre><p>After create the LogoutView, we have to create the URL for LogoutView in our urls.py file in app directory.</p><pre>urlpatterns = [<br>     .....<br>     path(&#39;logout/&#39;, views.LogoutView.as_view(), name =&#39;logout&#39;)<br>]</pre><p>By using that URL <a href="http://localhost:8000/logout/">http://localhost:8000/logout/</a>, we can invalid the refresh token and add token into blacklist. By using Postman we can hit this URL with POST request and pass the access token in authorization and refresh token in body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TO4T6rJecsv2Y-3utG5dCw.png" /></figure><p>Now all things is set on backend, We have tested all the API’s.</p><h4><strong>Frontend — React JS</strong></h4><p>There are many ways to connect the Django to your frontend but, In this tutorial we design the frontend using React JS Framework. We have already created the API’s for authentication.</p><p>Let’s setup the React app using this command:</p><pre>// Create the react app.</pre><pre>npx create-react-app frontend</pre><p>Install the following packages:</p><pre>// Install the packages.<br>npm i bootstrap<br>npm i axios<br>npm i react-router-dom</pre><p>After setup the project run this command to run the react app:</p><pre># To run the react app.</pre><pre>npm start</pre><p>Then open <a href="http://localhost:3000/">http://localhost:3000/</a> to see your app.</p><p>After run the server successfully, we move further to design the application. So first, we will create the component folder inside the src folder.</p><p>After create the component folder in src we will create the login.js, logout.js, navigation.js and home.js. Basically, we have created the different file for different use.</p><p>So first, we will write the code for navigation bar in navigations.js file.</p><pre>import Nav from &#39;react-bootstrap/Nav&#39;;<br>import Navbar from &#39;react-bootstrap/Navbar&#39;;<br>import React, { useState, useEffect} from &#39;react&#39;;</pre><pre>export function Navigation() {</pre><pre>   const [isAuth, setIsAuth] = useState(false);</pre><pre>   useEffect(() =&gt; {</pre><pre>     if (localStorage.getItem(&#39;access_token&#39;) !== null) {</pre><pre>        setIsAuth(true); <br>      }</pre><pre>    }, [isAuth]);</pre><pre>     return ( <br>      &lt;div&gt;<br>        &lt;Navbar bg=&quot;dark&quot; variant=&quot;dark&quot;&gt;<br>          &lt;Navbar.Brand href=&quot;/&quot;&gt;JWT Authentification&lt;/Navbar.Brand&gt;            <br>          &lt;Nav className=&quot;me-auto&quot;&gt; <br>          {isAuth ? &lt;Nav.Link href=&quot;/&quot;&gt;Home&lt;/Nav.Link&gt; : null}<br>          &lt;/Nav&gt;<br>          &lt;Nav&gt;<br>          {isAuth ? &lt;Nav.Link href=&quot;/logout&quot;&gt;Logout&lt;/Nav.Link&gt; :  <br>                    &lt;Nav.Link href=&quot;/login&quot;&gt;Login&lt;/Nav.Link&gt;}<br>          &lt;/Nav&gt;<br>        &lt;/Navbar&gt;<br>       &lt;/div&gt;<br>     );<br>}</pre><p>To deign the navigation page. First, we have imported all the packages and then define Navigation function. Inside the navigation function, we have used the useState to store the value in isAuth variable. Initially, we have set the value false. Then, used the useEffect and check access token is present or not in localStoarge. if it is not present than change isAuth variable value from false to true.</p><p>Then, we have return the HTML code to design the navigation bar and used the ternary operator condition which check isAuth is true or false. if it is then, it shows the Home and Logout button on navigation bar otherwise it show login button like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Kdynmh6kb6v4-F9Gps5Hg.png" /></figure><p>After written navigation page code, we have to add route condition in our app.js file.</p><pre>import &#39;./App.css&#39;;<br>import {BrowserRouter, Routes, Route} from &#39;react-router-dom&#39;<br>import {Login} from &quot;./component/login&quot;;<br>import {Home} from &quot;./component/Home&quot;;<br>import {Navigation} from &#39;./component/navigation&#39;;<br>import {Logout} from &#39;./component/logout&#39;;</pre><pre>function App() {</pre><pre>    return <br>      &lt;BrowserRouter&gt;<br>        &lt;Navigation&gt;&lt;/Navigation&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Home/&gt;}/&gt;<br>          &lt;Route path=&quot;/login&quot; element={&lt;Login/&gt;}/&gt;<br>          &lt;Route path=&quot;/logout&quot; element={&lt;Logout/&gt;}/&gt;<br>        &lt;/Routes&gt;<br>      &lt;/BrowserRouter&gt;;<br>}<br>export default App;</pre><p>In App.js file first, we have imported all the packages and files, then, written the route condition for login, logout and home page.</p><p>After design the Navigation, we will write the code for login functionality in login.js file.</p><pre>// Import the react JS packages <br>import axios from &quot;axios&quot;;<br>import {useState} from &quot;react&quot;;</pre><pre>// Define the Login function.<br>export const Login = () =&gt; {</pre><pre>     const [username, setUsername] = useState(&#39;&#39;);</pre><pre>     const [password, setPassword] = useState(&#39;&#39;);</pre><pre>     // Create the submit method.<br>     const submit = async e =&gt; {</pre><pre>          e.preventDefault();</pre><pre>          const user = {<br>                username: username,<br>                password: password<br>               };</pre><pre>          // Create the POST requuest<br>          const {data} = await                                                                            <br>                         axios.post(&#39;http://localhost:8000/token/&#39;,<br>                         user ,{headers: <br>                        {&#39;Content-Type&#39;: &#39;application/json&#39;}},<br>                         withCredentials: true});</pre><pre><br>         // Initialize the access &amp; refresh token in localstorage.      <br>         localStorage.clear();</pre><pre>         localStorage.setItem(&#39;access_token&#39;, data.access);</pre><pre>         localStorage.setItem(&#39;refresh_token&#39;, data.refresh);</pre><pre>         axios.defaults.headers.common[&#39;Authorization&#39;] = <br>                                         `Bearer ${data[&#39;access&#39;]}`;</pre><pre>         window.location.href = &#39;/&#39;</pre><pre>    }</pre><pre>    return(</pre><pre>      &lt;div className=&quot;Auth-form-container&quot;&gt;<br>        &lt;form className=&quot;Auth-form&quot; onSubmit={submit}&gt;<br>          &lt;div className=&quot;Auth-form-content&quot;&gt;<br>            &lt;h3 className=&quot;Auth-form-title&quot;&gt;Sign In&lt;/h3&gt;<br>            &lt;div className=&quot;form-group mt-3&quot;&gt;<br>              &lt;label&gt;Username&lt;/label&gt;<br>              &lt;input className=&quot;form-control mt-1&quot; <br>                placeholder=&quot;Enter Username&quot; <br>                name=&#39;username&#39;  <br>                type=&#39;text&#39; value={username}<br>                required <br>                onChange={e =&gt; setUsername(e.target.value)}/&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;form-group mt-3&quot;&gt;<br>              &lt;label&gt;Password&lt;/label&gt;<br>              &lt;input name=&#39;password&#39; <br>                type=&quot;password&quot;     <br>                className=&quot;form-control mt-1&quot;<br>                placeholder=&quot;Enter password&quot;<br>                value={password}<br>                required<br>                onChange={e =&gt; setPassword(e.target.value)}/&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;d-grid gap-2 mt-3&quot;&gt;<br>              &lt;button type=&quot;submit&quot; <br>                 className=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>       &lt;/form&gt;<br>     &lt;/div&gt;<br>     )<br>}</pre><p>Let’s look what we have done. First, we have initialize the react js packages. Second, we have create the function which name is Login. Inside the login function we have created the submit function. Inside the submit function we have written the axios post method to fetch the access token and refresh token. After fetch the token, we have store this tokens in local storage and navigate to the particular location which you want. For this case, I have route to my home URL. Then, we have design the Login form with username and password fields. Whenever, we click on submit button, the submit function is called and fetch the data from our backend login API. If it is successful than we get the access token and navigate to other page or home page otherwise it gives error in console.</p><p>After design the login page our page looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z5eEs6YQFwidXa5xN6Ysg.png" /></figure><p>After design the Login page, let’s move on to write the code for home page in our home.js file.</p><pre>// Import the react JS packages<br>import {useEffect, useState} from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br></pre><pre>// Define the Login function.<br>export const Home = () =&gt; {</pre><pre>     const [message, setMessage] = useState(&#39;&#39;);</pre><pre>     useEffect(() =&gt; {</pre><pre>        if(localStorage.getItem(&#39;access_token&#39;) === null){                   </pre><pre>            window.location.href = &#39;/login&#39;<br>        }<br>        else{</pre><pre>         (async () =&gt; {</pre><pre>           try {</pre><pre>             const {data} = await axios.get(   <br>                            &#39;http://localhost:8000/home/&#39;, {<br>                             headers: {<br>                                &#39;Content-Type&#39;: &#39;application/json&#39;<br>                             }}<br>                           );</pre><pre>             setMessage(data.message);</pre><pre>          } catch (e) {</pre><pre>            console.log(&#39;not auth&#39;)<br>          }</pre><pre>         })()};</pre><pre>     }, []);</pre><pre>     return </pre><pre>        &lt;div className=&quot;form-signin mt-5 text-center&quot;&gt;<br>          &lt;h3&gt;Hi {message}&lt;/h3&gt;<br>        &lt;/div&gt;<br>}</pre><p>Let’s look what we have done. First, we have initialize the react js packages. Second, we have create the function which name is Home. Inside the Home we have used the useState to store the message data and useEffect which called when every time the component renders. Inside useEffect we have written if else condition to check the access token is present or not. If access token is null in localStorage then, we will redirect to login page otherwise if we have token, we will create the get request to fetch the data from home API and set the message. Then, We have written the HTML code to display the message and our home page looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6KOv-WsUCUxK2sNXe1Phw.png" /></figure><p>We have design the home page also but, we all know that our access token is valid for very short time. After short time when we refresh the page, we will get the 401 unauthorized error because our access token is invalid. But we also know that in backend, we have created the refresh token API, which will generate the new access token and refresh token.</p><p>But the problem is how we know or after how much time access token is invalid or not. To resolve this problem, we use the interceptor in react js or in other words we can say middleware. Basically, Interceptors are methods which are triggered before or after the main method. So in this case we have using the axios interceptor. There are two types of interceptors:</p><ol><li>Request interceptor: — It allows you to write or execute your code before the request gets sent.</li><li>Response interceptor: — It allows you to write or execute your code before response reaches the calling end.</li></ol><p>So in our case, we have using the response interceptor because, we have to check the response. To write the response interceptor code first, we make the interceptor folder. Inside the interceptor folder create the axiox.js file. Inside the axios.js file, we will write the code:</p><pre>import axios from &quot;axios&quot;;</pre><pre>let refresh = false;</pre><pre>axios.interceptors.response.use(resp =&gt; resp, async error =&gt; {</pre><pre>  if (error.response.status === 401 &amp;&amp; !refresh) {</pre><pre>     refresh = true;<br>     console.log(localStorage.getItem(&#39;refresh_token&#39;))<br>     const response = await   <br>           axios.post(&#39;http://localhost:8000/token/refresh/&#39;, {      <br>                      refresh:localStorage.getItem(&#39;refresh_token&#39;)<br>                      }, { headers: <br>                      &#39;Content-Type&#39;: &#39;application/json&#39;<br>                      }<br>                      },{withCredentials: true});</pre><pre>    if (response.status === 200) {<br>       axios.defaults.headers.common[&#39;Authorization&#39;] = `Bearer <br>       ${response.data[&#39;access&#39;]}`;</pre><pre>       localStorage.setItem(&#39;access_token&#39;, response.data.access);</pre><pre>       localStorage.setItem(&#39;refresh_token&#39;, response.data.refresh);</pre><pre>       return axios(error.config);<br>    }</pre><pre>  }<br>refresh = false;</pre><pre>return error;</pre><pre>});</pre><p>Let’s look what we have done. First, we have import the axios package and then, create the axios response interceptor. Now, Every single time a request is made with the axios instance, if there are no errors, it just works as expected.</p><p>When there is error occur first, we will check the error code. If the error code is 401, we need to refresh the token. To refresh the token, we will create the POST request and get the new access token and refresh token. After get the token, we will reinitialize the token in localStorage and send the original request.</p><p>After create the response interceptor. We have to the add the interceptor location in our index.js file.</p><pre>import &#39;./interceptors/axios&#39;;</pre><p>Now, we will write the code for logout functionality in logout.js file.</p><pre>import {useEffect, useState} from &quot;react&quot;<br>import axios from &quot;axios&quot;;</pre><pre>export const Logout = () =&gt; {</pre><pre>    useEffect(() =&gt; {</pre><pre>       (async () =&gt; {</pre><pre>         try {<br>           const {data} = await  <br>                 axios.post(&#39;http://localhost:8000/logout/&#39;,{<br>                 refresh_token:localStorage.getItem(&#39;refresh_token&#39;)<br>                 } ,{headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}},  <br>                 {withCredentials: true});</pre><pre>           localStorage.clear();\<br>           axios.defaults.headers.common[&#39;Authorization&#39;] = null;<br>           window.location.href = &#39;/login&#39;<br>           } catch (e) {<br>             console.log(&#39;logout not working&#39;, e)<br>           }<br>         })();<br>    }, []);</pre><pre>    return (<br>       &lt;div&gt;&lt;/div&gt;<br>     )<br>}</pre><p>To add the logout functionality, we have declares the packages and use the useEffect hooks. Whenever we click on logout button, it call the backend logout API and remove all the tokens from local storage and navigate to login page.</p><p>This is some basic stuff if you need to build an authentication system with React and Django.</p><p><strong>Conclusion:</strong></p><p>In this article, we have learned to how to build the API’s with Django, designed the frontend part using React JS, call the API using axios and how to use response interceptor.</p><p>I hope this article has helped you.</p><p><em>Thanks for coding along with me!</em></p><p>Check the code of the Frontend and Backend on GitHub: <em>https://github.com/Ronakchitlangya1997/Authentication---React-Js-Django</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c034aae1e60d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>