<?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 Florian Abel on Medium]]></title>
        <description><![CDATA[Stories by Florian Abel on Medium]]></description>
        <link>https://medium.com/@florian_abel?source=rss-4027b693372a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IkT3gOSKv93kayKXFpwQHg.jpeg</url>
            <title>Stories by Florian Abel on Medium</title>
            <link>https://medium.com/@florian_abel?source=rss-4027b693372a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:11:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@florian_abel/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[A Quick Intro To Convolutions in CNNs]]></title>
            <link>https://medium.com/codex/a-quick-intro-to-convolutions-in-cnns-8b747504c281?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b747504c281</guid>
            <category><![CDATA[convolution]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 12:02:58 GMT</pubDate>
            <atom:updated>2023-03-18T12:02:58.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Quick Intro To Convolutions In CNNs</h3><p><em>Disclaimer: This article requires a basic understanding of neural networks and how fully connected layers function.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3jn9jtULXRgDVj0w" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Convolutional neural networks (CNNs) are a type of network architecture that is commonly used in computer vision tasks. The convolutional layers provide several advantages over fully connected layers, which are commonly used in classical neural network architectures. The main functionality of the convolutional layers is to detect features inside the images while reducing the required computational power in comparison to fully connected layers. <a href="https://www.baeldung.com/cs/neural-networks-conv-fc-layers#:~:text=Differences,-The%20basic%20difference&amp;text=The%20FC%20layers%20are%20densely,width%20of%20the%20convolutional%20kernel.">In fact, convolutional layers are fully connected layers, in which some of the weights are set to zero and some weights are shared between neurons.</a></p><h3>Why do we need convolutions?</h3><p><strong>Computationally expensive<br></strong>Image analysis problems often depend on comparably large inputs. With an image of size 1.000x1.000 pixels and three color channels (RGB) the input layer already consists of 1.000x1.000x3 = 3.000.000 input features. If a fully connected layer with only 1000 neurons is used, the weight matrix for the first layer alone has already 3 billion values that need to be computed. A network architecture with fully connected layers would therefore be computationally very expensive.</p><p><strong>Overfitting<br></strong>As outlined above, a network with fully connected layers would have a very large number of variables to learn. In order for the network to generalize well and prevent overfitting, a large amount of training data is needed. Next to the computational expenses it would, therefore, be very time-consuming and expensive to collect the required amount of training data.</p><p><strong>Feature detection<br></strong>Fully connected layers will also learn the features the input images are providing, however, they will learn these features not solely based on their existence but also based on their location in the image. If a network of this type learns to detect a feature, it might not detect the same feature in another part of the frame. CNNs on the other hand can learn and detect features independently of their position in the frame.</p><p><strong>Overall<br></strong>Convolutional layers help to substantially reduce the required computational power and required training data in comparison to networks using fully connected layers. Furthermore, they help the network to learn about features independently of their position.</p><h3>How do convolutions work?</h3><p>In a convolution, a filter (or kernel) is placed and shifted over an image in order to detect certain features. Depending on the filter and its position in the network it will detect more simple or more complex features within the image.</p><p><strong>What is a filter (or kernel)<br></strong>A filter (or kernel) is a matrix of typically 3x3, 5x5, or 7x7 pixels with a specific set of values. Depending on the values of the filter and the layer of the network it will help detect different features. The values of the filters in neural networks are variables that are learned by the network in the training process. In earlier applications in other fields, filters were often still chosen manually. In machine learning, however, it proved useful to let the network learn the best values instead of trying to manually design the filters.</p><p><strong>The convolution operation<br></strong>When placing the filter on an image, its values are multiplied and added element-wise. The result indicates the presence (or absence) of a feature (that is represented by this filter) in this particular position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K15cyix0s86AcnDNJ6xBEg.png" /><figcaption>Convolution for one position in the image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGxBfkK7UcB4gH0wC1ZANg.png" /></figure><p>Shifting the filter along the image and calculating the convolution in each position essentially generates a feature map, indicating the presence of this feature in different positions of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LU5iN-AIhYg83LElDpZBdQ.png" /><figcaption>Convolutions in different positions of the image by shifting the filter</figcaption></figure><blockquote>It is important to note, that the result of the convolutions are no pixel/color values, but a map of the existence of a feature (the feature that is represented by the filter) in a specific position.</blockquote><p><strong>Edge detection example for convolutions</strong></p><p>Edges are one of the most simple features and will be detected in the early layers of the network. A filter for vertical edge detection might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*zRkRStk4cwX9NSy4DZfX_w.png" /><figcaption>Filter for vertical edge detection</figcaption></figure><p>Let’s assume we have an image with only black and white (represented by 0 and 1), forming a vertical edge. In order to detect that edge, we are using the above filter to calculate the convolutions. As a result our feature map clearly shows the position of the edge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHRC5MWY5T3hiZu1rNQvYA.png" /><figcaption>Vertical edge detection</figcaption></figure><h3>Padding</h3><p>As you might have noticed, the resulting matrix of the feature map in the above example is a 4x4 matrix, whereas our input has been a 6x6 matrix. Due to the filter size of 3x3, it can occupy 4 positions horizontally and vertically, each, resulting in 16 unique positions and a 4x4 output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKbgbUq0PDwOZ4kqcLHnSw.png" /><figcaption>Unique filter positions</figcaption></figure><p><strong>Valid convolutions<br></strong>A convolution, in which the output is smaller than the input, is called a <strong>“valid convolution”</strong>.</p><p><strong>Same convolutions<br></strong>In some applications, it is important though to maintain the dimensions in the convolution process. This type of convolution is called <strong>“same convolution”</strong> and effectively signifies that the output has the same size as the input.</p><p><strong>How to obtain “same convolutions”<br></strong>In order to maintain the same size in the output as in the input it is important to have as many unique positions for the filter to be placed on as the original input has values. E.g. in a 6x6 input matrix, we need 6x6=36 unique positions for the filter to be placed.</p><p>In order to create the extra positions, the input matrix can be padded with extra values (in this case zeros):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Xt236vPLebaEPxTT8sxeA.png" /><figcaption>Same convolution with zero padding of the original input</figcaption></figure><h3>Summary</h3><p>This should have given you a good overview of how convolutions, the determining operation in convolutional neural networks, work. As this article is supposed to serve only as a quick introduction, there is still a lot more to learn in order to fully understand the process and how CNNs work exactly. However, this should give you a good starting point to read more detailed information about the topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b747504c281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/a-quick-intro-to-convolutions-in-cnns-8b747504c281">A Quick Intro To Convolutions in CNNs</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Google sign-in in Flutter without Firebase]]></title>
            <link>https://medium.com/codex/how-to-build-a-google-sign-in-in-flutter-without-firebase-5d0d379b2f64?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d0d379b2f64</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 14:54:21 GMT</pubDate>
            <atom:updated>2022-07-25T14:54:21.599Z</atom:updated>
            <content:encoded><![CDATA[<p>Let your Flutter App users authenticate with GoogleOAuth2, using <a href="https://pub.dev/packages/flutter_appauth">Flutter AppAuth</a>, and connect with your backend. Not limited to Firebase.</p><p><strong><em>TL;DR: The GitHub repo for this project can be found </em></strong><a href="https://github.com/florianabel/social-auth-example-flutter"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9B0-abqgTRhdCFi_" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=medium&amp;utm_medium=referral">freestocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>This article is a step-by-step guide to implementing social authentication with GoogleOAuth2 in your Flutter Application, using <a href="https://pub.dev/packages/flutter_appauth">Flutter AppAuth</a>. After successful authentication, you will receive an access token to gain access to your backend. I have written <a href="https://medium.com/codex/google-sign-in-rest-api-with-python-social-auth-and-django-rest-framework-4d087cd6d47f">another article</a> explaining how to handle the backend side with a Django Application. However, you are free to use every backend you feel most comfortable with.</p><h3>Authentication with OAuth2</h3><p>Authentication with OAuth2 is based on different flows, depending on the specific setup you are using for your application. The basics and which flow to choose for your project are covered well in these two articles from <a href="https://aaronparecki.com/oauth-2-simplified/#mobile-apps">Aaron Parecki</a> and <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use">Auth0</a>.</p><h4>Authorization Code Flow with Proof Key (PKCE)</h4><p>In this example, we are using the <a href="https://oauth.net/2/pkce/">Authorization Code Flow with Proof Key for Code Exchange (PKCE)</a>, which is the recommended way when public clients, like Single-Page and Mobile Applications, request an access token from an OAuth2 provider. The authentication process with the provider happens on the client. After successful authentication, the client exchanges the received access token for an authentication token from the backend. With this token, the client can then use restricted endpoints provided by the backend.</p><p>Further details about this flow are well explained in this <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-proof-key-for-code-exchange-pkce">Auth0 article</a>. The exception in our case is, that we are connecting directly to GoogleOAuth2, instead of Auth0.</p><h3>Registering your Application with GoogleOAuth2</h3><p>In order to let use Google’s social login functionality, your application needs to be registered at the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><ol><li>Create a new project</li><li>Define your <a href="https://console.cloud.google.com/apis/credentials/consent">OAuth Consent Screen</a></li><li>Create <a href="https://console.cloud.google.com/apis/credentials">credentials</a></li></ol><h4>Creating the credentials</h4><p><em>Note: We need to create two sets of credentials, one for iOS and one for Android.</em></p><p>We are starting at the <a href="https://console.cloud.google.com/apis/credentials">Credentials-Page</a>:</p><ol><li>Select + Create Credentials at the top of the Page</li><li>Choose OAuth client ID</li><li>iOS or Android as Application type</li><li>Name it as you wish</li><li>Fill in the Bundle ID (iOS) or Package Name (Android)</li><li>Create and fill in the SHA-1 certificate fingerprint (Only for Android)</li><li>Copy and save the Client ID</li></ol><p><strong>Bundle ID and Package Name<br></strong>The <a href="https://developer.apple.com/documentation/appstoreconnectapi/bundle_ids">Bundle ID</a> and <a href="https://support.google.com/admob/answer/9972781?hl=en">Package Name</a> are unique identifiers, chosen by you. They can never be the same for two applications inside the Apple App Store or Google Play Store, respectively. A common format is com.company.appname , e.g. com.socialauthexample.mobile_app .</p><p><em>Note: Do not use hyphens (-) or underscores (_), or you might run into errors.</em></p><p><strong>SHA-1 certificate fingerprint<br></strong>The SHA-1 certificate fingerprint is a unique signing key, that differs in development and production. <br>To obtain it for your development environment you can follow these steps. Check <a href="https://www.kindacode.com/article/android-how-to-get-sha-certificate-fingerprints/">this article</a> for more information and instructions on getting the fingerprint for production.</p><p><strong>For Mac:</strong></p><pre>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android</pre><p><strong>For Windows:</strong></p><pre>keytool -list -v -keystore C:\Users\&lt;Your User Name&gt;\.android\debug.keystore -alias androiddebugkey</pre><p><em>Note: Make sure to run Android Studio at least once before, otherwise you might receive an error.</em></p><h3>Set up your Application</h3><h4>Create base application</h4><pre>flutter create --org com.socialauthexample mobile_app</pre><h4>Install required dependencies</h4><p>Three packages are required for our social authentication solution and secure storage of tokens.</p><p><a href="https://pub.dev/packages/flutter_appauth"><strong>flutter_appauth</strong></a><strong><br></strong>Well-maintained Flutter package, wrapping around <a href="https://appauth.io/">AppAuth</a>, providing authentication and authorization for users.</p><p><a href="https://pub.dev/packages/http"><strong>http</strong></a><strong><br></strong>Future-based library to perform HTTP requests, developed by the Dart team.</p><p><a href="https://pub.dev/packages/flutter_secure_storage"><strong>flutter_secure_storage</strong></a><strong><br></strong>A Flutter plugin to store data in secure storage.</p><pre>flutter pub add flutter_appauth &amp;&amp; flutter pub add http &amp;&amp; flutter pub add flutter_secure_storage</pre><h3>Providing credentials to our application</h3><p>In order to successfully authenticate our users, we need to provide client ids (previously obtained) and redirect URLs to our application.</p><h4>Redirect URL Format</h4><p>The redirect or callback URL is the address where the OAuth2 server will send the user after successful authentication. Google has <a href="https://developers.google.com/identity/protocols/oauth2/native-app#request-parameter-redirect_uri">specific requirements</a> on the format. The format we are using in this example is based on your client ids: com.googleusercontent.apps.&lt;CLIENT-ID&gt;:redirect_uri_path</p><p><strong>iOS</strong></p><pre>com.googleusercontent.apps.&lt;IOS-CLIENT-ID&gt;:/oauthredirect</pre><p><strong>Android</strong></p><pre>com.googleusercontent.apps.&lt;ANDROID-CLIENT-ID&gt;:/oauthredirect</pre><p><strong>Using variables in your codebase<br></strong>We are using a helper file lib/helper/constants.dart to store all constants for our application and to pass on the correct credentials, depending on the platform the application is running on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b55fc97cb99a2ae8e99631b190277a6/href">https://medium.com/media/5b55fc97cb99a2ae8e99631b190277a6/href</a></iframe><blockquote>Note: For security reasons, credentials should never be part of your source code. The most secure way to provide them is to use environment variables, with e.g. <a href="https://pub.dev/packages/flutter_config">flutter_config</a>, but this goes beyond the scope of this article.</blockquote><h4>Setting up URL Schemes</h4><p>Besides providing the redirect URLs for Flutter AppAuth, we need to let our Applications know about the required URL schemes.</p><p><strong>CFBundleURLSchemes (iOS)<br></strong>To configure the URL scheme for iOS, we are adding a new dict tag CFBundleURLTypes to the /ios/Runner/Info.plist file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4dbc35ce2d960d6db26133294f4bbae/href">https://medium.com/media/f4dbc35ce2d960d6db26133294f4bbae/href</a></iframe><p><strong>appAuthRedirectScheme (Android)<br></strong>For Android, we need to adjust the following entries in the /android/app/build.gradle file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a4f06045866fd2c3421f3c236602602/href">https://medium.com/media/3a4f06045866fd2c3421f3c236602602/href</a></iframe><p><em>Note: Make sure that the URL schemes and redirect URLs match, otherwise you might not get redirected after authentication.</em></p><h3>Building the Application</h3><p>Our application will show a login screen for unauthenticated users that gets replaced with our main screen after successful authentication. Furthermore, previously logged-in users stay logged in after restarting the Application.</p><p>We are creating a user interface with some basic logic in our lib/main.dart file, three additional screens, and a service to handle authentication, lib/services/authentication_service.dart.</p><h4>Application Interface</h4><p><strong>main.dart<br></strong>Our main.dart holds the base structure for our Application. Two flags, isLoading and isLoggedIn , represent the current authentication status and if some action is currently loading. Their state is handled by three methods (setLoadingState , setAuthenticatedState and setUnauthenticatedState ) and the builder provides the correct screen, LoadingScreen MainScreen, AuthenticationScreen, accordingly.</p><p>On Application initialization, our app checks if a user is currently authenticated and sets the state accordingly (Details on how that happens will be discussed further below). If a user is already authenticated, the MainScreen is provided, otherwise, our user gets to see the AuthenticationScreen . Furthermore, we are passing the appropriate functions as callbacks to change the state later on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffde7159eda109aae77d487b4cd554b6/href">https://medium.com/media/ffde7159eda109aae77d487b4cd554b6/href</a></iframe><p><strong>loading_screen.dart<br></strong>Our LoadingScreen contains a CircularProgressIndicator , which continues spinning while our app waits for any actions to finish.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e550aa58de98bdd7c4951367d06155e0/href">https://medium.com/media/e550aa58de98bdd7c4951367d06155e0/href</a></iframe><p><strong>authentication_screen.dart<br></strong>Inside our AuthenticationScreen we provide a Button to initiate the authentication process, which sets the app in a loading state and calls our authentication service&#39;s login method. On success our app switches to the authenticated state, presenting the MainScreen , otherwise, it goes back into the unauthenticated state, showing the AuthenticationScreen , again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389666c7e1efc56c880dbd0dbc326961/href">https://medium.com/media/389666c7e1efc56c880dbd0dbc326961/href</a></iframe><p><strong>main_screen.dart<br></strong>Our main screen currently only has one function, logging the user out again. When clicking the Button our logout method is called, which in turn calls the authentication service and on success, changes the state of the Application to unauthenticated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed33a20627c37e5430c17e2b71cb4113/href">https://medium.com/media/ed33a20627c37e5430c17e2b71cb4113/href</a></iframe><h4>Authentication Service</h4><p>The true magic is within our authentication service. It checks for an already existing refresh token in our secure storage, performs the authentication and refresh processes, and saves and deletes our obtained tokens.</p><p><strong>The basics<br></strong>The authentication service is built as a Singleton, meaning that only one instance of it can exist at all times. The constructor is private and can only be called from within the class. In order to access the service, we always have to call the instance AuthService.instance.someMethod() . The service provides three public methods and one private for internal use.</p><p><strong>Initialization<br></strong>The first method, called by the Application in main.dart is initAuth() . It checks for an existing refresh token and tries to obtain a fresh access token with it. If that works, we have a logged-in user and our Application goes into the authenticated state. If not, either no user has logged in yet, or the token expired. In both cases, our App goes into an unauthenticated state.</p><p><strong>Login<br></strong>Once a user clicks the login button, our login() method is called and starts the authentication process. A window for a Google sign-in is presented and the user can authenticate. If everything goes smoothly, a result with an access and a refresh token is returned.</p><p><strong>Logout<br></strong>Upon logout, the saved refresh token is deleted and our Application switches back to an unauthenticated state.</p><p><strong>Handling authentication results<br></strong>_handleAuthResult is the only private method in our service. It is responsible to take care of the responses we are getting from Google upon authentication or when trying to obtain a fresh access token with the help of an existing refresh token.<br>If the result is valid we update the refresh token. Afterward, we are exchanging the obtained access token for an authentication token from our own backend and save it for further use.</p><blockquote>Note: Since this goes way beyond the scope of this article I laid out a quick example for you in the uncommented section of the method. You can implement it with your own backend as you need. For this scenario, we are just assuming that the backend returned a valid token that we can use.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/075b732b30e1dfd42a9eb43382eed963/href">https://medium.com/media/075b732b30e1dfd42a9eb43382eed963/href</a></iframe><h3>Summary</h3><p>Now you have a basic social authentication schema to use Google sign-in. It can easily be changed to different providers like Facebook or Twitter, by using different credentials. Afterward, your backend will handle the obtained access tokens and provide you with a fresh authentication token. For a Django backend example, check <a href="https://medium.com/codex/google-sign-in-rest-api-with-python-social-auth-and-django-rest-framework-4d087cd6d47f">my other article</a>.</p><p><strong>Feel free to reach out in the comments or follow me on </strong><a href="https://twitter.com/florian_abel_"><strong>Twitter</strong></a><strong> (</strong><a href="https://twitter.com/florian_abel_"><strong>@florian_abel_</strong></a><strong>). I’d be happy to hear your thoughts, questions, and experiences.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d0d379b2f64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-to-build-a-google-sign-in-in-flutter-without-firebase-5d0d379b2f64">How to build a Google sign-in in Flutter without Firebase</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google sign-in REST API with python-social-auth and Django REST Framework]]></title>
            <link>https://medium.com/codex/google-sign-in-rest-api-with-python-social-auth-and-django-rest-framework-4d087cd6d47f?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d087cd6d47f</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 09:48:21 GMT</pubDate>
            <atom:updated>2022-07-19T09:48:21.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Authenticate your Django backend for users that sign up with Google, Facebook, or other third-party OAuth providers in your frontend or mobile application.</p><p><strong><em>TL;DR: The GitHub repo for this project can be found </em></strong><a href="https://github.com/florianabel/social-auth-example-django"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PWpVGpK2GzmMJwLd" /><figcaption>Photo by <a href="https://unsplash.com/@impelling?utm_source=medium&amp;utm_medium=referral">Ed Hardie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In this article, you are building REST API endpoints for social authentication. They can be used with a separate frontend like a Single-Page or Mobile Application. We will be using <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> together with <a href="https://www.django-rest-framework.org/">Django REST Framework</a> (DRF) to exchange an access token obtained by a third-party OAuth provider (GoogleOAuth2) with an authentication token from DRF.</p><p><em>Note: We will only work with API endpoints and not be using Djangos&#39; built-in template language in this example.</em></p><h4>The authentication process</h4><p>Authentication with OAuth2 offers different flows, depending on the specific setup you are using for your application. The basics and which flow to choose for your project are covered well in these two articles from <a href="https://aaronparecki.com/oauth-2-simplified/#mobile-apps">Aaron Parecki</a> and <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/which-oauth-2-0-flow-should-i-use">Auth0</a>.</p><p>In this example, we are using the <a href="https://oauth.net/2/pkce/">Authorization Code Flow with Proof Key for Code Exchange (PKCE)</a>, which is the recommended way when public clients, like Single-Page and Mobile Applications, request an access token from an OAuth2 provider. The authentication process with the provider happens on the client, which after successful authentication exchanges the received access token for another authentication token from the backend. With this token, the client can then be authenticated to use the APIs provided by the backend.</p><p>Further details about this flow are well explained in this <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-proof-key-for-code-exchange-pkce">Auth0 article</a>. The exception in our case is, that we are connecting directly to GoogleOAuth2, instead of Auth0.</p><p><strong><em>Is this the right social authentication package for me?<br></em></strong><em>Note: If you are unsure if this is the best package for your use case, you can find a brief comparison between four popular social authentication packages for Django in </em><a href="https://medium.com/codex/django-allauth-vs-dj-rest-auth-vs-python-social-auth-vs-drf-social-oauth2-ef7d50f92d16"><em>this article</em></a><em>.</em></p><h3>Prerequisites</h3><h4>Django</h4><p>Before we start I am asking you to install and set up your Django project. If you are unsure of how to do that, please check the ‘<a href="https://www.djangoproject.com/start/">Get started with Django</a>’-documentation.</p><h4>Django REST Framework</h4><p>We are using <a href="https://www.django-rest-framework.org/">Django REST Framework</a> (DRF) for setting up the REST API endpoints and a basic understanding of it is recommended. The scope of this Article will not cover much about DRF itself, however, the information provided in its ‘<a href="https://www.django-rest-framework.org/tutorial/quickstart/#quickstart">Quickstart</a>’-Tutorial will be more than enough to follow along here.</p><h4>Obtaining an access token</h4><p>To test your application you will need a GoogleOAuth2 access token. This would usually be obtained by your frontend, like a Single-Page or Mobile Application. For development purposes, you can also do that by using a web browser and curl, as described <a href="https://medium.com/codex/manually-obtain-googleoauth2-access-token-with-your-web-browser-and-curl-fd93effe15ff">here</a>.</p><p><em>Note: Make sure to request the required scope to adequately populate your user model, when sending the OAuth request with the client. <br>For GoogleOAuth2 it is: </em><em>scope = [&#39;email&#39;, &#39;profile&#39;] .</em></p><h3>Getting Started</h3><p>Assuming that you have set up your Django Project and have already applied your initial migrations, let’s start by adding a new app called users. In there we are building our authentication logic:</p><pre>python manage.py startapp users</pre><p>Next, we install the required third-party packages.</p><pre>pip install django \</pre><pre>djangorestframework \</pre><pre>social-auth-core \</pre><pre>social-auth-app-django</pre><p>After installation, we register the users and external apps in our settings.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a26155db90c4a6731a1dd8d9e307817c/href">https://medium.com/media/a26155db90c4a6731a1dd8d9e307817c/href</a></iframe><p>Finally, we run the migrations that come with <a href="https://www.django-rest-framework.org/">DRF</a> and <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a>.</p><pre>python manage.py migrate</pre><p><strong><em>For PostgreSQL users:</em></strong><em><br>In this example, we are using the SQLite3 database, that Django uses by default. If you are working with a PostgreSQL database, it is recommended to use the built-in JSONB field for storing the extracted </em><em>extra_data , by adding this line to your settings.py: </em>SOCIAL_AUTH_JSONFIELD_ENABLED = True</p><p><strong><em>For MongoEngineORM users:</em></strong><em><br>If you are using the </em><a href="http://mongoengine.org/"><em>MongoEngine</em></a><em> ORM, installation and setup vary slightly. Please check </em><a href="https://python-social-auth.readthedocs.io/en/latest/configuration/django.html"><em>the official docs of python-social-auth</em></a><em>.</em></p><h3>Configuration</h3><h4>Token-based authentication and permission classes from DRF</h4><p>For DRF we are adding a few entries into our settings.py to define authentication and permission classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a7237db0e26b44a4446638359a0286a/href">https://medium.com/media/5a7237db0e26b44a4446638359a0286a/href</a></iframe><p><strong>Authentication<br></strong>By adding rest_framework.authtoken to our INSTALLED_APPS and adding TokenAuthentication to the list of default authentication classes, we enabled <a href="https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication">DRFs built-in token authentication</a>. It provides a simple token-based HTTP Authentication scheme.</p><p>In our example, we are exchanging the access token received from the social provider in our frontend for one of these tokes. It can then be used to authenticate against our protected API endpoints.</p><p><strong><em>Note: This is not a very secure authentication scheme and is used only for presentation purposes. For production-level applications, you want to consider a more secure alternative.</em></strong></p><p><strong>Permissions<br></strong>By default, all API requests need to be authenticated with this setting. We can change this behavior on APIs that are intended to be public, later on.</p><h4>Authentication backends</h4><p>Django keeps a list of authentication backends, to iterate through on an authentication request. It defaults to Django’s basic authentication backend but can be <a href="https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#authentication-backends">extended or replaced as necessary</a>. In this example, we are adding a backend for <a href="https://python-social-auth.readthedocs.io/en/latest/backends/google.html#google-oauth2">GoogleOAuth2</a> authentication. You can find a full list of available options with python-social-auth, <a href="https://python-social-auth.readthedocs.io/en/latest/backends/index.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5997b9763f682915f0696dbb40edd5f1/href">https://medium.com/media/5997b9763f682915f0696dbb40edd5f1/href</a></iframe><p><em>Note: If the entry </em><em>AUTHENTICATION_BACKENDS does not exist, you must create it yourself.</em></p><h4>Social auth pipeline</h4><p><a href="https://python-social-auth.readthedocs.io/en/latest/pipeline.html">Pipeline mechanisms</a> are used to handle authentication, association, and disconnection flows in python-social-auth. Default flows exist for these pipelines and can be adjusted as required (Adding custom functions; Removing default items).</p><p>The default authentication pipeline can be found, <a href="https://python-social-auth.readthedocs.io/en/latest/pipeline.html#authentication-pipeline">here</a>. To define your own, you can add it to your settings.py.</p><p><em>Note: In this example, we use the default pipeline, without adding our own version. However, you can find an example version below.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8cf4dd755a93448fd34fc48381ab20e/href">https://medium.com/media/c8cf4dd755a93448fd34fc48381ab20e/href</a></iframe><h4>Creating the API endpoints</h4><p>We will use a registration endpoint to register/login a user with an access token from a social provider (GoogleOAuth2). This endpoint will be open to the public. Furthermore, we are defining a second endpoint that can be used with the authentication tokens handed out by our backend.</p><h4>Creating the view</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f3f4edcb72bcde6ded9825b87e0385/href">https://medium.com/media/69f3f4edcb72bcde6ded9825b87e0385/href</a></iframe><h4>The @psa() decorator</h4><p>The @psa() decorator is the key piece of our view. It connects our view with <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> and adds details to the request object.</p><ul><li>The social strategy (In our case, Django)</li><li>The social authentication backend to use (In our case, GoogleOAuth2), based on the backend argument in our view.</li><li>Providing the redirect URL (In our case: None. We perform the authentication on the client-side)</li></ul><p><em>Note: Unfortunately, the @psa() decorator is barely mentioned in the official documentation of </em><a href="https://python-social-auth.readthedocs.io/en/latest/use_cases.html?highlight=%40psa#signup-by-oauth-access-token"><em>python-social-auth</em></a><em>, but some additional information can be found in this </em><a href="https://stackoverflow.com/questions/28626718/what-is-the-purpose-of-the-psa-decorator-and-how-do-we-use-it"><em>StackOverflow post</em></a><em>.</em></p><h4>Adding URLs</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9297d5fb4c560fa821d06255498b1137/href">https://medium.com/media/9297d5fb4c560fa821d06255498b1137/href</a></iframe><h3>Testing our API</h3><h4>Register/Login user</h4><p>With the access token obtained from our client we can now test our API:</p><pre>curl -X POST \</pre><pre>http://127.0.0.1/api/register-by-access-token/social/google-oauth2/ \</pre><pre>-H &#39;Accept: application/json&#39; \</pre><pre>-H &#39;Content-Type: application/json&#39; \</pre><pre>-d &#39;{&quot;access_token&quot;: &quot;&lt;GoogleOAuth2-ACCESS-TOKEN-FROM-CLIENT&gt;&quot;}&#39;</pre><p>This should yield something like: {&quot;token&quot;: &quot;&lt;TOKEN-FROM-BACKEND&quot;} .</p><h4>Test returned token</h4><p>Using the received authentication token from our backend, we can now access the protected endpoint.</p><pre>curl \</pre><pre>http://127.0.0.1/api/authentication-test/ \</pre><pre>-H &#39;Accept: application/json&#39; \</pre><pre>-H &#39;Content-Type: application/json&#39; \</pre><pre>-H &#39;Authorization: Token fd4d4cca9163e5afb251f6310b9c725413979f10&#39;</pre><p>{&quot;message&quot;: &quot;User successfully authenticated&quot;}</p><h3>Summary</h3><p>You now have a simple REST API endpoint to create and log in Google users. To receive access, simply exchange an access token obtained with your frontend for an authentication token of your backend. To use other authentication providers like Facebook or Twitter, follow the same principle with a different authentication backend.</p><p><strong>Feel free to post your questions/comments in the comments or hit me up on </strong><a href="https://twitter.com/florian_abel_"><strong>Twitter</strong></a><strong> (</strong><a href="https://twitter.com/florian_abel_"><strong>@florian_abel_</strong></a><strong>). I’d be happy to hear your thoughts, questions, and experiences.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d087cd6d47f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/google-sign-in-rest-api-with-python-social-auth-and-django-rest-framework-4d087cd6d47f">Google sign-in REST API with python-social-auth and Django REST Framework</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manually obtain GoogleOAuth2 access token with your web browser and curl]]></title>
            <link>https://medium.com/codex/manually-obtain-googleoauth2-access-token-with-your-web-browser-and-curl-fd93effe15ff?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd93effe15ff</guid>
            <category><![CDATA[token]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 17:06:31 GMT</pubDate>
            <atom:updated>2022-07-09T17:06:31.891Z</atom:updated>
            <content:encoded><![CDATA[<p>If you manually need to obtain an access token from GoogleOAuth2, for development (or other) reasons, you can do so in a few simple steps with your web browser and curl.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o9SI7XJT2ZoMU971" /><figcaption>Photo by <a href="https://unsplash.com/@zisun_word?utm_source=medium&amp;utm_medium=referral">ZSun Fu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Note: This article has been inspired partly based on the following two resources. There has been </em><a href="https://www.daimto.com/how-to-get-a-google-access-token-with-curl/"><em>another way to do this</em></a><em> in the past, which recently stopped working. In my search for a new solution, I found this </em><a href="https://stackoverflow.com/questions/66940072/get-google-oauth2-access-token-using-only-curl"><em>post on StackOverflow</em></a><em>, in which this approach is being discussed.</em></p><h3>Registering an Application with GoogleOAuth2</h3><p>In order to obtain an access token from GoogleOAuth2, you first need to register your application at the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><ol><li>Create a new project</li><li>Define your <a href="https://console.cloud.google.com/apis/credentials/consent">OAuth Consent Screen</a></li><li>Create <a href="https://console.cloud.google.com/apis/credentials">credentials</a></li></ol><h4>Creating the credentials</h4><p>We are starting at the <a href="https://console.cloud.google.com/apis/credentials">Credentials-Page</a>:</p><ol><li>Select + Create Credentials at the top of the Page</li><li>Choose OAuth client ID</li><li>Web application as Application type</li><li>Name it as you wish</li><li>Under Authorized redirect URIs select + Add URI and add <a href="http://127.0.0.1/">http://127.0.0.1</a></li><li>Select Create</li><li>Copy and save the shown Client ID and Client Secret</li></ol><h3>Obtaining the access token</h3><h4>User authentication</h4><p>Within your web browser open the following URI (Do not forget to fill in your client id) and authenticate your application (Sign in to your account if requested).</p><pre>https://accounts.google.com/o/oauth2/auth?client_id=&lt;CLIENT-ID&gt;&amp;redirect_uri=http://127.0.0.1&amp;scope=profile&amp;email&amp;response_type=code&amp;include_granted_scopes=true&amp;access_type=offline&amp;state=state_parameter_passthrough_value</pre><p>After authentication, Google redirects you to your specified redirect URI, which is responsible for handling the authentication request response. Since no server is running at this URI, your browser shows an error page. However, in the address bar of the browser, you will find the redirect request from Google.</p><pre>http://127.0.0.1/?...&amp;code=&lt;CODE&gt;&amp;...</pre><p>Within you have a parameter named code , that we are going to copy and save for the next step.</p><h4>Requesting access token</h4><p>With the previously obtained code parameter, we are now running a curl request to ask Google for the access token. Fill in your code , client id , client secret and redirect URI and run the command in your terminal.</p><pre>curl -X POST https://oauth2.googleapis.com/token \<br>-d &quot;code=&lt;CODE&gt;&amp;client_id=&lt;CLIENT-ID&gt;&amp;client_secret=&lt;CLIENT-SECRET&gt;&amp;redirect_uri=&lt;REDIRECT-URI&gt;&amp;access_type=offline&amp;grant_type=authorization_code&quot;</pre><p>This gives you a response like this:</p><pre>{</pre><pre>  &quot;access_token&quot;: &quot;&lt;ACCESS-TOKEN&gt;&quot;,</pre><pre>  &quot;expires_in&quot;: 3599,</pre><pre>  &quot;refresh_token&quot;: &quot;&lt;REFRESH-TOKEN&gt;&quot;,</pre><pre>  &quot;scope&quot;: &quot;https://www.googleapis.com/auth/user.birthday.read     https://www.googleapis.com/auth/userinfo.email  https://www.googleapis.com/auth/userinfo.profile openid&quot;,</pre><pre>  &quot;token_type&quot;: &quot;Bearer&quot;,</pre><pre>  &quot;id_token&quot;: &quot;XXX&quot;</pre><pre>}</pre><p>Now you have an access token, that you can use e.g. for development purposes.</p><h4>Refreshing access token</h4><p>If your access token expires, refresh it with this command:</p><pre>curl -X POST https://oauth2.googleapis.com/token \<br>-d &quot;access_type=offline&amp;refresh_token=[ZZZZ]&amp;client_id=&lt;CLIENT-ID&gt;&amp;client_secret=&lt;CLIENT-SECRET&gt;&amp;grant_type=refresh_token&quot;</pre><h4>Other scopes</h4><p>In this example, we have requested the email and profile information of the user. If you want to obtain other scopes with your access token, add the desired scopes to your request.</p><h3>Conclusion</h3><p>With these easy steps, you can quickly obtain an access token from GoogleOAuth2. You can then use it e.g. during development to test (parts of) your software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd93effe15ff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/manually-obtain-googleoauth2-access-token-with-your-web-browser-and-curl-fd93effe15ff">Manually obtain GoogleOAuth2 access token with your web browser and curl</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using persistent data in a dockerized Django development environment]]></title>
            <link>https://medium.com/codex/using-persistent-data-in-a-dockerized-django-development-environment-cec794db32a0?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cec794db32a0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 13:29:58 GMT</pubDate>
            <atom:updated>2022-07-04T14:25:38.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Run Django inside a Docker container, mirroring your codebase, for a clean development environment that reflects code changes in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sD0DunTHs5mY939g" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Development environment</h3><p>Having a clean development environment where you can specify exactly which system and packages are being used is vital. It prevents interference between packages being installed on the host machine and those being used for your project. Docker containers provide a confined, clearly specified and reproducible environment and file changes on the host do not affect the container. However, during development, our code base changes continuously. To reflect these changes our container needs to be rebuilt and rerun continuously.</p><h4>Djangos development server</h4><p>Django runs its own development server, monitoring file changes and restarting when necessary. Shielded from the outside, these file changes do not happen inside a classical container setup.</p><h4>Local database setup</h4><p>Furthermore, working with a local database file like SQLite3 (Djangos default), all changes like migrations or database entries will be wiped clean every time the container is stopped (or restarted). Migrations can be rerun, even though it’s quite a tedious task. Other data will be lost completely.</p><h4>Mounting a volume to a container</h4><p>Mounting the project folder and database as a volume to the Docker container gives it read and write access. In other words, existing data (our project files and database) can be accessed and edited by the container, as well as new data can be saved permanently.</p><h3>Setting up the environment</h3><h4>Our project structure</h4><p>We want to mount the entire content of our project folder, including the database file we are using, for local development.</p><pre>|-django_docker_setup<br>|---django_docker_setup<br>|---example_application<br>|-----migrations<br>|-manage.py<br>|-requirements.txt<br>|-Dockerfile<br>|-Database-File</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/679585506972eaf5968ffeddb886de29/href">https://medium.com/media/679585506972eaf5968ffeddb886de29/href</a></iframe><h4>Our Dockerfile</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/344145f6f7189ca2c0c80f497d597ad0/href">https://medium.com/media/344145f6f7189ca2c0c80f497d597ad0/href</a></iframe><h3>Building and running our container</h3><h4>Mounting a volume</h4><p><a href="https://docs.docker.com/storage/volumes/">Mounting a volume</a> is the preferred mechanism to make data, used or generated by the Docker container, persistent.</p><p>In order to mount the folder to our container, we are using the -v or --volume flag on the docker run and specify the origin and destination paths:</p><pre>docker run -v &lt;Path of folder to mount&gt;:&lt;Path to mount inside container&gt;</pre><h4>Publishing the port</h4><p>In order to reach our Django application from outside the container, we need to publish a port to the host. In this case, we are mapping the previously exposed container port (8000) to the HTTP port (80) of our host. The format we are using is the following, more possibilities can be found in the <a href="https://docs.docker.com/engine/reference/run/#expose-incoming-ports">Docker docs</a>.</p><pre>docker run -p hostPort:containerPort</pre><h4>The full command:</h4><pre>docker build -t container-name .<br>docker run -v $(pwd):/home/ -p 80:8000 container-name</pre><p>Since our Dockerfile lives within the project folder, we want to mount all data from within that folder inside the working directory we have specified in the Dockerfile.</p><ul><li>$(pwd) prints the path to the current working directory</li><li>/home/ is the absolute path, as defined in our Dockerfile</li></ul><h4>Accessing the running container</h4><p>At this point, your Django project is running within your container. To access the container we can use <a href="https://docs.docker.com/engine/reference/commandline/exec/">docker exec</a> . It runs a command in a running container, allowing us to open a shell.</p><p>First, we need to find our container id, by running:</p><pre>docker ps</pre><p>which gives us something like this:</p><pre>CONTAINER ID   IMAGE                        COMMAND                  CREATED         STATUS         PORTS                      NAMES</pre><pre>3fe54fa54c56   container-name   &quot;/bin/sh -c &#39;python3…&quot;   2 minutes ago   Up 2 minutes   0.0.0.0:80-&gt;8000/tcp       priceless_robinson</pre><p>With the container id 3fe54fa54c56 we can now open our shell and run our migrations or whatever else we desire:</p><pre>docker exec -it 3fe54fa54c56 bash</pre><p>Inside we can now make or run our migrations in a persistent way:</p><pre>dockeruser@3fe54fa54c56:/$ python3 manage.py migrate</pre><h4>Changing files during runtime</h4><p>Also, code changes made during runtime will be mirrored inside the container in real-time. Changing a file outside of the container will instantly be registered by the Django application, and the development server restarts.</p><h3>Summary</h3><p>With these few simple steps, you created an environment that does not interfere with your host machine&#39;s setup, while keeping the development process smooth and easy. The environment is confined from your host’s system, clearly specified and reproducible. At the same time, file changes outside your container are instantly reflected inside, while changes inside, like migrations or database entries, are made persistent beyond the life of the currently running container.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cec794db32a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/using-persistent-data-in-a-dockerized-django-development-environment-cec794db32a0">Using persistent data in a dockerized Django development environment</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django-allauth vs dj-rest-auth vs python-social-auth vs drf-social-oauth2]]></title>
            <link>https://medium.com/codex/django-allauth-vs-dj-rest-auth-vs-python-social-auth-vs-drf-social-oauth2-ef7d50f92d16?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef7d50f92d16</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[social]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 16:38:14 GMT</pubDate>
            <atom:updated>2022-06-30T16:38:14.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Finding the right social authentication package for your Django project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2MnUdJHOZq84wGle" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FLY:D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Package hell 🔥</h3><p>Unfortunately, there is an overwhelming amount of packages available, trying to address the task of (social) authentication in a Django project. I am comparing four popular packages based on functionality, development history, popularity, and documentation. They have been preselected based on popularity and active development status.</p><h3>Package overview</h3><h4><a href="https://django-allauth.readthedocs.io/">django-allauth</a></h4><p><a href="https://django-allauth.readthedocs.io/">Django-allauth</a> is one of the most popular authentication packages in the Django world, offering broad functionality for classical and social authentication. It is being developed and actively maintained for over 10 years already, is being used in almost 100.000 projects, and has a large base of contributors. Its documentation is extensive, straightforward, and easy to understand, just as it is quite easy to implement. The package comes, however, with one big downside. It does provide no out-of-the-box functionality to using it with <a href="https://www.django-rest-framework.org/">django-rest-framework</a>, limiting it to the use with Django’s template language. Therefore, excluding all projects that are run headless with a Single-Page-Application or Mobile Application as Frontends. Overall, it is a well-developed package for (social) authentication with Django, but it lacks the REST API functionality, which is a big downside.</p><h4><a href="https://dj-rest-auth.readthedocs.io/">dj-rest-auth</a></h4><p><a href="https://dj-rest-auth.readthedocs.io/">DJ-rest-auth</a> is being built on top of <a href="https://django-allauth.readthedocs.io/">django-allauth</a> and closes the gap to using authentication with <a href="https://www.django-rest-framework.org/">django-rest-framework</a>, effectively allowing (social) authentication also for headless Django applications via the use of REST API endpoints. It is being developed for several years and is still actively maintained. With almost 1000 stars and 100+ contributors, it is also a highly popular package. Its documentation is straight to the point, easy to follow, and covers everything essential. Overall, it appears to be a great package for implementing (social) authentication with Django and <a href="https://www.django-rest-framework.org/">django-rest-framework</a>.</p><h4><a href="https://python-social-auth.readthedocs.io/">python-social-auth</a></h4><p>This package offers social authentication and authorization for python projects, supporting OAuth1, OAuth2, and OpenID protocols, among others. It has been developed for several years and is still actively maintained. The codebase was initially derived from django-social-auth, aiming to provide a more general package, also supporting other Python frameworks such as Flask. The package is split into several modules whereas the <a href="https://github.com/python-social-auth/social-core">core module</a> alone has 18000+ users and hundreds of contributors. The documentation is extensive, straightforward, and fairly easy to understand. Overall, it can be considered a safe bet for implementing a (social) authentication solution in a Python (not just Django) project.</p><h4><a href="https://github.com/wagnerdelima/drf-social-oauth2">drf-social-oauth2</a></h4><p><a href="https://github.com/wagnerdelima/drf-social-oauth2">Drf-social-oauth2</a> is a wrapper around <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> and <a href="https://django-oauth-toolkit.readthedocs.io/">django-oauth-toolkit</a> combining their functionality within one package. Effectively giving you easy access to setting up social authentication with a REST API endpoint as well as setting up an OAuth Provider. Its advantage over <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> comes into play when you also want to set up an OAuth Provider yourself additionaly to giving your users the possibility to authenticate via a common social provider. It appears to be the successor of <a href="https://github.com/RealmTeam/django-rest-framework-social-oauth2">django-rest-framework-social-oauth2</a> and is actively maintained. At first sight, it seems to be not as popular as the other packages. This might just be due to its taking over from <a href="https://github.com/RealmTeam/django-rest-framework-social-oauth2">django-rest-framework-social-oath2</a> in 2019 though. The documentation is not too extensive but straightforward and covers all base cases. Furthermore, since it is a wrapper around two other packages, you can dig deeper within their documentation. Overall, it is a nice package if you are interested in implementing (social) authentication via REST API endpoint and also want to set up an OAuth Provider yourself.</p><h3>Summary</h3><p>When it comes to popularity, development status, and documentation all four packages seem to be doing very well. The differences are mainly found in the different scopes of functionality. Which package is the right one for your project will heavily depend on your specific requirements.</p><p>If you have a Django project, using its built-in template language, and want to use a well-developed and heavily tested package, <a href="https://django-allauth.readthedocs.io/">django-allauth</a> is probably the right choice for you. If you need to implement authentication via REST API endpoints as well, then <a href="https://dj-rest-auth.readthedocs.io/">dj-rest-auth</a> or <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> are both excellent choices. Whereas, <a href="https://dj-rest-auth.readthedocs.io/">dj-rest-auth</a> relies on <a href="https://django-allauth.readthedocs.io/">django-allauth</a>, <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> functions as a standalone package and can also be used with other frameworks than Django. If additionally, you want to set up your own OAuth Provider, <a href="https://github.com/wagnerdelima/drf-social-oauth2">drf-social-oauth2</a> might be for you, wrapping <a href="https://python-social-auth.readthedocs.io/">python-social-auth</a> and <a href="https://django-oauth-toolkit.readthedocs.io/">django-oauth-toolkit</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef7d50f92d16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/django-allauth-vs-dj-rest-auth-vs-python-social-auth-vs-drf-social-oauth2-ef7d50f92d16">Django-allauth vs dj-rest-auth vs python-social-auth vs drf-social-oauth2</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Tinder-like swiping interface in Flutter]]></title>
            <link>https://medium.com/codex/building-a-tinder-like-swiping-interface-in-flutter-5a799901df74?source=rss-4027b693372a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a799901df74</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Florian Abel]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 15:52:45 GMT</pubDate>
            <atom:updated>2022-06-25T14:59:37.585Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR: If you are only interested in the swiping functionality you can jump straight <a href="#2201">here</a>, or check out the final project on <a href="https://github.com/florianabel/swiping-interface">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LIRP8M6UUYNVpoiW" /><figcaption>Photo by <a href="https://unsplash.com/@sanjaymehra?utm_source=medium&amp;utm_medium=referral">Sanjay Mehra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Intro</strong></h3><p>In this article you will be guided step-by-step through the development of a tinder-like swiping interface with the Flutter framework.</p><p>What I like about the interface is the simplicity that allows a user to easily decide for or against a choice that is outlined in a Card. It can be useful for all types of Apps that need an easy YES/NO selection process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*uLdgrew0t1r373A0V5B0iA.gif" /></figure><h3>The Flutter framework</h3><p>Since this interface is best served on mobile devices and I was aiming at reusability across different platforms I decided to build this project in Google’s Flutter framework. It provides functionality to develop multi-platform applications that are usable on both Android and Apple phones, tablets, and even web applications from a single codebase.</p><h3><strong>Used Elements</strong></h3><p>The main components to building the swiping interface in this project are:</p><ul><li><a href="https://api.flutter.dev/flutter/widgets/Container-class.html">Container</a></li><li><a href="https://api.flutter.dev/flutter/widgets/Expanded-class.html">Expanded</a></li><li><a href="https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html">LayoutBuilder</a></li><li><a href="https://api.flutter.dev/flutter/widgets/Draggable-class.html">Draggable</a></li></ul><p>Furthermore, we will be using the <a href="https://api.dart.dev/stable/2.17.3/dart-convert/dart-convert-library.html">dart:convert library</a> and <a href="https://docs.flutter.dev/development/data-and-backend/json#serializing-json-inside-model-classes">Model-Class serialization</a> to read and decode some JSON data in order to populate the profile cards to swipe.</p><h3><strong>Setup</strong></h3><p><em>Please note, that this article is assuming a prior setup of your Flutter development environment. If you have not worked with Flutter before you can find a ton of free resources on how to get started in building your own applications on their official Flutter Website, </em><a href="https://docs.flutter.dev/get-started/install"><em>here</em></a><em>.</em></p><h4>Creating the Flutter project</h4><p><em>The process of setting up a Flutter project template differs a little bit, depending on the IDE you are working with. To make it best accessible and independent from any IDE I will be using the terminal for all steps throughout this article.</em></p><p>Let’s start with setting up a Flutter template project in our terminal:</p><pre>flutter create swiping_interface<br>cd swiping_interface</pre><p>Next, let’s clean up the template project and build the main skeleton of our app. Inside of ‘<strong>lib/main.dart</strong>’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b43652b514fdb535fd007ac88f94946/href">https://medium.com/media/5b43652b514fdb535fd007ac88f94946/href</a></iframe><h3><strong>Importing Assets</strong></h3><p>In order to show some nice profile cards on the screen, we need data to populate the cards. For this project, we are going to store some profile pictures and additional profile information as JSON locally in the applications assets folder.</p><h4>Creating the folder structure</h4><p>Inside our application folder let’s create a new folder called ‘assets’ and inside the assets folder another folder called ‘json’ and one more called ‘profilepictures’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*FNiIvYYayuEVv7-kp8u5pg.png" /></figure><h4>Adding profile pictures</h4><p>For the profile pictures, I went to <a href="https://www.pexels.com/">Pexels</a>, grabbed a few suitable profile pictures, and dropped them into the ‘profilepictures’ folder.</p><h4>Adding profile data</h4><p>Inside the ‘json’ folder we can create a ‘profiles.json’ like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dc29c4b9940ab38a0aa9d4dd83b50a1/href">https://medium.com/media/8dc29c4b9940ab38a0aa9d4dd83b50a1/href</a></iframe><h4>Making the data available in your application</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acb879419d6d5dbca5772ace0b4edd06/href">https://medium.com/media/acb879419d6d5dbca5772ace0b4edd06/href</a></iframe><p>Inside the ‘flutter’ section of ‘pubspec.yaml’ we are adding an ‘assets’ section, telling Flutter which folders can be used as assets inside the application. More info on that topic can be found <a href="https://docs.flutter.dev/development/ui/assets-and-images">here</a>.</p><h3>Application-Layout</h3><p>It’s time to bring a bit more on the screen now. Let’s start with a basic application outline.</p><h4>Material widget and SafeArea</h4><p>We are adding a <a href="https://api.flutter.dev/flutter/material/Material-class.html">Material widget</a> for some basic styling and a <a href="https://api.flutter.dev/flutter/widgets/SafeArea-class.html">SafeArea</a> to make sure our App is not extending over unsafe boundaries such as nudges. Furthermore, let’s add a basic <a href="https://api.flutter.dev/flutter/widgets/Container-class.html">Container</a> to hold all the elements from our layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/779f15e7956a6e0a48d635951d1c4b05/href">https://medium.com/media/779f15e7956a6e0a48d635951d1c4b05/href</a></iframe><h4>Container styling and base layout</h4><p>Now it’s time to fill this Container with a bit of styling and its first life, positioning it in the center of the screen and giving it a white background. Inside we are defining a Column with three child widgets:</p><ul><li>A Container to hold a logo</li><li>The card that we want to swipe in the end</li><li>Another Container to hold a navigation</li></ul><p><em>Since the ‘SwipeCard()’ is not defined yet, your IDE is probably going to show you an error at this stage. We are going to fix this in the next section.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af4d1502936f77363a5f53ad977d8cd7/href">https://medium.com/media/af4d1502936f77363a5f53ad977d8cd7/href</a></iframe><p>Below you can see the complete ‘main.dart’ file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd55ef64572ab17122dd3f658905eb86/href">https://medium.com/media/bd55ef64572ab17122dd3f658905eb86/href</a></iframe><h3>Building the card-layout</h3><p>In the last section, we have used a ‘SwipeCard()’ widget which has not been defined yet. Let’s start by creating another file inside the ‘lib’-folder and calling it ‘swipe_card.dart’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*g9AamBfbeRZz4877GBRJ6g.png" /></figure><p>Inside this file, we are going to build our Card-Interface for a user’s profile.</p><h4>Base layout</h4><p>First, we are creating e a base layout for the Card and then we will get to styling it in the next steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d475bc9d2197d9cec48125773b46d3/href">https://medium.com/media/e4d475bc9d2197d9cec48125773b46d3/href</a></iframe><p>Inside our ‘main.dart’-file we are importing the SwipeCard widget, so Flutter can actually access it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c08a91a4e8d3e655e62d6030800fc4c5/href">https://medium.com/media/c08a91a4e8d3e655e62d6030800fc4c5/href</a></iframe><h4>Displaying a profile picture</h4><p>It might not look like much but we have created the groundwork for building up our interface and the swiping functionality. Now let’s go on to draw something on the screen:</p><p>First, we are adding a <a href="https://api.flutter.dev/flutter/painting/BoxDecoration-class.html">BoxDecoration</a> widget to the Container’s decoration property, this gives us the possibility to add a background image to it and add some nice rounded corners.</p><p>However, since the <a href="https://api.flutter.dev/flutter/widgets/Container-class.html">Container</a> widgets by default inherit the size of their children and we do not have a child widget here, we won’t see much on the screen yet. Therefore, we are adding an <a href="https://api.flutter.dev/flutter/widgets/Expanded-class.html">Expanded</a> widget around the Container to make it fill all the available space.</p><p>Finally, to make this Card look nice we are also adding some <a href="https://api.flutter.dev/flutter/painting/EdgeInsets-class.html">margins</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdf85e5b0059e62de39ce06074f5b4ab/href">https://medium.com/media/fdf85e5b0059e62de39ce06074f5b4ab/href</a></iframe><p><em>If you go back a little bit you can see that so far we are occupying some space for the SafeArea, 60 pixels on top for a logo Container and 60 pixels on the bottom for a Navigation Container. Hence our SwipeCard Widget will now fill the remaining space available.</em></p><figure><img alt="Application-Layout with Logo-Container on top, SwipeCard in the middle and Navigation-Container on the bottom" src="https://cdn-images-1.medium.com/max/351/1*I7fjfUjYl1ckFPFiM7xOyA.png" /><figcaption>Application-Layout with Logo-Container on top, SwipeCard in the middle, and Navigation-Container on the bottom</figcaption></figure><h3>Making SwipeCard reusable and adding more data to it</h3><p>As you might have noticed in the last step, we have been hard-coding the path to our background image. This is making it impossible to reuse our widget for other profiles.</p><h4>Making the widget reusable</h4><p>First, let’s add some class variables and adjust our constructor. This way we can pass the necessary information into our widget and make it reusable. We are defining:</p><ul><li>id</li><li>userName</li><li>userAge</li><li>userDescription</li><li>profileImageSrc</li></ul><p>As you can see, the path for the image is not hardcoded anymore and depends on a path being passed into the Widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16050195c34819d0b3af410af99ed825/href">https://medium.com/media/16050195c34819d0b3af410af99ed825/href</a></iframe><p>Later we are going to populate this Widget with the data we have defined earlier on in our JSON-File. For now, we are going to populate it manually, when we are invoking it at ‘main.dart’. So, please adjust <em>SwipeCard()</em> in your ‘main.dart’ to look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bf89da5f27c23e55477ff7d568e3ec6/href">https://medium.com/media/8bf89da5f27c23e55477ff7d568e3ec6/href</a></iframe><p><em>If everything went well, your App should still function as before and look exactly the same.</em></p><h4>Adding additional information to the layout</h4><p>For the additional information, we are adding a Container, a Column, and two children with some styling.</p><ul><li>The first child of the Column displays userName and userAge</li><li>The second child of the Column displays the user description. Make sure to add the overflow property so your user’s description does not overflow the available screen size.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea6ef5d5a435e07948b4da0d1627d6a0/href">https://medium.com/media/ea6ef5d5a435e07948b4da0d1627d6a0/href</a></iframe><p><em>If you are receiving an Error on the </em><strong><em>Colors Widget</em></strong><em> you might still be importing </em><strong><em>‘flutter/widgets.dart’</em></strong><em> instead of </em><strong><em>‘flutter/material.dart’</em></strong><em>, just adjust that line and you are good to go.</em></p><p>Now your layout should look like this:</p><figure><img alt="Final layout for the swiping interface" src="https://cdn-images-1.medium.com/max/351/1*EcXxvfIh1-gMUoekQLhw0A.png" /><figcaption>Final layout for the swiping interface</figcaption></figure><h3>Building the swipe functionality</h3><p>After we have finalized the layout it is now time to add some functionality to our interface.</p><p>In order to swipe through a stack of profiles we are going to need a few things:</p><ul><li>A stack of profiles that we can swipe through</li><li>A way to swipe our profile cards left and right and to surface the card below</li><li>Some container to understand the swiping gesture and what to do afterward</li></ul><h4>The swiping interface container</h4><p>We are going to create a new stateful widget, that holds all the necessary information and keeps track of what to show to the user.</p><p><em>In this article, I am not covering the details of stateless and stateful widgets. If this concept is new or unclear to you, please have a deeper look </em><a href="https://docs.flutter.dev/development/ui/interactive"><em>here</em></a><em>.</em></p><p>First, we are creating a new file ‘swipe_interface.dart’, and are setting up the basis for our stateful widget. For the moment we are using our previously build SwipeCard widget as the only child and are replacing SwipeCard inside ‘main.dart’ with our newly created SwipingInterface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22446212b807bb0913f2424b137e2a07/href">https://medium.com/media/22446212b807bb0913f2424b137e2a07/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b202ca77a9297a401e0a2c3fe3b10f/href">https://medium.com/media/59b202ca77a9297a401e0a2c3fe3b10f/href</a></iframe><h4>Populating a stack of profile cards from our profiles.JSON file</h4><p>We have made our SwipeCard widget reusable, but the data that we use to populate it is still hard-coded. Let’s change that and create a list of profiles from our JSON-file, that we can then use to populate the SwipeCard with data.</p><p>We are creating a new file called ‘profile.dart’ holding the Profile Class. Within this class we are creating a factory constructor to build a Profile object from JSON data:</p><p><em>For more information on the factory constructor, you can read </em><a href="https://medium.com/nerd-for-tech/factory-constructor-in-dart-part-1-1bbdf0d0f7f0"><em>here</em></a><em> and for more information on JSON and serialization in Flutter, you can read </em><a href="https://docs.flutter.dev/development/data-and-backend/json"><em>here</em></a><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908d24110a96b83fce3052f189afae4f/href">https://medium.com/media/908d24110a96b83fce3052f189afae4f/href</a></iframe><p>With this Profile Class available we can now easily create Profile Objects from JSON data. This is what we are going to do in our SwipeInterface, or actually we are going to create a list of Profile Objects.</p><p>Inside of our SwipeInterfaceState we are:</p><ul><li>Defining a list of type Profile, that we manually pre-populate with two entries (more on that later).</li><li>Defining a function to load the data from our profiles.json file in assets, then creating a list of Profiles from it, and finally updating our profiles variable with it.</li><li>Calling this function from the constructor, to fetch the data and create our list of profiles on widget build.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1316d64fa4ac7df172397efcc7eb8e5d/href">https://medium.com/media/1316d64fa4ac7df172397efcc7eb8e5d/href</a></iframe><p>Next, we are replacing the hard-coded data for SwipeCard with data from our list of profiles. And since we are handling a list of data, we are going to need a counter to indicate which profile should be loaded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/663e7ec6747476e4b1f1f73f3ebab180/href">https://medium.com/media/663e7ec6747476e4b1f1f73f3ebab180/href</a></iframe><p>Now we are populating the SwipeCard widget from the list of profiles based on our counter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60e7b99173e75c3b7c67115ebb06fb0/href">https://medium.com/media/b60e7b99173e75c3b7c67115ebb06fb0/href</a></iframe><p>Here you can see the full file for reference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7034fe36d22b4457e51389e2ff4dbb9f/href">https://medium.com/media/7034fe36d22b4457e51389e2ff4dbb9f/href</a></iframe><p>Now, our app should load all data from the JSON-file you have defined and show the first entry on the screen.</p><h4>Adding the swipe functionality to the stack of profile cards</h4><p>Now that we have all the building blocks in place, it is time to finally add the swiping interaction, using the <a href="https://api.flutter.dev/flutter/widgets/Draggable-class.html">Draggable</a> and <a href="https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html">LayoutBuilder</a> widgets, which cover a lot of the desired functionality out of the box.</p><ul><li>The Draggable Widget can be dragged around the screen and show different states in order to give feedback on the dragging process.</li><li>The LayoutBuilder Widget provides its parents’ constraints and can therefore be used to set constraints based on the parents’ size.</li></ul><p>At first, we are going to replace our static SwipeCard widget with a LayoutBuilder that returns a Draggable Widget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1973bf15d1271102ee1e17de5bf9c050/href">https://medium.com/media/1973bf15d1271102ee1e17de5bf9c050/href</a></iframe><p>Draggable comes with a bunch of properties. Three of them indicate different UI elements being used:</p><ul><li>feedback → Element that gets dragged around (For us, this is the current profile card).</li><li>childWhenDragging → Element that is shown in the original place of the Widget (For us this is the card that is hidden under the current profile card).</li><li>child → Element that is shown initially, before the drag process is started (For us this is the current profile card).</li></ul><p><em>For the feedback property, we are going to wrap our SwipeCard in a SizedBox widget. This gives us the possibility to define its height and width properties, based on the constraints provided by the LayoutBuilder. We need to do this because there seems to be a </em><a href="https://github.com/flutter/flutter/issues/39406"><em>persisting bug</em></a><em> with the feedback property, not providing constraints, and also not updating after rendering.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c484a69f0e59a70376a8b167945827c9/href">https://medium.com/media/c484a69f0e59a70376a8b167945827c9/href</a></iframe><p>Most likely your App will look something like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*cjYkA6Or5M-bGZWQMOQryA.png" /></figure><p>The problem here is based on the Expanded widget, which currently expands the SwipeCard as far as possible. Since we are using a LayoutBuilder now to wrap our Draggable and SwipeCards, we need to use the Expanded widget around the LayoutBuilder instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c03ee694bdbdd317757ea0d5d2cf75ac/href">https://medium.com/media/c03ee694bdbdd317757ea0d5d2cf75ac/href</a></iframe><p>Now we can already swipe the profile cards as we please and the only thing missing is some kind of logic to utilize the swiping gestures.</p><p><em>Note: Here you can see, that the styling of the feedback card is different than the original. This is most likely also caused by the aforementioned bug.</em></p><h4>Building logic to utilize swiping gestures</h4><p>We want the app to notice that a user has “liked” or “not liked” a profile, do with that information whatever it should do, and then show the next profile in the stack.</p><p>Draggable has a callback function called ‘onDragEnd’ that we can utilize. It is called once the drag movement has finished and it provides us with the offset in x and y directions (dx and dy).</p><p>We are going to check the offset in the x-direction (dx) and if it goes beyond a defined threshold, we will call the appropriate function to deal with it.</p><p>First, let’s define a threshold and some methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbf3fbc74f38754ca750e31d4b7b31c7/href">https://medium.com/media/dbf3fbc74f38754ca750e31d4b7b31c7/href</a></iframe><p>Next, inside of Draggable, let’s call onDragEnd and pass dx:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d23e86634455a6112d8d8b34e6131b/href">https://medium.com/media/a0d23e86634455a6112d8d8b34e6131b/href</a></iframe><p>Here, you can see the final version of the SwipeInterface widget:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60497370c9979b9b162f1b48beb142fe/href">https://medium.com/media/60497370c9979b9b162f1b48beb142fe/href</a></iframe><h3>Conclusion</h3><p>Now, you can be proud of your very own swiping interface, built in Flutter. It is not perfect and still has a few corners and edges. I am sure there are more/different ways of building this and some might be better suited than others also depending on the concrete requirements you are having for your project. I hope it gives you a great start on experimenting with this type of interface and that you can build on top of it.</p><p>I’d be happy to hear about your experiences and/or where you would take another way in building this. Please feel free to hit me up in the comments section or on <a href="https://twitter.com/florian_abel_">Twitter</a> (<a href="https://twitter.com/florian_abel_">@florian_abel_</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*uLdgrew0t1r373A0V5B0iA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a799901df74" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/building-a-tinder-like-swiping-interface-in-flutter-5a799901df74">Building a Tinder-like swiping interface in Flutter</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>