<?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 Joey Masip Romeu on Medium]]></title>
        <description><![CDATA[Stories by Joey Masip Romeu on Medium]]></description>
        <link>https://medium.com/@joeymasip?source=rss-f18b9d52af41------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z0b1haRNC8Kk_AYr0NI94w.jpeg</url>
            <title>Stories by Joey Masip Romeu on Medium</title>
            <link>https://medium.com/@joeymasip?source=rss-f18b9d52af41------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:22:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joeymasip/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[Websites translations in cache for improved performance]]></title>
            <link>https://joeymasip.medium.com/websites-translations-in-cache-for-improved-performance-a8ec642b610c?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8ec642b610c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 09:47:25 GMT</pubDate>
            <atom:updated>2026-09-10T09:47:25.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*t8UcXNPhNVYneudzwCeZIA.jpeg" /></figure><p>I had this itch while looking at our own site, <a href="https://slowcode.io,/">https://slowcode.io</a> about the performance of the translations.</p><p>We serve the site in English, Spanish, and Catalan. The UI copy lives in the database, so the team can edit it from the admin — menu labels, buttons, SEO bits, form messages.. etc And in the templates, it looks innocent:</p><pre>{% load trans %}<br>&lt;h1&gt;{% trans &#39;home.headline&#39; %}&lt;/h1&gt;<br>&lt;p&gt;{% trans &#39;home.subtitle&#39; %}&lt;/p&gt;</pre><h3>The gut feeling was half right</h3><p>It wasn’t one query per key. The template tag only did a dictionary lookup. The expensive part was quieter.</p><p>On every request, a context processor reloaded <em>all</em> CMS strings from MySQL, stuffed them into a process-global dict, and only then did {% trans %} become cheap:</p><pre># before: ran on every template render<br>def set_translations(request):<br>    translator.set_translations_dict()<br>    return {}</pre><pre>def get_translations_dict(self):<br>    translations = {}<br>    for string in String.objects.all():<br>        translations[string.key] = string.value<br>    return translations</pre><p>So a page with sixty translation tags still cost one SELECT — but that SELECT ran on <em>every</em> HTML response. Home, services, blog, contact. Over and over. Same ~100 rows.</p><p>With a small table it wasn’t melting the server. It was still free work on every request, and it scaled with traffic for no good reason.</p><h3>What we wanted instead</h3><ol><li>Load the string table once per language, not once per request.</li><li>Hydrate translations <em>before</em> the view runs.</li></ol><h3>The Django fix</h3><p>We switched to a per-locale cache. First hit for en / es / ca builds a dict from the right column (value_en, etc.). After that, requests read memory:</p><pre>def get_translations_dict(language=None):<br>    language = _normalize_language(language)<br>    cache_key = &#39;cms_translations:{}&#39;.format(language)<br>    translations = cache.get(cache_key)<br>    if translations is None:<br>        translations = build_translations_dict(language)<br>        cache.set(cache_key, translations, CACHE_TIMEOUT)<br>    return translations</pre><pre>def build_translations_dict(language=None):<br>    field = &#39;value_{}&#39;.format(_normalize_language(language))<br>    return {<br>        key: (value or &#39;&#39;)<br>        for key, value in String.objects.values_list(&#39;key&#39;, field)<br>    }</pre><p>When someone edits a string in admin, we clear the cache:</p><pre>@receiver(post_save, sender=String)<br>@receiver(post_delete, sender=String)<br>def clear_translations_cache(sender, **kwargs):<br>    invalidate_translations_cache()</pre><p>Middleware, placed <em>after</em> LocaleMiddleware, attaches the dict to the request so views and templates share the same snapshot:</p><pre>class TranslationsMiddleware(object):<br>    def __init__(self, get_response):<br>        self.get_response = get_response</pre><pre>    def __call__(self, request):<br>        translations = get_translations_dict()<br>        request.translations = translations<br>        request.translator = Translator(translations=translations)<br>        return self.get_response(request)</pre><p>The template tag prefers that request dict:</p><pre>@register.simple_tag(takes_context=True, name=&#39;trans&#39;)<br>def trans(context, field):<br>    request = context.get(&#39;request&#39;)<br>    if request is not None and getattr(request, &#39;translations&#39;, None) is not None:<br>        return translate(field, translations=request.translations)<br>    return translator.trans(field)</pre><p>And String.key is unique. We deduped existing rows in a migration first, then added the constraint. Unique already gives you the index you want.</p><h3>What changed in practice</h3><p>Before: every page had a full table read, and then in-memory lookups. This might look fine on the surface but it gets expensive over time, specially if requests increase.</p><p>After: cold request does one single read and saves the dict in the cache. Warm requests have zero translation queries.</p><p>One caveat worth saying out loud: we used Django’s local-memory cache. That’s per process. With several gunicorn workers, an admin edit clears the worker that handled the save; the others catch up when the TTL expires (we use five minutes). Fine for our traffic. If you need instant consistency across workers, point CACHES at Redis later — the same keys and invalidation still apply.</p><h3>Takeaway</h3><p>If your multilingual UI copy lives in the database, don’t assume the tag is the problem. Look at <em>when</em> the dictionary is built. “Batch load once per request” feels tidy until you realize you’re paying that cost on every hit for a table that barely changes.. so cache scoped to the request is the solution in my opinion. Load it before the view and much less noise in the database.</p><p>Happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8ec642b610c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doctrine Migrations vs. Schema Update: The Right Choice for Production]]></title>
            <link>https://joeymasip.medium.com/doctrine-migrations-vs-schema-update-the-right-choice-for-production-0bfb84d97543?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bfb84d97543</guid>
            <category><![CDATA[doctrine]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[schema]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 21:40:46 GMT</pubDate>
            <atom:updated>2024-10-08T21:40:46.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kTIkjl7EVPmWpsNGK-2ag.jpeg" /></figure><p>When managing databases in Symfony applications, developers often face the challenge of keeping their database schema synchronized with their application’s data model. A common mistake many developers make — especially in the early stages of development — is relying on the doctrine:schema:update --force command to directly update the database. While this may seem convenient, especially in local development, it can lead to serious problems when running in a production environment.</p><p>In this post, I’ll explain why using <strong>Doctrine Migrations</strong> is the better approach, particularly in production environments.</p><h3>Why Avoid doctrine:schema:update --force in Production?</h3><h4>1. Uncontrolled Schema Updates</h4><p>doctrine:schema:update --force makes automatic schema changes without allowing the developer to see what exactly is being altered. This can cause unexpected changes to the database, possibly leading to data loss or schema corruption.</p><h4>2. Lack of Version Control</h4><p>With doctrine:schema:update --force, you have no clear history of schema changes. If you need to rollback changes or track how the database evolved over time, you&#39;re out of luck.</p><h4>3. No Rollback Option</h4><p>In case an update fails, there’s no built-in mechanism to revert the database schema to its previous state. This makes schema changes riskier, especially in production.</p><h3>Why Doctrine Migrations Are the Better Choice</h3><p>Doctrine Migrations provide a much safer and controlled way to handle database changes in any environment, but they are <strong>essential</strong> for production. Here’s why:</p><h4>1. Version Control for Your Database</h4><p>Doctrine Migrations allow you to create versioned migration files that describe the changes to be applied to your database. Each migration corresponds to a specific change, and these migrations can be committed to version control along with your code.</p><h4>2. Predictability and Safety</h4><p>With migrations, you know exactly what changes will be applied to the database. This predictability ensures you can review and test migrations before applying them to production.</p><h4>3. Rollback Support</h4><p>Migrations come with built-in support for rolling back changes. If something goes wrong, you can easily revert the database to a previous state.</p><h4>4. Better Control in Production</h4><p>Instead of applying arbitrary changes directly to the production database, you execute migrations that have been tested and reviewed. This helps minimize the risk of downtime or critical data loss.</p><h3>How to Use Doctrine Migrations in Production</h3><p>Let’s walk through a typical setup to manage database schema changes using Doctrine Migrations in a Symfony project. We’ll look at how to create migrations, execute them during a deployment, and rollback if needed.</p><h4>Step 1: Generating a Migration</h4><p>First, whenever you make changes to your data model (like adding a field to an entity), you need to generate a migration file:</p><pre>bin/console doctrine:migrations:diff</pre><p>This will generate a migration file in your migrations/ directory. The file will contain SQL queries that correspond to the changes in your entities.</p><h4>Step 2: Reviewing the Migration</h4><p>Before running the migration, always review the generated file to ensure that the changes are correct and won’t cause issues in your database. For example, here’s what a simple migration might look like:</p><pre>&lt;?php </pre><pre>declare(strict_types=1);</pre><pre>namespace DoctrineMigrations;</pre><pre>use Doctrine\DBAL\Schema\Schema;<br>use Doctrine\Migrations\AbstractMigration;</pre><pre>final class Version20241002185538 extends AbstractMigration<br>{<br>    public function up(Schema $schema): void<br>    {<br>        // Apply changes<br>        $this-&gt;addSql(&#39;ALTER TABLE log_sync CHANGE command command VARCHAR(510) NOT NULL&#39;);<br>    }</pre><pre>    public function down(Schema $schema): void<br>    {<br>        // Revert changes<br>        $this-&gt;addSql(&#39;ALTER TABLE log_sync CHANGE command command VARCHAR(255) NOT NULL&#39;);<br>    }<br>}</pre><h4>Step 3: Executing the Migration in Production</h4><p>Instead of running doctrine:schema:update --force in production, you should run the migration you’ve prepared and reviewed. You can execute all pending migrations like this:</p><pre>bin/console doctrine:migrations:migrate --no-interaction</pre><p>This will apply the latest available migration(s) to your production database safely.</p><h4>Step 4: Managing Migrations During Deployments</h4><p>For automated deployments, it’s important to track which migration version has been applied. You can create a script to read the migration version from a file and run the migration like so:</p><pre># Read the version from the file, replacing double backslashes with a single backslash<br>TARGET_VERSION=$(cat MIGRATION_VERSION)<br><br># Executing migration for: $TARGET_VERSION&quot;<br>bin/console doctrine:migrations:migrate DoctrineMigrations\\$TARGET_VERSION --no-interaction</pre><p>This script ensures that only the specific version defined in MIGRATION_VERSION is executed, giving you precise control over which migration is applied during the deployment process.</p><p>The MIGRATION_VERSION file will just contain the version like so:</p><pre>Version20241002185538</pre><h3>Example Deployment Script</h3><p>Here’s a simple deployment script that could be part of your CI/CD pipeline:</p><pre># Read the target version from the migration version file<br>TARGET_VERSION=$(cat MIGRATION_VERSION)<br><br># Apply the migration<br>bin/console doctrine:migrations:migrate DoctrineMigrations\\$TARGET_VERSION --no-interaction<br>bin/console cache:clear</pre><h3>Rolling Back Migrations</h3><p>If something goes wrong in production, you can easily rollback the last applied migration. To rollback a specific migration, use</p><pre>bin/console doctrine:migrations:execute --down &#39;DoctrineMigrations\\Version20241002185538&#39;</pre><p>This will revert the changes made by the migration.</p><p>Or you can also use the MIGRATION_VERSION file like so</p><pre>TARGET_VERSION=$(cat MIGRATION_VERSION)<br>bin/console doctrine:migrations:migrate DoctrineMigrations\\$TARGET_VERSION --no-interaction</pre><h3>Conclusion</h3><p>Relying on doctrine:schema:update --force may be tempting due to its simplicity, but it poses significant risks in a production environment. Using <strong>Doctrine Migrations</strong> gives you a much more controlled, predictable, and secure way of handling database schema changes, especially during deployment.</p><p>With migrations, you gain the ability to track, version, and rollback database changes, which are critical features when working in production. By implementing migrations, you ensure your application remains stable and your database is managed safely.</p><p>By following these steps and practices, you’ll have a robust database migration process that scales with your application. If you have any questions or tips from your own experiences with Doctrine Migrations, feel free to share them in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bfb84d97543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SEO and Security in Django: Sitemaps and HTTPS]]></title>
            <link>https://joeymasip.medium.com/mastering-seo-and-security-in-django-sitemaps-and-https-3da52f0f49da?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da52f0f49da</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 18:06:49 GMT</pubDate>
            <atom:updated>2023-10-04T19:58:12.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hp6pp-vfS9mnCc5uzO8j6w.jpeg" /></figure><p>In the world of web development, two critical aspects that often go hand in hand are SEO optimization and ensuring secure data transmission. Django, a popular Python web framework, provides a robust solution for managing sitemaps and seamlessly integrating HTTPS into your web application.</p><p>Lately, I had to work on this matter for a project and wanted to share in this blog post the importance of sitemaps in Django and how to enhance security by implementing HTTPS.</p><h3>Part 1: Sitemaps in Django</h3><h3>What is a Sitemap?</h3><p>A sitemap is a structured list of URLs that helps search engines like Google index and understand the content of your website. It provides valuable information about your site’s structure and the importance of each page. While search engines can crawl websites without a sitemap, having one can significantly improve your website’s visibility in search engine results.</p><h3>Setting Up Sitemaps in Django</h3><ol><li>Configure the Sitemap</li></ol><p>In your Django project, create a sitemap by defining a class that inherits from django.contrib.sitemaps.Sitemap. This class should specify the URLs you want to include in your sitemap.</p><pre>from django.contrib import sitemaps<br><br>class MySitemap(sitemaps.Sitemap):<br>    i18n = True<br>    changefreq = &quot;weekly&quot;<br>    priority = 0.7<br>    protocol = &#39;https&#39;<br><br>    def items(self):<br>        return MyModel.objects.all()<br><br>    def lastmod(self, obj):<br>        return obj.last_modified</pre><p>2. Add the Sitemap to URL Patterns</p><p>To make your sitemap accessible to search engines, add it to your project’s URL patterns in the urls.py file:</p><pre>from django.contrib.sitemaps.views import sitemap<br>from .sitemaps import MySitemap<br><br>sitemaps = {<br>    &#39;mysitemap&#39;: MySitemap,<br>}<br><br>urlpatterns = [<br>    # ... other URL patterns ...<br>    path(&#39;sitemap.xml&#39;, sitemap, {&#39;sitemaps&#39;: sitemaps}),<br>]</pre><p>3. Include the Sitemap in Robots.txt</p><p>To inform search engines of the location of your sitemap, add it to your website’s robots.txt file:</p><pre>Sitemap: https://yourwebsite.com/sitemap.xml</pre><h3>Part 2: HTTPS Implementation</h3><h3>The Importance of HTTPS</h3><p>HTTPS (Hypertext Transfer Protocol Secure) is essential for securing data transmission between your web server and clients. It encrypts the data exchanged, ensuring privacy and integrity. Here’s how to enable HTTPS in Django:</p><ol><li>Obtain an SSL Certificate</li></ol><p>To enable HTTPS, you need an SSL/TLS certificate. You can obtain one from a Certificate Authority (CA) or use a service like Let’s Encrypt for free certificates.</p><p>2. Configure Django Settings:</p><p>In your Django project’s settings, make the following changes</p><pre># settings.py<br>SECURE_PROXY_SSL_HEADER = (&#39;HTTP_X_FORWARDED_PROTO&#39;, &#39;https&#39;)<br>SECURE_SSL_REDIRECT = True</pre><p>The first line ensures that Django recognizes HTTPS requests even when they pass through a proxy. The second line enforces SSL redirection.</p><p>3. Update Your Web Server</p><p>Configure your web server (e.g., Nginx, Apache) to use the SSL certificate and forward requests to your Django application.</p><p>4. Test and Monitor</p><p>Thoroughly test your website to ensure HTTPS is working correctly. Additionally, monitor your site for security updates and certificate expiration.</p><h3>Conclusion</h3><p>We’ve explored the significance of sitemaps in Django and the importance of implementing HTTPS for secure data transmission. By setting up sitemaps, you can improve your website’s search engine visibility, while HTTPS ensures the privacy and integrity of data exchanged between your server and users. Combining these two aspects will help you create a user-friendly and secure web application.</p><p>Remember that regularly updating your sitemap and monitoring your HTTPS implementation are crucial for maintaining a successful web presence. Stay informed about the latest best practices in SEO and security to keep your Django project ahead of the curve.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da52f0f49da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in Django]]></title>
            <link>https://joeymasip.medium.com/unit-testing-in-django-99a7473544ba?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a7473544ba</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 07:37:14 GMT</pubDate>
            <atom:updated>2023-10-02T07:37:14.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UccftM6Xjfl98fp4" /></figure><p>Unit testing is an essential practice in software development that helps ensure the reliability and correctness of your code. When working with a powerful web framework like Django, it’s crucial to understand how to write effective unit tests to verify the behavior of your applications. In this blog post, we will explore the world of unit testing in Django, covering the basics, best practices, and some useful tools and techniques.</p><h3>What is Unit Testing?</h3><p>Unit testing is a software testing method where individual units or components of a program are tested in isolation to ensure they work as expected. In Django, a unit test typically focuses on testing a specific function, method, or class to verify that it produces the correct output for various inputs and edge cases.</p><h3>Setting Up Your Django Project</h3><p>Before you can start writing unit tests in Django, make sure you have a Django project up and running. If you haven’t already, you can create a new Django project using the following command:</p><pre>django-admin startproject project_name</pre><p>Next, create a Django app within your project:</p><pre>cd project_name<br>python manage.py startapp app_name</pre><p>Now that your project structure is set up, let’s dive into writing unit tests for your Django application.</p><h3>Writing Your First Django Unit Test</h3><p>Django provides a testing framework that makes it easy to write unit tests. Test cases are created by subclassing the django.test.TestCase class. Let&#39;s create a simple unit test for a hypothetical Calculator class:</p><pre># app_name/tests.py </pre><pre>from django.test import TestCase<br>from .models import Calculator</pre><pre>class CalculatorTestCase(TestCase):</pre><pre>    def test_addition(self):<br>        calculator = Calculator()<br>        result = calculator.add(2, 3)<br>        self.assertEqual(result, 5)</pre><pre>    def test_subtraction(self):<br>        calculator = Calculator()<br>        result = calculator.subtract(5, 3)<br>        self.assertEqual(result, 2)</pre><p>In this example, we’ve created a CalculatorTestCase class that inherits from TestCase. Inside the class, we define two test methods: test_addition and test_subtraction. These methods create a Calculator instance, perform operations, and use self.assertEqual to verify the expected results.</p><h3>Running Your Django Unit Tests</h3><p>To execute your unit tests, run the following command from your project’s root directory:</p><pre>python manage.py test app_name</pre><p>Replace app_name with the name of your app containing the test cases. Django will automatically discover and run all the test methods in your app&#39;s test modules.</p><h3>Best Practices for Django Unit Testing</h3><p>Here are some best practices to keep in mind when writing unit tests for your Django applications:</p><h3>1. Test Isolation</h3><p>Ensure that each test is independent and doesn’t rely on the state or data modified by other tests. Django creates a new database for each test method, providing a clean slate for each test.</p><h3>2. Use Descriptive Test Names</h3><p>Give your test methods descriptive names that reflect what is being tested. This makes it easier to understand failures and maintain your test suite.</p><h3>3. Mock External Dependencies</h3><p>When testing code that interacts with external services or databases, consider using mocking libraries like unittest.mock to simulate those interactions. This keeps your tests fast and avoids external dependencies.</p><h3>4. Test Edge Cases</h3><p>Make sure to test both typical and edge cases to ensure your code handles unexpected scenarios gracefully.</p><h3>5. Continuous Integration</h3><p>Integrate your unit tests into your continuous integration (CI) pipeline to automatically run tests whenever code changes are pushed to your repository.</p><h3>Conclusion</h3><p>Unit testing is a crucial part of developing robust and maintainable Django applications. By following best practices and using Django’s testing framework, you can confidently verify the correctness of your code, catch bugs early in the development process, and ensure that your web applications work as intended. Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a7473544ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphism in Python and Django]]></title>
            <link>https://joeymasip.medium.com/polymorphism-in-python-and-django-2d87dd654a55?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d87dd654a55</guid>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 20:20:03 GMT</pubDate>
            <atom:updated>2021-06-22T11:41:46.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgJOdVQ8b-491l9YW0XZRw.png" /></figure><h3>What is polymorphism?</h3><p>Polymorphism is the ability of an object to take on many forms.</p><h3>When is polymorphism used?</h3><p>A polymorphic model is used when a single entity requires different functionality or information.</p><h3>Difference of Polymorphic and Abstract Classes</h3><p>Simply put, abstract instances do not exist. An abstract class is just a way of generalizing information for future children classes. Therefore, the only objects you’ll be able to relate are the children instances, never the parent abstract class.</p><p>If you want to relate to the parent abstract class, this is where polymorphic classes come in handy in Django.</p><p>I’m currently working on a project where I need classes related with a OneToMany relationship with that parent abstract class. If you relate it without polymorphism you’ll get the following error:</p><pre>abstract_base_model.ModelName.field: (fields.E300) Field defines a relation with model &#39;ModelName&#39;, which is either not installed, or is abstract.</pre><h3>Django Polymorphic models</h3><p>The good news is that it’s actually really straightforward to use polymorphism in Django! I’ve used the library <a href="https://django-polymorphic.readthedocs.io/en/stable/index.html">django-polymorphic</a></p><h4>Step 1: Install the library</h4><pre>pip install django-polymorphic</pre><h4>Step 2: Update the settings.py file</h4><pre>INSTALLED_APPS += (<br>    &#39;polymorphic&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>)</pre><h4>Step 3: Define your polymorphic model</h4><pre>from polymorphic.models import PolymorphicModel<br><br>class Block(PolymorphicModel):<br>    code = models.CharField(max_length=20, unique=True)</pre><h4>Step 4: Define your polymorphic children models</h4><pre>class BlockOne(Block):<br>    text = models.CharField(max_length=255)</pre><pre>class BlockTwo(Block):<br>    quote = models.CharField(max_length=255)</pre><h4>Step 5: Relate the polymorphic model to other models</h4><pre>from django.db import models</pre><pre>class BlockWrapper(models.Model):<br>    block = models.ForeignKey(<br>        Block,<br>        on_delete=models.SET_NULL,<br>        null=True,<br>        blank=False,<br>    )</pre><h4>Step 6: Query the models in the view</h4><p>You can check what kind of object is the block you get. So for instance:</p><pre># get all block wrappers<br>block_wrappers = blockwrapper_inst.blockwrapperblock_set.all()</pre><pre># iterate through the block wrappers<br>for block_wrapper in block_wrappers:</pre><pre>    # now we can check what kind of block it&#39;s related to<br>    block_inst = block_wrapper.block<br>        <br>    if isinstance(block_inst, BlockOne):<br>        # do stuff<br>    elif isinstance(block_inst, BlockTwo):<br>        # do other stuff</pre><p>You can also use instance_of or not_instance_of for narrowing the result to specific subtypes:</p><pre>Block.objects.instance_of(BlockOne)</pre><h3>Final notes</h3><p>Taking this same example, how does this really work in the backend? When you’re getting a BlockOne or a BlockTwo instance, internally Django will have to perform an INNER JOIN to get all the parent’s data. So, as the documentation says, taking performance into account “<em>While django-polymorphic makes subclassed models easy to use in Django, we still encourage to use them with caution</em>”</p><h4>Resources:</h4><p><a href="https://django-polymorphic.readthedocs.io/en/stable/index.html"><em>django-polymorphic library</em></a></p><p><a href="https://realpython.com/modeling-polymorphism-django-python/"><em>realpython</em></a></p><p>Happy codding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d87dd654a55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Console App with Docker]]></title>
            <link>https://joeymasip.medium.com/python-console-app-with-docker-a1de8f3626b1?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1de8f3626b1</guid>
            <category><![CDATA[requirements]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[console]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Sat, 11 May 2019 17:22:52 GMT</pubDate>
            <atom:updated>2019-05-14T20:04:10.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*qFXJP7OjHQ7mbNQinKhfBw.jpeg" /></figure><p>Today I want to write about dockerizing a python app, for instance, a python script.</p><p>Let’s imagine we want to run this script in different machines and we can’t control what python version they have, or even worse, we don’t know if python is installed or not, and what dependencies they have installed.</p><p>Docker helps us separate the code from the infrastructure so this blog post will be about this.</p><h3>Create the Python script</h3><p>Let’s create a simple python script. We’ll call the file script.py inside a src folder of the project.</p><pre>#src/script.py</pre><pre>print(&#39;hello world!&#39;)</pre><h3>Create the Dockerfile</h3><pre>#Dockerfile</pre><pre>FROM python:3.6</pre><pre>RUN mkdir /application<br>WORKDIR &quot;/application&quot;</pre><pre># Upgrade pip<br>RUN pip install --upgrade pip</pre><pre># Update<br>RUN apt-get update \<br>    &amp;&amp; apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*</pre><pre>ADD requirements.txt /application/<br>ADD src/script.py /application/</pre><pre>RUN pip install -r /application/requirements.txt</pre><pre>CMD [ &quot;python&quot;, &quot;script.py&quot; ]</pre><p>FROM tells Docker which image you base your image on. In the example, Python 3.</p><p>RUN tells Docker which additional commands to execute in bash console. In the example, we create a folder called application and we later install the requirements with the pip library we installed earlier.</p><p>CMD tells Docker to execute the command when the image loads. In the example, our python script.</p><h3>How to run</h3><p>In your console, build the docker image</p><pre>docker build -t python-script .</pre><p>And then run it</p><pre>docker run python-blog-scraper</pre><p>You should now get a ‘hello world’ printed 🙂</p><h3>Requirements</h3><p>You might ask yourself, why not just run the script, i.e python script.py from the console? My answer to that is, because of the requirements. As I mentioned earlier, systems change and it’s not realistic to think that you’ll always have the python version you need with the pip requirements installed.</p><p>So let’s test this out with some requirements.</p><pre>#requirements.txt</pre><pre>requests<br>beautifulsoup4</pre><p>Now let’s use these requirements in our script. For instance, let’s make a GET request to my blog and let’s scrape the contents of it, maybe the title of the blog posts and the first sentence. Print these in our console.</p><p>Note: Scraping is better done with Selenium in my opinion, but just as an example, let’s just use beatifulsoup’s library.</p><pre>#blog-scraper.py<br>import requests<br>from bs4 import BeautifulSoup<br></pre><pre>class BlogPost:<br>    title = None<br>    first_sentence = None</pre><pre>    def __init__(self, title, first_sentence):<br>        self.title = title<br>        self.first_sentence = first_sentence</pre><pre>    def __str__(self):<br>        return str(self.title) + &#39;\n&#39; + str(self.first_sentence)<br></pre><pre>def scrape(url):<br>    r = requests.get(url)</pre><pre>    if r.status_code == 200:<br>        soup = BeautifulSoup(r.content, features=&quot;html.parser&quot;)<br>        # print(soup.prettify())</pre><pre>        for article in soup.find_all(&#39;article&#39;, attrs={&#39;class&#39;: &#39;post&#39;}):<br>            title = article.find(&#39;h2&#39;, attrs={&#39;class&#39;: &#39;entry-title&#39;}).string<br>            first_sentence = article.find(&#39;div&#39;, attrs={&#39;class&#39;: &#39;entry-content&#39;}).find(&#39;p&#39;).string</pre><pre>            blog_post = BlogPost(<br>                title=title,<br>                first_sentence=first_sentence<br>            )<br>            print(blog_post)<br>            print(&#39;------------------------------&#39;)<br>    else:<br>        print(&#39;Whoops! Something went wrong!&#39;)<br></pre><pre>scrape(&quot;https://blog.joeymasip.com/&quot;)</pre><p>For readability, I created a model that has the information we want to keep to print later. We’re printing as we run the loop here, not saving anything to an array or database (this is just as an example so we can use libraries we just installed). Also, I renamed this blog-scraper.py, so don’t forget to update your Dockerfile!</p><pre>#Dockerfile<br>#...<br>ADD requirements.txt /application/<br>ADD src/blog-scraper.py /application/</pre><pre>RUN pip install -r /application/requirements.txt</pre><pre>CMD [ &quot;python&quot;, &quot;blog-scraper.py&quot; ]<br>#...</pre><p>Now let’s rebuild the image and run it.</p><pre>docker build -t python-script .<br>docker run python-blog-scraper</pre><p>And there we have it, you should have the blog posts being printed in your console!</p><h3>Conclusion and Resources</h3><p>As you can see, we’ve added requirements and packaged everything in a Docker image, so we can easily deploy this simple app to any machine that has docker installed and run it with no requirement missing or version issues.</p><p>I’ve uploaded the <a href="https://github.com/joeymasip/docker-python-console-app">source code in GitHub here</a>.<br>Link to Python library <a href="https://pypi.org/project/beautifulsoup4/">Beautifulsoup docs</a>.<br>Link to Python library <a href="https://pypi.org/project/requests/">Requests docs</a>.</p><p>Happy coding! 🙂</p><p><em>Originally published at </em><a href="https://blog.joeymasip.com/python-console-app-with-docker/"><em>Joey’s blog.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1de8f3626b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create an API with Symfony 4 and JWT]]></title>
            <link>https://joeymasip.medium.com/how-to-create-an-api-with-symfony-4-and-jwt-b2334a8fbec2?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2334a8fbec2</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[symfony4]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 23:15:18 GMT</pubDate>
            <atom:updated>2019-01-25T00:51:06.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMhBQtRXmww7TKiADgtGxg.jpeg" /></figure><p>Today we’re going to create a Symfony 4 API web app from scratch — I’ll walk you through all the steps, so by the end of this tutorial, you should be able to create, configure and run a web app with API endpoints and protected with JWT authentication.</p><p>Also, I’ve uploaded all the <a href="https://github.com/joeymasip/symfony4-api-jwt">source code here</a> so you can follow through the tutorial or you can download the code and play with it while you read.</p><h3>1. Docker</h3><p>To set our development environment, we’ll use Docker — you probably already know by now how much I love Docker 🙂</p><p>Let’s start by creating a docker-compose.yaml file with php7, mysql for database and nginx for the webserver.</p><pre>#docker-compose.yaml<br>version: &quot;3.1&quot;</pre><pre>volumes:<br>    db-data:</pre><pre>services:<br>    mysql:<br>      image: mysql:5.6<br>      container_name: ${PROJECT_NAME}-mysql<br>      working_dir: /application<br>      volumes:<br>        - db-data:/application<br>      environment:<br>        - MYSQL_ROOT_PASSWORD=docker_root<br>        - MYSQL_DATABASE=sf4_db<br>        - MYSQL_USER=sf4_user<br>        - MYSQL_PASSWORD=sf4_pw<br>      ports:<br>        - &quot;8306:3306&quot;</pre><pre>    webserver:<br>      image: nginx:alpine<br>      container_name: ${PROJECT_NAME}-webserver<br>      working_dir: /application<br>      volumes:<br>        - .:/application<br>        - ./docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf<br>      ports:<br>        - &quot;8000:80&quot;</pre><pre>    php-fpm:<br>      build: docker/php-fpm<br>      container_name: ${PROJECT_NAME}-php-fpm<br>      working_dir: /application<br>      volumes:<br>        - .:/application<br>        - ./docker/php-fpm/php-ini-overrides.ini:/etc/php/7.2/fpm/conf.d/99-overrides.ini<br>      environment:<br>        XDEBUG_CONFIG: &quot;remote_host=${localIp}&quot;</pre><p>Also, don’t forget the .env file with your PROJECT_NAME variable. On this ocasion, for the php-fpm and the nginx, I’m pointing to docker folder, so I can override the nginx.conf file and the php-fpm Dockerfile with special configuration, such as xdebug.</p><p><a href="https://github.com/joeymasip/symfony4-api-jwt/blob/5f70d30f2854303fce395653733cc134a1e3fa9e/docker/nginx/nginx.conf">Link to docker/nginx/nginx.conf file</a><br><a href="https://github.com/joeymasip/symfony4-api-jwt/blob/5f70d30f2854303fce395653733cc134a1e3fa9e/docker/php-fpm/Dockerfile">Link to docker/php-fpm/Dockerfile</a><br><a href="https://github.com/joeymasip/symfony4-api-jwt/blob/5f70d30f2854303fce395653733cc134a1e3fa9e/docker/php-fpm/php-ini-overrides.ini">Link to docker/php-fpm/php-ini-overrides.ini</a></p><p>Once we’re ready, we can build and run.</p><pre>docker-compose build<br>docker-compose up -d</pre><h3>2. Creating a Symfony project</h3><p>First, let’s go into the bash</p><pre>docker-compose exec php-fpm bash</pre><p>Let’s create a symfony 4 project</p><pre>#inside php-fpm bash<br>composer create-project symfony/website-skeleton symfony</pre><p>Clean up</p><pre>#inside php-fpm bash<br>mv /application/symfony/* /application<br>mv /application/symfony/.* /application<br>rm -Rf /application/symfony</pre><p><a href="https://blog.joeymasip.com/docker-for-symfony-4/">More on how to create a symfony 4 application with docker here</a></p><p>If we open the browser <a href="http://localhost:8000/">http://localhost:8000/</a> we should see the Symfony welcome page. So now that we have a symfony 4 app up and running, let’s start putting stuff into it!</p><h3>3. Mapping our User in the database</h3><p>Inside the php-fpm bash, let’s start with installing the FOSUserBundle to have a User base entity we can relate to.</p><pre>#inside php-fpm bash<br>composer require friendsofsymfony/user-bundle &quot;~2.0&quot;</pre><p>After donwloading the packages and clearing the cache…you’ll probably get the error</p><pre>&quot;The child node &quot;db_driver&quot; at path &quot;fos_user&quot; must be configured.&quot; </pre><p>Don’t panic, this is unfortunately normal. Reason being is it’s trying to clear the cache before configuration is correct.</p><h3>3.1 Configuriation</h3><pre>#config/services.yaml</pre><pre># FOS user config<br>fos_user:<br>    db_driver:      orm # other valid values are &#39;mongodb&#39;, &#39;couchdb&#39; and &#39;propel&#39;<br>    firewall_name:  main<br>    user_class:     App\Entity\User<br>    from_email:<br>        address: &quot;no-reply@joeymasip.com&quot;<br>        sender_name: &quot;Joey&quot;<br>    registration:<br>#        form:<br>#            type: AppBundle\Form\UserRegisterType<br>        confirmation:<br>            enabled: <strong>true</strong><br>            template:   FOSUserBundle:Registration:email.txt.twig<br>            from_email:<br>                address:        &quot;no-reply@joeymasip.com&quot;<br>                sender_name:    &quot;No Reply Registration&quot;<br>    service:<br>        mailer: fos_user.mailer.twig_swift<br>    resetting:<br>        email:<br>            template:   FOSUserBundle:Resetting:email.txt.twig</pre><h3>3.2 Creating the User class</h3><pre>namespace App\Entity;</pre><pre>use FOS\UserBundle\Model\User as BaseUser;<br>use Doctrine\ORM\Mapping as ORM;</pre><pre>/**<br> * @ORM\Entity<br> * @ORM\Table(name=&quot;fos_user&quot;)<br> */<br>class User extends BaseUser<br>{<br>    /**<br>     * @ORM\Id<br>     * @ORM\Column(type=&quot;integer&quot;)<br>     * @ORM\GeneratedValue(strategy=&quot;AUTO&quot;)<br>     */<br>    protected $id;</pre><pre>    public function __construct()<br>    {<br>        parent::__construct();<br>        // your own logic<br>    }<br>}</pre><h3>3.3 Configuring main firewall</h3><pre>#config/packages/security.yaml<br>security:<br>    encoders:<br>        FOS\UserBundle\Model\UserInterface: bcrypt<br>        Symfony\Component\Security\Core\User\User: plaintext</pre><pre>    role_hierarchy:<br>        ROLE_ADMIN:         ROLE_USER<br>        ROLE_SUPER_ADMIN:   ROLE_ADMIN</pre><pre>    providers:<br>        chain_provider:<br>            chain:<br>                providers: [in_memory, fos_userbundle]<br>        in_memory:<br>            memory:<br>                users:<br>                    superadmin:<br>                        password: &#39;superadminpw&#39;<br>                        roles: [&#39;ROLE_SUPER_ADMIN&#39;]<br>        fos_userbundle:<br>            id: fos_user.user_provider.username</pre><pre>    access_control:<br>        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }<br>        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }<br>        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }<br>        - { path: ^/admin/, role: ROLE_ADMIN }</pre><pre>    firewalls:<br>        dev:<br>            pattern: ^/(_(profiler|wdt)|css|images|js)/<br>            security: <strong>false</strong><br>        main:<br>            pattern: ^/<br>            form_login:<br>                provider: chain_provider<br>                csrf_token_generator: security.csrf.token_manager<br>                login_path: fos_user_security_login<br>                check_path: fos_user_security_check<br>                always_use_default_target_path: <strong>false</strong><br>                default_target_path: admin_admin_index</pre><pre>            logout:<br>                path:   fos_user_security_logout<br>                target: fos_user_security_login<br>            anonymous:    <strong>true</strong></pre><h3>3.4 Creating the register API endpoint</h3><p>Now that we have a User entity mapped in our database, let’s create a register API endpoint so we can add new users.</p><p>I’ve created an Api folder, and added in routes.yaml</p><pre>#config/routes.yaml<br>api:<br>    prefix: /api<br>    resource: &#39;../src/Controller/Api&#39;</pre><p>So all our API endpoints will have the prefix api</p><p>So now let’s create a Controller for registering our users.</p><pre>namespace App\Controller\Api;</pre><pre>use FOS\UserBundle\Model\UserManagerInterface;<br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\HttpFoundation\Request;<br>use Symfony\Component\HttpFoundation\Response;<br>use App\Entity\User;<br>use Symfony\Component\Routing\Annotation\Route;<br>use Symfony\Component\Validator\Validation;<br>use Symfony\Component\Validator\Constraints as Assert;</pre><pre>/**<br> * @Route(&quot;/auth&quot;)<br> */<br>class ApiAuthController extends AbstractController<br>{<br>    /**<br>     * @Route(&quot;/register&quot;, name=&quot;api_auth_register&quot;,  methods={&quot;POST&quot;})<br>     * @param Request $request<br>     * @param UserManagerInterface $userManager<br>     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse<br>     */<br>    public function register(Request $request, UserManagerInterface $userManager)<br>    {<br>        $data = json_decode(<br>            $request-&gt;getContent(),<br>            true<br>        );</pre><pre>        $validator = Validation::createValidator();</pre><pre>        $constraint = new Assert\Collection(array(<br>            // the keys correspond to the keys in the input array<br>            &#39;username&#39; =&gt; new Assert\Length(array(&#39;min&#39; =&gt; 1)),<br>            &#39;password&#39; =&gt; new Assert\Length(array(&#39;min&#39; =&gt; 1)),<br>            &#39;email&#39; =&gt; new Assert\Email(),<br>        ));</pre><pre>        $violations = $validator-&gt;validate($data, $constraint);</pre><pre>        if ($violations-&gt;count() &gt; 0) {<br>            return new JsonResponse([&quot;error&quot; =&gt; (string)$violations], 500);<br>        }</pre><pre>        $username = $data[&#39;username&#39;];<br>        $password = $data[&#39;password&#39;];<br>        $email = $data[&#39;email&#39;];</pre><pre>        $user = new User();</pre><pre>        $user<br>            -&gt;setUsername($username)<br>            -&gt;setPlainPassword($password)<br>            -&gt;setEmail($email)<br>            -&gt;setEnabled(true)<br>            -&gt;setRoles([&#39;ROLE_USER&#39;])<br>            -&gt;setSuperAdmin(false)<br>        ;</pre><pre>        try {<br>            $userManager-&gt;updateUser($user, true);<br>        } catch (\Exception $e) {<br>            return new JsonResponse([&quot;error&quot; =&gt; $e-&gt;getMessage()], 500);<br>        }</pre><pre>        return new JsonResponse([&quot;success&quot; =&gt; $user-&gt;getUsername(). &quot; has been registered!&quot;], 200);<br>    }<br>}</pre><p>Note: validation and data handling for user creation should be decoupled from the controller, it has been put together just for the example.</p><p>If you now send a POST request with the data to <a href="http://localhost:8000/api/auth/register,">http://localhost:8000/api/auth/register,</a> you should get a registered user, and validation error if the data in the json is incorrect or the keys some keys are missing. Also, you’ll get a doctrine error if the username or emails you try to add in the database already exist, as they are unique keys in the FOSUserBundle base User we’re using.</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; http://localhost:8000/api/auth/register -d &#39;{&quot;username&quot;:&quot;patata&quot;,&quot;password&quot;:&quot;fregida&quot;, &quot;email&quot;:&quot;patatafregida@joeymasip.com&quot;}&#39;</pre><h3>4. LexikJWTAuthenticationBundle</h3><p>Now it’s time for the login and recieving a token. For this, we’ll use JWT.</p><pre>#inside php-fpm bash<br>composer require lexik/jwt-authentication-bundle</pre><h3>4.1 Private and Public keys</h3><p>First, let’s create the private and public keys for our project, with a passphrase.</p><pre>#inside php-fpm bash<br>mkdir config/jwt<br>openssl genrsa -out config/jwt/private.pem -aes256 4096<br>openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem</pre><h3>4.2 Configuration</h3><p>Once you’ve created the keys, you can add the config in the yaml and .env files. The passphrase you created the keys with must relate to the config.</p><pre>#config/packages/lexik_jwt_authentication.yaml<br>lexik_jwt_authentication:<br>    secret_key: &#39;%env(resolve:JWT_SECRET_KEY)%&#39;<br>    public_key: &#39;%env(resolve:JWT_PUBLIC_KEY)%&#39;<br>    pass_phrase: &#39;%env(JWT_PASSPHRASE)%&#39;<br>    token_ttl: 3600</pre><pre>#.env<br>JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem<br>JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem<br>JWT_PASSPHRASE=sf4jwt</pre><h3>4.3 Routes</h3><p>Once we’ve created the keys and configured the bundle, it’s time to add the login route in our routes.yaml</p><pre>#config/routes.yaml<br>api_auth_login:<br>    path: /api/auth/login<br>    methods:  [POST]</pre><pre>api:<br>    prefix: /api<br>    resource: &#39;../src/Controller/Api&#39;</pre><p>Note: it’s important to put the specific routes before the main ones. See that /api/auth/login is more specific than /api</p><h3>4.4 Firewalls</h3><p>And now we have to tell our app to handle this route through configuration, since we won’t be implementing it in our controller.</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    firewalls:<br>        dev:<br>            #...</pre><pre>        api_login:<br>            pattern:  ^/api/auth/login<br>            stateless: <strong>true</strong><br>            anonymous: <strong>true</strong><br>            json_login:<br>                provider: chain_provider<br>                check_path:               /api/auth/login<br>                success_handler:          lexik_jwt_authentication.handler.authentication_success<br>                failure_handler:          lexik_jwt_authentication.handler.authentication_failure<br>            provider: chain_provider</pre><pre>        main:<br>        	#...</pre><p>Again, make sure to put api firewalls before the main. The pattern used for the “main” firewall catches everything, the pattern for “api” catches “/api”, so you should put the wildcard AKA main at the end, after the specific cases.</p><p>If we now send a POST request to <a href="http://localhost:8000/api/auth/login">http://localhost:8000/api/auth/login</a> with the username and password from the user we created earlier, you should get a response with the token!</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; http://localhost:8000/api/auth/login -d &#39;{&quot;username&quot;:&quot;patata&quot;,&quot;password&quot;:&quot;fregida&quot;}&#39;</pre><p>We’ll get the 200 response</p><pre>{&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOi...&quot;}</pre><p>All of this is great!</p><p>Now it’s time to protect our API calls now that we have tokens right? This is done by creating a new firewall in our security.yaml.</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    firewalls:<br>        dev:<br>            #...</pre><pre>        api_login:<br>            #...</pre><pre>		api:<br>            pattern: ^/api<br>            stateless: <strong>true</strong><br>            anonymous: <strong>false</strong><br>            provider: chain_provider<br>            guard:<br>                authenticators:<br>                    - lexik_jwt_authentication.jwt_token_authenticator<br>        main:<br>        	#...</pre><p>Now if we try to call to our previous route <a href="http://localhost:8000/api/auth/register">http://localhost:8000/api/auth/register</a> without any Authorization header, we’ll see that we get a 401 error.</p><pre>{<br>    &quot;code&quot;: 401,<br>    &quot;message&quot;: &quot;JWT Token not found&quot;<br>}</pre><p>This doesn’t make sense because someone who has to register doesn’t have a token yet! Let’s add one last firewall so anonymous users can register.</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    firewalls:<br>        dev:<br>            #...</pre><pre>        api_login:<br>            #...</pre><pre>        api_register:<br>            pattern:  ^/api/auth/register<br>            stateless: <strong>true</strong><br>            anonymous: <strong>true</strong></pre><pre>		api:<br>            #...</pre><pre>        main:<br>        	#...</pre><p>To authenticate in our api calls, we just need to add an Authorization header with the Bearer prefix followed by the JWT token, so the value of the header could be for example:</p><pre>Bearer eyJ0eXAiOiJKV1QiLCJhbGc...</pre><p>Since we added the anonymous in the /api/auth/register pattern in our firewall, we should now be able to register without sending any token in the header.</p><p>Moreover, if you want to open API calls even without a JWT token in the Authorization header, you can just set anonymour to true in the api firewall, like so:</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    firewalls:<br>        dev:<br>            #...</pre><pre>        api_login:<br>            #...</pre><pre>        api_register:<br>        	#...</pre><pre>		api:<br>            #...<br>            anonymous: <strong>true</strong><br>            #...</pre><pre>        main:<br>        	#...</pre><p>Now we can add the ACL to control access to fully secure all the prefix routes in our security.yaml</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    access_control:<br>        #...<br>        - { path: ^/api/auth/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }<br>        - { path: ^/api/auth/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }<br>        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }</pre><p>One last thing, once we register, it would be nice to receive the token inmediately. It would be wierd for an app to make you register and then make you login afterwards. We can redirect to the /auth/login route once a User has been created and return the response.</p><p>So in our previous ApiAuthController,</p><pre>namespace App\Controller\Api;</pre><pre>/**<br> * @Route(&quot;/auth&quot;)<br> */<br>class ApiAuthController extends AbstractController<br>{<br>    /**<br>     * @Route(&quot;/register&quot;, name=&quot;api_auth_register&quot;,  methods={&quot;POST&quot;})<br>     * @param Request $request<br>     * @param UserManagerInterface $userManager<br>     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse<br>     */<br>    public function register(Request $request, UserManagerInterface $userManager)<br>    {<br>        #...</pre><pre>        # Code 307 preserves the request method, while redirectToRoute() is a shortcut method.<br>        return $this-&gt;redirectToRoute(&#39;api_auth_login&#39;, [<br>            &#39;username&#39; =&gt; $data[&#39;username&#39;],<br>            &#39;password&#39; =&gt; $data[&#39;password&#39;]<br>        ], 307);<br>    }<br>}</pre><h3>5. NelmioApiDocBundle</h3><p>Let’s add some docs in our API project.</p><pre>#inside php-fpm bash<br>composer require nelmio/api-doc-bundle</pre><h3>5.1 Configuration</h3><pre>#config/packages/nelmio_api_doc.yaml<br>nelmio_api_doc:<br>    documentation:<br>#        schemes: [http, https]<br>        info:<br>            title: Symfony JWT API<br>            description: Symfony JWT API docs<br>            version: 1.0.0<br>        securityDefinitions:<br>            Bearer:<br>                type: apiKey<br>                description: &#39;Authorization: Bearer {jwt}&#39;<br>                name: Authorization<br>                in: header<br>        security:<br>            - Bearer: []<br>    areas: # to filter documented areas<br>        path_patterns:<br>            - ^/api(?!/doc$) # Accepts routes under /api except /api/doc</pre><h3>5.2 Routing</h3><p>Also uncomment the app.swagger_ui route in</p><pre>#config/routes/nelmio_api_doc.yaml<br>app.swagger_ui:<br>    path: /api/doc<br>    methods: GET<br>    defaults: { _controller: nelmio_api_doc.controller.swagger_ui }</pre><h3>5.3 ACL</h3><p>Finally, we want to add this to our ACL</p><pre>#config/packages/security.yaml<br>security:<br>	#...<br>    access_control:<br>        #...<br>        - { path: ^/api/doc, roles: IS_AUTHENTICATED_ANONYMOUSLY }<br>        #...<br>        - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }</pre><p>Again, remember to put this specific route before the generic /api prefix</p><p>If we open the browser <a href="http://localhost:8000/api/doc">http://localhost:8000/api/doc</a> we should see the swagger with the jwt api key auth for secured routes.</p><h3>6. NelmioCorsBundle</h3><p>Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. So if we want to access our API from a different domain we’ll probably run into CORS problems, so let’s quickly set up NelmioCorsBundle!</p><pre>#inside php-fpm bash<br>composer req cors</pre><p>Change the default configuration from this</p><pre>#config/packages/nelmio_cors.yaml<br>nelmio_cors:<br>    defaults:<br>        origin_regex: <strong>true</strong><br>        allow_origin: [&#39;%env(CORS_ALLOW_ORIGIN)%&#39;]<br>        allow_methods: [&#39;GET&#39;, &#39;OPTIONS&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;]<br>        allow_headers: [&#39;Content-Type&#39;, &#39;Authorization&#39;]<br>        expose_headers: [&#39;Link&#39;]<br>        max_age: 3600<br>    paths:<br>        &#39;^/&#39;: <strong>~</strong></pre><p>To this</p><pre>#config/packages/nelmio_cors.yaml<br>nelmio_cors:<br>    defaults:<br>        allow_credentials: <strong>false</strong><br>        allow_origin: []<br>        allow_headers: []<br>        allow_methods: []<br>        expose_headers: []<br>        max_age: 0<br>        hosts: []<br>        origin_regex: <strong>false</strong><br>        forced_allow_origin_value: <strong>~</strong><br>    paths:<br>        &#39;^/api/&#39;:<br>            allow_origin: [&#39;*&#39;]<br>            allow_headers: [&#39;Content-Type&#39;, &#39;Authorization&#39;]<br>            allow_methods: [&#39;POST&#39;, &#39;PUT&#39;, &#39;GET&#39;, &#39;DELETE&#39;]<br>            max_age: 3600<br>        &#39;^/&#39;:<br>            origin_regex: <strong>true</strong><br>            allow_origin: [&#39;^http://localhost:[0-9]+&#39;]<br>            allow_headers: [&#39;Content-Type&#39;, &#39;Authorization&#39;]<br>            allow_methods: [&#39;POST&#39;, &#39;PUT&#39;, &#39;GET&#39;, &#39;DELETE&#39;]<br>            max_age: 3600<br>            hosts: [&#39;^api\.&#39;]</pre><p>This will allow all origins for the /api prefix so any mobile app can now use our API. Feel free to play with the regex until you’re comfortable with the result.</p><h3>7. Creating an example API enpoint</h3><p>As an example, let’s create an API endpoint for retrieving a user.</p><p>I’ll create a new controller</p><pre>namespace App\Controller\Api;</pre><pre>use App\Entity\User;<br>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;<br>use Symfony\Component\HttpFoundation\JsonResponse;<br>use Symfony\Component\Routing\Annotation\Route;<br>use Symfony\Component\Serializer\Serializer;<br>use Symfony\Component\Serializer\Encoder\XmlEncoder;<br>use Symfony\Component\Serializer\Encoder\JsonEncoder;<br>use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;</pre><pre>/**<br> * @Route(&quot;/user&quot;)<br> */<br>class ApiUserController extends AbstractController<br>{<br>    /**<br>     * @Route(&quot;/{id}&quot;, name=&quot;api_user_detail&quot;, methods={&quot;GET&quot;})<br>     * @param User $user<br>     * @return JsonResponse<br>     */<br>    public function detail(User $user)<br>    {<br>        $this-&gt;denyAccessUnlessGranted(&#39;view&#39;, $user);<br>        return new JsonResponse($this-&gt;serialize($user), 200);<br>    }</pre><pre>    protected function serialize(User $user)<br>    {<br>        $encoders = [new XmlEncoder(), new JsonEncoder()];<br>        $normalizers = [new ObjectNormalizer()];</pre><pre>        $serializer = new Serializer($normalizers, $encoders);</pre><pre>        $json = $serializer-&gt;serialize($user, &#39;json&#39;);</pre><pre>        return $json;<br>    }<br>}</pre><p>Note: Please consider serializing in a separate service, this is a just some example code.</p><p>We’ll need a voter to let us know if a user is allowed to be retrieved or not. It should only be retrieved if it’s himself, or if it’s an admin right?</p><pre>namespace App\Security;</pre><pre>use App\Entity\User;<br>use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;<br>use Symfony\Component\Security\Core\Authorization\Voter\Voter;<br>use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;</pre><pre>class UserVoter extends Voter<br>{<br>    // these strings are just invented: you can use anything<br>    const VIEW = &#39;view&#39;;<br>    const EDIT = &#39;edit&#39;;</pre><pre>    private $decisionManager;</pre><pre>    public function __construct(AccessDecisionManagerInterface $decisionManager)<br>    {<br>        $this-&gt;decisionManager = $decisionManager;<br>    }</pre><pre>    protected function supports($attribute, $subject)<br>    {<br>        // if the attribute isn&#39;t one we support, return false<br>        if (!in_array($attribute, array(self::VIEW, self::EDIT))) {<br>            return false;<br>        }</pre><pre>        // only vote on User objects inside this voter<br>        if (!$subject instanceof User) {<br>            return false;<br>        }</pre><pre>        return true;<br>    }</pre><pre>    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)<br>    {<br>        $user = $token-&gt;getUser();</pre><pre>        if (!$user instanceof User) {<br>            // the user must be logged in; if not, deny access<br>            return false;<br>        }</pre><pre>        // ROLE_SUPER_ADMIN can do anything! The power!<br>        if ($this-&gt;decisionManager-&gt;decide($token, array(&#39;ROLE_ADMIN&#39;))) {<br>            return true;<br>        }</pre><pre>        // you know $subject is a User object, thanks to supports<br>        /** @var User $userSubject */<br>        $userSubject = $subject;</pre><pre>        switch ($attribute) {<br>            case self::VIEW:<br>                return $this-&gt;canView($userSubject, $user);<br>            case self::EDIT:<br>                return $this-&gt;canEdit($userSubject, $user);<br>        }</pre><pre>        throw new \LogicException(&#39;This code should not be reached!&#39;);<br>    }</pre><pre>    private function canView(User $userSubject, User $user)<br>    {<br>        // if they can edit, they can view<br>        if ($this-&gt;canEdit($userSubject, $user)) {<br>            return true;<br>        }</pre><pre>        // the User object could have, for example, a method isPrivate()<br>        // that checks a boolean $private property<br>        return $user === $userSubject;<br>    }</pre><pre>    private function canEdit(User $userSubject, User $user)<br>    {<br>        // this assumes that the data object has a getOwner() method<br>        // to get the entity of the user who owns this data object<br>        return $user === $userSubject;<br>    }<br>}</pre><p>As you can see, we can get the user from the TokenInterface. The function</p><pre>$tokenInterface-&gt;getUser()</pre><p>will return a UserInterface aka our User. The TokenInterface can be injected in an EventListener, Controller, etc. so you can always know what user is making the request.</p><p><a href="https://blog.joeymasip.com/security-and-voters-in-symfony-3-4/">More on how to use voters for securing your app here.</a></p><p>Let’s try getting that user with the GET request.</p><pre>curl -X GET -H &quot;Content-Type: application/json&quot; <a href="http://localhost:8000/api/user/1">http://localhost:8000/api/user/1</a></pre><p>The response is a 401</p><pre>{&quot;code&quot;:401,&quot;message&quot;:&quot;JWT Token not found&quot;}</pre><p>This time let’s add the token in the header, like so</p><pre>curl -X GET -H &quot;Content-Type: application/json&quot; -H &quot;Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1NDgyODI4NjUsImV4cCI6MTU0ODI4NjQ2NSwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoicGF0YXRhIn0.SLB40jBqtbY7Ql5DI4L4rZBEcH5hXNqn9u0eVYOCtlE_vqa_1RYQzHHVy7iMbmP4CMjSKUiBlGzuIBGApRmD36CFKgdMdfXuqrHeEFB-BUsd-HezdLg6U762GnLbe4g4vHzg9XKZVCzRtpboGUKgVycIaMdfiZ1FvUkJeZvdS_5HgHW43LrSqntPlbEaNaEYv7mrkzTQNi1WiKwJaDCW5M0JgRkfbHoUYXMadFUxR4KSnaXRQAwxZnqqPBW4dRs97ho5A15XKpuxmEWemvhMs0XL9E8KyPNG7ZipLis4JGs3X9Mn-ov4RDCqYbShSNbtj_F2gcakXL97FF3myLn1U2XfIzuwxq9ZIJnGLtemKgPlxSB1uxX5ep9aYxppuXpwxY0vGr9MsOgyL3kkuMqeXvFDN46bY-3P8TLOqEuPrrlKYuRfMQv6Wrhdq0orl3eo7t83YCb_Z-Mf7yeDDGeJsftaj4pALJUw4Ovo6Kv_4gNcG3VQpkJr4XtnULAcO9O_OJLgVOBXoOc7lUQmokdvAGeltEBmYIZD_2KtGrTwS4rL55LMn3MawL4dKVIAg8aaYbPDCxkk1t3LdZyI5zSUiJvLaCrMM8ZhJ7eJ0rKod2-d_dZcYPzQ5RF_wD8spuw1pkT6r4hMyTJvGQUUDjN-3E-MkNBHT8Ku8Z8I7a65x5M&quot; <a href="http://localhost:8000/api/user/1">http://localhost:8000/api/user/1</a></pre><p>This will return the user serialized, so success!</p><h3>Conclusion</h3><p>We’ve created a project from scratch and we’ve installed a User library, a JWT library, an API doc library and a CORS library. We’ve created a register endpoint, we’ve protected our api with firewalls and we’ve created a user endpoint with a voter to test authentication and authorization.</p><p>This is a great start to develop your API project and scale it up!</p><p>Happy coding! 🙂</p><h3>Resources</h3><p><a href="https://github.com/joeymasip/symfony4-api-jwt">Link to symfony4-api-jwt GitHub project.</a><br><a href="https://github.com/joeymasip/symfony4-api-jwt/commits/master">Link to all commits.</a></p><p><a href="https://www.docker.com/">Docker</a> to set up the development environment.<br><a href="https://github.com/lexik/LexikJWTAuthenticationBundle">LexikJWTAuthenticationBundle</a> to authenticate users on our API side.<br><a href="https://symfony.com/doc/current/bundles/FOSUserBundle/index.html">FOSUserBundle</a> for User entities.<br><a href="https://symfony.com/doc/master/bundles/NelmioApiDocBundle/index.html">NelmioApiDocBundle</a> for our API docs.<br><a href="https://github.com/nelmio/NelmioCorsBundle">NelmioCorsBundle</a> for Cross Origin.</p><p><em>Originally published at </em><a href="https://blog.joeymasip.com/how-to-create-an-api-with-symfony-4-and-jwt/"><em>Joey’s blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2334a8fbec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django project, apps structure and folders]]></title>
            <link>https://joeymasip.medium.com/django-project-apps-structure-and-folders-b9436cc22b98?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9436cc22b98</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[folders]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 19:29:43 GMT</pubDate>
            <atom:updated>2018-12-09T20:26:06.419Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post I’ll talk about Django folders structure inside a project.</p><p>After developing a few projects with Django 1.11 and Django 2.0, I’ve stumbled with somewhat an issue that’s been bothering me. When you create projects and apps in Django, as the tutorial shows you, apps will be created inside the main project folder, at the same level of the project’s settings folder (usually it’s the folder that has the same name as your project).</p><p>So basically, what you end up with is a container folder and inside has the project config folder, and many other folders with the app names.</p><p>So as a result, you get different ordering in the folders for every new project, as folders will usually order by name inside your IDE, i.e PyCharm.</p><p>So, for instance, if your app is called ‘apples’ and your project is called ‘mysite’, then the order will be:</p><pre>- apples<br>- mysite</pre><p>Let’s also assume you’re using docker, so you probably have a docker folder, now we have:</p><pre>- apples<br>- docker<br>- mysite</pre><p>But if you create an app called ‘oranges’, now your project folder is:</p><pre>- apples<br>- docker<br>- mysite<br>- oranges</pre><p>This is unconfortable because you never know which is the project’s config folder and which ones are the different app folders, so you keep opening the wrong folders all the time!! This is awful, as programers, we tend strive for efficiency!! :)</p><p>So my strategy for now is to bundle all apps inside an apps folder, so my project will always look like:</p><pre>- apps<br>- docker<br>- mysite</pre><p>And there you have it, nicely ordered apps inside your project!!</p><p>To include them in your settings, you just have to remember to include the namespace</p><pre>&#39;apps.your_app_name&#39;</pre><p>, so if your app is called apples</p><pre>INSTALLED_APPS += [&#39;apps.apples&#39;]</pre><p>Also, when importing classes in different files, just use the namespace. So imagine, I need to import the Apple class defined in my models inside my apples app, would do something like so:</p><p>from apps.apples.models import Apple</p><p>If you’ve read until here, it means you REALLY CARE about your project folder structure, so here’s a handy script I’ve created to start apps. It’s just a wrapper from the django startapp command, but it takes care of the apps folder, etc.</p><pre>#!/usr/bin/env bash<br><br>if [ &quot;$1&quot; == &quot;-h&quot; ]; then<br>	echo &quot;This script will create an app inside the apps folder&quot;<br>	echo &quot;To use type the following line:&quot;<br>	echo &quot;bash start-app.sh app_name&quot;<br>	echo &quot;Replace app_name with the actual name for your app&quot;<br>elif [ &quot;$1&quot; != &quot;&quot; ]; then<br>    if [ ! -d &quot;apps&quot; ]; then<br>        mkdir apps<br>        touch apps/__init__.py<br>    fi<br>    mkdir apps/$1<br>    if [ -f /.dockerenv ]; then<br>        python manage.py startapp $1 apps/$1<br>    else<br>        docker-compose run django python manage.py startapp $1 apps/$1<br>    fi<br>    echo &quot;Success! The app $1 has been aded, don&#39;t forget to add INSTALLED_APPS += [&#39;apps.$1&#39;] in your project&#39;s settings.py&quot;<br>else<br>	echo &quot;Error! One parameter is expected: app_name&quot;<br>fi</pre><p>I call the file “start-app.sh”, so to use it just type</p><pre>bash start-app.sh app_name</pre><p>Happy coding!!</p><p><em>Originally published at </em><a href="http://blog.joeymasip.com/django-project-apps-structure-and-folders/"><em>Joey’s blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9436cc22b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gedmo Translations in Symfony 4]]></title>
            <link>https://joeymasip.medium.com/gedmo-translations-in-symfony-4-b5ca1faa15a0?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5ca1faa15a0</guid>
            <category><![CDATA[gedmo]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[symfony4]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Sun, 16 Sep 2018 18:07:35 GMT</pubDate>
            <atom:updated>2018-10-01T11:44:21.409Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I’ve had to install Gedmo Translations into a Symfony 4 app and I had some trouble, so after fixing them problems I thought of writing them down in case someone else can benefit from it :)</p><p>Let’s start fromt he begginig.</p><h4>Create a Symfony 4 project</h4><p>Please use docker! :) More info here in the <a href="https://blog.joeymasip.com/docker-for-symfony-4/">Docker for Symfony 4 post</a>.</p><p>Here’s what my docker.compose.yml looks like</p><pre>#docker.compose.yml<br>version: &quot;3.1&quot;<br><br>volumes:<br>    db-data:<br><br>services:<br>    mysql:<br>      image: mysql:5.6<br>      container_name: ${PROJECT_NAME}-mysql<br>      working_dir: /application<br>      volumes:<br>        - db-data:/application<br>      environment:<br>        - MYSQL_ROOT_PASSWORD=docker_root<br>        - MYSQL_DATABASE=gedmoapp_db<br>        - MYSQL_USER=gedmoapp_user<br>        - MYSQL_PASSWORD=gedmoapp_pw<br>      ports:<br>        - &quot;8306:3306&quot;<br><br>    webserver:<br>      image: nginx:alpine<br>      container_name: ${PROJECT_NAME}-webserver<br>      working_dir: /application<br>      volumes:<br>        - .:/application<br>        - ./docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf<br>      ports:<br>        - &quot;8000:80&quot;<br><br>    php-fpm:<br>      build: docker/php-fpm<br>      container_name: ${PROJECT_NAME}-php-fpm<br>      working_dir: /application<br>      volumes:<br>        - .:/application<br>        - ./docker/php-fpm/php-ini-overrides.ini:/etc/php/7.2/fpm/conf.d/99-overrides.ini</pre><h4>Installation of Gedmo’s bundle</h4><pre>composer require stof/doctrine-extensions-bundle</pre><h4>Configuration</h4><p>Now we need to update our configuration file, so in the doctrine.yaml, under the doctrine key, we should go from this</p><pre>#doctrine.yaml<br>doctrine:<br>#...<br>    orm:<br>        auto_generate_proxy_classes: &#39;%kernel.debug%&#39;<br>        naming_strategy: doctrine.orm.naming_strategy.underscore<br>        auto_mapping: true<br>        naming_strategy: doctrine.orm.naming_strategy.underscore<br>        auto_mapping: true<br>        mappings:<br>            App:<br>                is_bundle: false<br>                type: annotation<br>                dir: &#39;%kernel.project_dir%/src/Entity&#39;<br>                prefix: &#39;App\Entity&#39;<br>                alias: App</pre><p>To this</p><pre>#doctrine.yaml<br>doctrine:<br>#...<br>	orm:<br>        auto_generate_proxy_classes: &#39;%kernel.debug%&#39;<br>#        naming_strategy: doctrine.orm.naming_strategy.underscore<br>#        auto_mapping: true<br>        entity_managers:<br>            default:<br>#                connection: default<br>                naming_strategy: doctrine.orm.naming_strategy.underscore<br>                auto_mapping: true<br>                mappings:<br>                    App:<br>                        is_bundle: false<br>                        type: annotation<br>                        dir: &#39;%kernel.project_dir%/src/Entity&#39;<br>                        prefix: &#39;App\Entity&#39;<br>                        alias: App<br>                    gedmo_translatable:<br>                        type: annotation<br>                        prefix: Gedmo\Translatable\Entity<br>                        dir: &quot;%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity&quot;<br>                        alias: GedmoTranslatable # (optional) it will default to the name set for the mapping<br>                        is_bundle: false<br>                    gedmo_translator:<br>                        type: annotation<br>                        prefix: Gedmo\Translator\Entity<br>                        dir: &quot;%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translator/Entity&quot;<br>                        alias: GedmoTranslator # (optional) it will default to the name set for the mapping<br>                        is_bundle: false<br>#                    gedmo_loggable:<br>#                        type: annotation<br>#                        prefix: Gedmo\Loggable\Entity<br>#                        dir: &quot;%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity&quot;<br>#                        alias: GedmoLoggable # (optional) it will default to the name set for the mappingmapping<br>#                        is_bundle: false<br>                    gedmo_tree:<br>                        type: annotation<br>                        prefix: Gedmo\Tree\Entity<br>                        dir: &quot;%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity&quot;<br>                        alias: GedmoTree # (optional) it will default to the name set for the mapping<br>                        is_bundle: false</pre><p>Also, in our stof_doctrine_extensions.yaml, let’s add the following configuration for the doctrine extensions.</p><pre>#stof_doctrine_extensions.yaml<br>stof_doctrine_extensions:<br>    default_locale: en_US<br>    orm:<br>        default:<br>            tree: true<br>            translatable: true<br>            sluggable: true</pre><p>Now, if we try to update our schema</p><pre>php bin/console doc:sch:update --dump-sql</pre><pre>The following SQL statements will be executed:<br><br>     CREATE TABLE ext_translations (id INT AUTO_INCREMENT NOT NULL, locale VARCHAR(8) NOT NULL, object_class VARCHAR(255) NOT NULL, field VARCHAR(32) NOT NULL, foreign_key VARCHAR(64) NOT NULL, content LONGTEXT DEFAULT NULL, INDEX translations_lookup_idx (locale, object_class, foreign_key), UNIQUE INDEX lookup_unique_idx (locale, object_class, field, foreign_key), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT = DYNAMIC;</pre><p>Looks about right, so let’s hit it!</p><pre>php bin/console doc:sch:update --force</pre><p>And we get the following error</p><pre>Updating database schema...<br><br><br>In AbstractMySQLDriver.php line 126:<br>                                                                                                                                <br>  An exception occurred while executing &#39;ALTER TABLE ext_translations CHANGE object_class object_class VARCHAR(255) NOT NULL&#39;:  <br>                                                                                                                                <br>  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes               <br>                                                                                                                                <br><br>In PDOConnection.php line 109:<br>                                                                                                                   <br>  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes  <br>                                                                                                                   <br><br>In PDOConnection.php line 107:<br>                                                                                                                   <br>  SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes</pre><p>Now, after looking for this issue with Symfony and Gedmo Translations in the internet, I found <a href="https://github.com/FriendsOfSymfony/FOSUserBundle/issues/1919">this issue</a> about Doctrine and <a href="https://github.com/symfony/symfony-docs/issues/6398">this other one</a>, and the <a href="https://github.com/symfony/symfony-docs/pull/10055">fix here</a>.</p><p>As <a href="https://github.com/davidbehler"><em>davidbehler</em></a> and <a href="https://github.com/javiereguiluz"><em>javiereguiluz</em></a> explain in the posts,</p><blockquote>the cause of this is that Symfony advises you to use utf8mb4_general_ci/utf8mb4 as collation/charset for your database. utf8mb4 takes 4 bytes per char, meaning a 255 char field needs 1020 bytes for an index.</blockquote><p>And so it seems that MySql 5.6 has a max key length of 767 bytes, so that leaves us with three options:</p><ol><li>Decrease the field length to 191. However, we would have to override Gedmo’s translations bundle, as it uses 255 char fields everywhere..</li><li>We could change the charset encoding to ut8 like so (thanks to <a href="https://medium.com/u/375f78d23db9">Kuba Florczuk</a> for the configuration):</li></ol><pre>#doctrine.yaml<br>doctrine:<br>    dbal:<br>        # configure these for your database server<br>        driver: &#39;pdo_mysql&#39;<br>        server_version: &#39;5.6&#39;<br>        charset: utf8<br>        default_table_options:<br>            charset: utf8<br>            collate: utf8_unicode_ci<br><br>        url: &#39;%env(resolve:DATABASE_URL)%&#39;<br>#...</pre><p>3. We could upgrade to mysql 5.7 like so:</p><pre>#docker-compose.yml<br>services:<br>    mysql:<br>      image: mysql:5.7<br>#...</pre><p>And update the doctrine config like so:</p><pre>#doctrine.yaml<br>doctrine:<br>    dbal:<br>        # configure these for your database server<br>        driver: &#39;pdo_mysql&#39;<br>        server_version: &#39;5.7&#39;<br>        charset: utf8mb4<br>        default_table_options:<br>            charset: utf8mb4<br>            collate: utf8mb4_unicode_ci<br><br>        url: &#39;%env(resolve:DATABASE_URL)%&#39;<br>#...</pre><p>All of them solutions work gracefully. Hope this helps, happy coding! :)</p><h4>Gedmo’s Translations Documentation</h4><p><a href="https://symfony.com/doc/master/bundles/StofDoctrineExtensionsBundle/index.html">StofDoctrineExensionBundle in Symfony’s official website.</a><br><a href="https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/symfony2.md">Doctrine’s extensions GitHub doc.</a><br><a href="https://github.com/Atlantic18/DoctrineExtensions/blob/v2.4.x/doc/translatable.md">Translatable’s GitHub doc.</a></p><p><em>Originally published at </em><a href="http://blog.joeymasip.com/gedmo-translations-in-symfony-4/"><em>Joey’s blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5ca1faa15a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a REST API with Django and JWT Auth]]></title>
            <link>https://joeymasip.medium.com/how-to-build-a-rest-api-with-django-and-jwt-auth-9cd2f421f7fb?source=rss-f18b9d52af41------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd2f421f7fb</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Joey Masip Romeu]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 11:02:01 GMT</pubDate>
            <atom:updated>2018-10-05T16:36:17.560Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while since I wrote anything in the blog.</p><p>Today on this short tutorial I’ll explain the steps on how to build an api app with Django, using the JWT (JSON Web Token) as a way to identify users.</p><p>Libraries we’ll use are:</p><p><em>Docker<br> Django 1.11<br> Python 3<br> </em><a href="http://www.django-rest-framework.org/"><em>Django’s REST Framework</em></a><em><br> </em><a href="https://getblimp.github.io/django-rest-framework-jwt/"><em>Django’s JWT</em></a></p><p>So let’s start by creating a Django project with Docker. If you still don’t know how to do that, more info on how to do <a href="https://blog.joeymasip.com/docker-for-django/">create a django project with docker here</a>.</p><p>Our requirements.txt would something like this:</p><pre>django==1.11<br>mysqlclient<br>djangorestframework<br>djangorestframework-jwt<br>requests</pre><p>*Note: The <em>requests</em> library is just to create some requests (GET, POST…) inside our python code. For this example, I’ve named the project ‘apiskeleton’ and the app ‘apiapp’.</p><h4>Step1: Django’s REST Framework</h4><p>Once we have created the project and app, let’s register our app and the rest framework app also in our settings.</p><pre>#settings.py<br><br>INSTALLED_APPS = [<br>	# ...<br>	&#39;apiapp&#39;,<br>    &#39;rest_framework&#39;,<br>	# ...<br>]</pre><p>Great, now we’re ready to create some logic in our app.</p><p>First off, if you haven’t done already, create a separate User model. This is best practices for Django.</p><pre>#models/user.py<br>from django.db import models<br>from django.contrib.auth.models import AbstractUser<br><br><br>class User(AbstractUser):<br>    pass</pre><p>Update the settings.py</p><pre>#settings.py<br><br># Custom User model<br>AUTH_USER_MODEL = &#39;apiapp.User&#39;</pre><p>Now, let’s create a serializer for our User model. The serializer will allow us to convert a model instance or queryset to a JSON content type. More info on serializers <a href="http://www.django-rest-framework.org/api-guide/serializers/">here</a>.</p><p>Our serializers.py would look something like this:</p><pre>#serializers/user.py<br>from rest_framework import serializers<br>from appapi.models import User<br><br>class UserSerializer(serializers.Serializer):<br>    id = serializers.IntegerField(read_only=True)<br>    username = serializers.CharField(required=True, allow_blank=False, max_length=100)<br>    password = serializers.CharField(required=True, write_only=True)<br>    email = serializers.CharField(required=True, allow_blank=True, max_length=100)<br>    is_staff = serializers.BooleanField(required=False, default=False)<br>    is_superuser = serializers.BooleanField(required=False, default=False)<br><br>    def create(self, data):<br>        &quot;&quot;&quot;<br>        Create and return a new `Snippet` instance, given the validated data.<br>        &quot;&quot;&quot;<br>        instance = User.objects.create(<br>            username=data.get(&#39;username&#39;),<br>            email=data.get(&#39;email&#39;),<br>            is_staff=data.get(&#39;is_staff&#39;),<br>            is_superuser=data.get(&#39;is_superuser&#39;),<br>        )<br>        instance.set_password(data.get(&#39;password&#39;))<br>        instance.save()<br>        return instance<br><br>    def update(self, instance, data):<br>        &quot;&quot;&quot;<br>        Update and return an existing `Snippet` instance, given the validated data.<br>        &quot;&quot;&quot;<br>        instance.username = data.get(&#39;username&#39;, instance.username)<br>        instance.email = data.get(&#39;email&#39;, instance.email)<br>        instance.is_staff = data.get(&#39;is_staff&#39;, instance.is_staff)<br>        instance.is_superuser = data.get(&#39;is_superuser&#39;, instance.is_staff)<br>        instance.set_password(data.get(&#39;password&#39;))<br>        instance.save()<br>        return instance</pre><p>It’s very simple, I know, but I like the readability here! There are probably better ways to make your serializers, for instance, by extending serializers.ModelSerializer, more info on this <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer">here</a>, but it’s not the aim of this tutorial right now. Trying to make things as easy and readable as possible.</p><p>Now let’s add a GET API route to list all users, something on the lines of /user/. Since it’s listing all users, it should only be allowed for an admin user to use it right? For now, I’ll just call it api_admin_user_index, so I know this is for admins only. Later on we’ll secure these.</p><pre>#urls.py<br>urlpatterns = [<br>    url(https://medium.com/r&#39;^user/r&#39;^user/$&#39;, user.api_admin_user_index, name=&#39;api_admin_user_index&#39;#39;,%20user.api_admin_user_index,%20name=&#39;api_admin_user_index&#39;),<br>]</pre><p>Now, let’s create the view for this url:</p><pre>#views/user.py<br>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br>from apiapp.models import User<br>from apiapp.serializers.user import UserSerializer<br><br>@api_view([&#39;GET&#39;])<br>def api_admin_user_index(request):<br>    &quot;&quot;&quot;<br>    get:<br>    List all users.<br>    &quot;&quot;&quot;<br>    serializer = UserSerializer(User.objects.all(), many=True)<br>    return Response(serializer.data)</pre><p>This first parameter in the serializer is the queryset, and the second parameter is to let the serializer know this is a list. <a href="https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py">More info on this on the BaseSerializer class from Django’s Rest Framework</a>.</p><p>Now, if we open a browser and type this route, we should see a list of 0 users, but the route works right? Success!</p><p>Now let’s create some users. We should add the POST verb in our view to do that, so it would look something like this:</p><pre>#views/user.py<br>from rest_framework import status<br>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br>from apiapp.models import User<br>from apiapp.serializers.user import UserSerializer<br>from apiapp.utils.jsonreader import JsonReader<br><br><br>@api_view([&#39;GET&#39;, &#39;POST&#39;])<br>def api_admin_user_index(request):<br>    &quot;&quot;&quot;<br>    get:<br>    List all users.<br>    post:<br>    Create new user.<br>    &quot;&quot;&quot;<br>    if request.method == &#39;GET&#39;:<br>        serializer = UserSerializer(User.objects.all(), many=True)<br>        return Response(serializer.data)<br><br>    elif request.method == &#39;POST&#39;:<br>        data = JsonReader.read_body(request)<br>        serializer = UserSerializer(data=data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p>The POST will create a user through the serializer.</p><p>In the code, you can see that I added a JsonReader class. This is a util class I use in most of my projects, it just makes reading the body easier, here’s the code:</p><pre>#utils/jsonreader.py<br>import json<br><br><br>class JsonReader:<br><br>    @staticmethod<br>    def read_body(request):<br>        &#39;&#39;&#39;returns a dict from the body of request&#39;&#39;&#39;<br><br>        data = dict()<br><br>        try:<br>            body = request.body<br>            data = JsonReader.bytes_to_dict(body)<br>        except Exception as exc:<br>            if isinstance(request.data, dict):<br>                data = request.data<br>            elif isinstance(request.data, str):<br>                data = JsonReader.str_to_dict(request.data)<br><br>        return data<br><br>    @staticmethod<br>    def str_to_dict(s: str):<br>        dict = json.loads(s)<br>        return dict<br><br>    @staticmethod<br>    def dict_to_str(d: dict):<br>        str = json.dumps(d)<br>        return str<br><br>    @staticmethod<br>    def bytes_to_dict(b: bytes):<br>        str = b.decode(&quot;utf-8&quot;)<br>        dict = JsonReader.str_to_dict(str)<br>        return dict</pre><p>Now we can create some users through our POST method, just sending some JSON with the keys username, password and email, which are the required ones in our serializer. Simple right?</p><p>Now it’s time for the rest of the usual verbs, PUT and DELETE. Also, we need a GET for a single user.</p><p>The routes would look something like this:</p><pre>#urls.py<br>urlpatterns = [<br>    url(https://medium.com/r&#39;^user/r&#39;^user/$&#39;, user.api_admin_user_index, name=&#39;api_admin_user_index&#39;#39;,%20user.api_admin_user_index,%20name=&#39;api_admin_user_index&#39;),<br>    url(https://medium.com/r&#39;^user/(?P[0-9]+)/$&#39;, user.api_admin_user_detail, name=&#39;api_admin_user_detail&#39;),<br>]</pre><p>And now let’s update the view</p><pre>#views/user.py<br>@api_view([&#39;GET&#39;, &#39;PUT&#39;, &#39;DELETE&#39;])<br>def api_admin_user_detail(request, pk):<br>    &quot;&quot;&quot;<br>    get:<br>    Detail one user.<br>    put:<br>    Update one user.<br>    delete:<br>    Delete one user.<br>    &quot;&quot;&quot;<br><br>    try:<br>        user = User.objects.get(pk=pk)<br>    except User.DoesNotExist:<br>        return Response({&#39;error&#39;: &quot;User &quot; + pk + &quot; does not exist&quot;}, status=status.HTTP_404_NOT_FOUND)<br><br>    if request.method == &#39;GET&#39;:<br>        serializer = UserSerializer(user)<br>        return Response(serializer.data)<br><br>    elif request.method == &#39;PUT&#39;:<br>        data = JsonReader.read_body(request)<br>        serializer = UserSerializer(user, data=data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br>    elif request.method == &#39;DELETE&#39;:<br>        user.delete()<br>        return Response(status=status.HTTP_204_NO_CONTENT)</pre><p>All of this is great, but now let’s secure these admin calls right? Here’s where JWT comes into play.</p><h4>Step2: Django’s JWT</h4><p>JWT is a stateless authentication mechanism as the user state is never saved in the server memory. Django will check for a valid JWT in the Authorization header, and if it is there, the user will be allowed. As JWTs are self-contained, all the necessary information is there, reducing the need to go back and forth to the database.</p><p>This allows the user to fully rely on data APIs that are stateless. It doesn’t matter which domains are serving your APIs, as Cross-Origin Resource Sharing (CORS) won’t be an issue since it doesn’t use cookies.</p><p>With that being said, let’s start by updating our settings.py with the JWT configuration</p><pre>#settings.py<br><br># Configure the authentication in Django Rest Framework to be JWT<br># http://www.django-rest-framework.org/<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework_jwt.authentication.JSONWebTokenAuthentication&#39;,<br>    ),<br>}<br><br># Configure the JWTs to expire after 1 hour, and allow users to refresh near-expiration tokens<br># https://getblimp.github.io/django-rest-framework-jwt/<br>JWT_AUTH = {<br>    # If the secret is wrong, it will raise a jwt.DecodeError telling you as such. You can still get at the payload by setting the JWT_VERIFY to False.<br>    &#39;JWT_VERIFY&#39;: True,<br><br>    # You can turn off expiration time verification by setting JWT_VERIFY_EXPIRATION to False.<br>    # If set to False, JWTs will last forever meaning a leaked token could be used by an attacker indefinitely.<br>    &#39;JWT_VERIFY_EXPIRATION&#39;: True,<br><br>    # This is an instance of Python&#39;s datetime.timedelta. This will be added to datetime.utcnow() to set the expiration time.<br>    # Default is datetime.timedelta(seconds=300)(5 minutes).<br>    &#39;JWT_EXPIRATION_DELTA&#39;: datetime.timedelta(hours=1),<br><br>    &#39;JWT_ALLOW_REFRESH&#39;: True,<br>    &#39;JWT_AUTH_HEADER_PREFIX&#39;: &#39;JWT&#39;,<br>}</pre><p>The config is pretty self-explanatory, but there’s more documentation on <a href="https://getblimp.github.io/django-rest-framework-jwt/#additional-settings">JWT settings here</a>.</p><p>Once this is out of the way, let’s add some JWT route patterns so we can get that JWT token.</p><pre>#urls.py<br>urlpatterns = [<br>    # ...<br>    url(https://medium.com/r&#39;^jwt/refresh-token/&#39;,%20refresh_jwt_token,%20name=&#39;refresh_jwt_token&#39;),<br>    url(https://medium.com/r&#39;^jwt/api-token-verify/&#39;,%20verify_jwt_token,%20name=&#39;verify_jwt_token&#39;),<br>    url(https://medium.com/r&#39;^jwt/api-token-auth/&#39;,%20obtain_jwt_token,%20name=&#39;obtain_jwt_token&#39;),<br>]</pre><p>Also, this is not necessary, but instead of exposing the JWT routes, let’s add a login API route that will wrap the obtaining of the JWT token.</p><pre>#urls.py<br>urlpatterns = [<br>    # ...<br>    url(https://medium.com/r&#39;^login/&#39;,%20registration.api_login,%20name=&#39;api_login&#39;),<br>]</pre><p>And in our registration view</p><pre>#views/registration.py<br>@api_view([&#39;POST&#39;])<br>def api_login(request):<br>    &quot;&quot;&quot;<br>    post:<br>    This view is called through API POST with a json body like so:<br><br>    {<br>        &quot;username&quot;: &quot;admin&quot;,<br>        &quot;password&quot;: &quot;admin&quot;<br>    }<br><br>    :param request:<br>    :return:<br>    &quot;&quot;&quot;<br>    data = JsonReader.read_body(request)<br><br>    response_login = requests.post(<br>        request.build_absolute_uri(reverse(&#39;obtain_jwt_token&#39;)),<br>        data=data<br>    )<br>    response_login_dict = json.loads(response_login.content)<br>    return Response(response_login_dict, response_login.status_code)</pre><p>Notice that this time I didn’t use the prefix ‘admin’. This is because this will be authorized to anonymous users, unlike the ones we created previously.</p><p>So as you can see, it’s pretty straightforward. This view is a wrapper of the JWT route. This way, we can add information to the response if we need to, for instance, the user id, user profile, etc. For now, let’s leave it this way.</p><p>If we now test it with a username and password, we should get the token. If you haven’t created any users yet, you could use the POST call we created previously. Otherwise, just add some superusers in the python console or create some fixtures, up to you.</p><p>If you’re lazy, here are my fixtures, and the location is <em>apiapp/fixtures/users.json</em></p><pre>[<br>{<br>    &quot;model&quot;: &quot;apiapp.user&quot;,<br>    &quot;pk&quot;: 1,<br>    &quot;fields&quot;: {<br>        &quot;password&quot;: &quot;pbkdf2_sha256$36000$SoF7ueJzOE1I$244qaRI1dReT4DxZKXJi2sRmuKdqPcjeOiUaPdH2UV0=&quot;,<br>        &quot;last_login&quot;: null,<br>        &quot;is_superuser&quot;: true,<br>        &quot;username&quot;: &quot;admin&quot;,<br>        &quot;first_name&quot;: &quot;&quot;,<br>        &quot;last_name&quot;: &quot;&quot;,<br>        &quot;email&quot;: &quot;admin@slowcode.io&quot;,<br>        &quot;is_staff&quot;: true,<br>        &quot;is_active&quot;: true,<br>        &quot;date_joined&quot;: &quot;2018-08-29T10:09:27.191Z&quot;,<br>        &quot;groups&quot;: [],<br>        &quot;user_permissions&quot;: []<br>    }<br>},<br>{<br>    &quot;model&quot;: &quot;apiapp.user&quot;,<br>    &quot;pk&quot;: 2,<br>    &quot;fields&quot;: {<br>        &quot;password&quot;: &quot;pbkdf2_sha256$36000$bkA3NXYqXZ4S$zuH97poSj3trZoNRFeROw3PgutbGOHlZunliI8/1jbg=&quot;,<br>        &quot;last_login&quot;: null,<br>        &quot;is_superuser&quot;: false,<br>        &quot;username&quot;: &quot;user1&quot;,<br>        &quot;first_name&quot;: &quot;&quot;,<br>        &quot;last_name&quot;: &quot;&quot;,<br>        &quot;email&quot;: &quot;user1@slowcode.io&quot;,<br>        &quot;is_staff&quot;: true,<br>        &quot;is_active&quot;: true,<br>        &quot;date_joined&quot;: &quot;2018-08-29T10:10:56.873Z&quot;,<br>        &quot;groups&quot;: [],<br>        &quot;user_permissions&quot;: []<br>    }<br>},<br>{<br>    &quot;model&quot;: &quot;apiapp.user&quot;,<br>    &quot;pk&quot;: 3,<br>    &quot;fields&quot;: {<br>        &quot;password&quot;: &quot;pbkdf2_sha256$36000$KKujn28LvdGX$OxtfRmIUWNPwbBPsz2iwKwff8klJ5PiPXj3P9N70Hto=&quot;,<br>        &quot;last_login&quot;: null,<br>        &quot;is_superuser&quot;: false,<br>        &quot;username&quot;: &quot;user2&quot;,<br>        &quot;first_name&quot;: &quot;&quot;,<br>        &quot;last_name&quot;: &quot;&quot;,<br>        &quot;email&quot;: &quot;user2@slowcode.io&quot;,<br>        &quot;is_staff&quot;: false,<br>        &quot;is_active&quot;: true,<br>        &quot;date_joined&quot;: &quot;2018-08-29T10:11:19.576Z&quot;,<br>        &quot;groups&quot;: [],<br>        &quot;user_permissions&quot;: []<br>    }<br>}<br>]</pre><p>To import them, use the command</p><pre>python manage.py loaddata users</pre><p>Great, by now you should have some users in your database and you should be able to use our login API we just created. But what do we do with the token we get back?</p><p>Well, as mentioned before, this token should be added as a Authorization header in our calls to identify such user.</p><p>With JWT we will be able to authorize or prohibit certain calls for certain users, and or we will send different type of info, depending on what user is sending the call.</p><p>All of this decision making will be done by a different layer, which I call ‘security voters’ (hereditary from Symfony)</p><p>Here’s an example of what a voter would look like:</p><pre>#security/voters.py<br>from apiapp.models import User<br><br><br>class AbstractVoter:<br><br>    request = None<br><br>    def __init__(self, request):<br>        self.request = request<br><br>    def is_logged_in(self):<br>        if isinstance(self.request.user, User):<br>            return True<br><br>        return False<br><br>    def is_superuser(self):<br>        if self.is_logged_in():<br>            return self.request.user.is_superuser<br><br>        return False<br><br><br>class UserVoter(AbstractVoter):<br><br>    def user_can_manage_me(self, user_inst: User):<br>        if self.is_logged_in():<br>            if self.is_superuser():<br>                return True<br>            if self.request.user == user_inst:<br>                return True<br><br>        return False</pre><p>Now we can call this voter in our APIs.</p><pre>#views/user.py<br>@api_view([&#39;GET&#39;, &#39;POST&#39;])<br>def api_admin_user_index(request):<br>    &quot;&quot;&quot;<br>    get:<br>    List all users.<br>    post:<br>    Create new user.<br>    &quot;&quot;&quot;<br>    voter = UserVoter(request)<br>    if not voter.is_superuser():<br>        return Response({&#39;error&#39;: &quot;User API is not allowed by non admin user&quot;}, status=status.HTTP_403_FORBIDDEN)<br><br>    #...<br><br><br>@api_view([&#39;GET&#39;, &#39;PUT&#39;, &#39;DELETE&#39;])<br>def api_admin_user_detail(request, pk):<br>    &quot;&quot;&quot;<br>    get:<br>    Detail one user.<br>    put:<br>    Update one user.<br>    delete:<br>    Delete one user.<br>    &quot;&quot;&quot;<br>    voter = UserVoter(request)<br>    if not voter.is_superuser():<br>        return Response({&#39;error&#39;: &quot;User API is not allowed by non admin user&quot;}, status=status.HTTP_403_FORBIDDEN)<br><br>    #...</pre><p>It can also be useful for API calls that are not for superusers. Let’s create the route for a user detail.</p><pre>#urls.py<br>urlpatterns = [<br>	#...<br>    url(https://medium.com/r&#39;^(?P[0-9]+)/$&#39;, user.api_user_detail, name=&#39;api_user_detail&#39;),<br>]</pre><p>And now in the view.<br> In the GET verb, Unless the user wants to see himself, it should be denied.</p><pre>#views/user.py<br>@api_view([&#39;GET&#39;, &#39;PUT&#39;])<br>def api_user_detail(request, pk):<br>    &quot;&quot;&quot;<br>    get:<br>    Detail one user.<br>    put:<br>    Update one user.<br>    &quot;&quot;&quot;<br>    try:<br>        user_inst = User.objects.get(pk=pk)<br>    except User.DoesNotExist:<br>        return Response(status=status.HTTP_404_NOT_FOUND)<br><br>    voter = UserVoter(request)<br>    if not voter.user_can_manage_me(user_inst):<br>        return Response({&#39;error&#39;: &quot;User API is not allowed&quot;}, status=status.HTTP_403_FORBIDDEN)<br><br>    if request.method == &#39;GET&#39;:<br>        serializer = UserSerializer(user_inst)<br>        return Response(serializer.data)<br><br>    elif request.method == &#39;PUT&#39;:<br>        data = JsonReader.read_body(request)<br>        if &#39;is_staff&#39; in data:<br>            if not voter.is_superuser():<br>                return Response({&#39;error&#39;: &quot;Non admin cannot update admin attributes&quot;}, status=status.HTTP_403_FORBIDDEN)<br>        serializer = UserSerializer(user_inst, data=data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><h4>Conclusion</h4><p>On this post we’ve seen how to implement the Django’s REST Framework together with Django’s JWT library.</p><p>We’ve seen that JWT is a powerful and easy way to identify users that use our API.</p><p>If you have any questions or something is confusing, let me know and I’ll do my best to clarify.</p><p>I’ve also <a href="https://github.com/joeymasip/django-apiskeleton">uploaded the code on github</a> so you can clone the project and try it out for yourself.</p><pre>git clone <a href="https://github.com/joeymasip/django-apiskeleton.git">https://github.com/joeymasip/django-apiskeleton.git</a></pre><p>I use it as a base for API projects, as I usually always need some User API to start with.</p><p>Happy coding :)</p><p><em>Originally published at </em><a href="http://blog.joeymasip.com/how-to-build-a-rest-api-with-django-and-jwt-auth/"><em>Joey’s blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd2f421f7fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>