<?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 Berkan Çınar on Medium]]></title>
        <description><![CDATA[Stories by Berkan Çınar on Medium]]></description>
        <link>https://medium.com/@berkancnr?source=rss-fab1648686e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i_MtPTC3lUSmvhAG0VWFKQ.jpeg</url>
            <title>Stories by Berkan Çınar on Medium</title>
            <link>https://medium.com/@berkancnr?source=rss-fab1648686e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:25:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@berkancnr/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[Firestore Güvenlik Kurallarını Efektif Şekilde Kullanmak]]></title>
            <link>https://medium.com/@berkancnr/firestore-g%C3%BCvenlik-kurallar%C4%B1n%C4%B1-efektif-%C5%9Fekilde-kullanmak-707b177db61b?source=rss-fab1648686e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/707b177db61b</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Berkan Çınar]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 20:37:14 GMT</pubDate>
            <atom:updated>2024-08-12T20:37:14.564Z</atom:updated>
            <content:encoded><![CDATA[<p>Firestore, Google Cloud tarafından sunulan ve ölçeklenebilir, esnek bir veritabanı hizmetidir. Güvenli ve kontrollü bir şekilde veri erişimini sağlamak için Firestore, güvenlik kuralları kullanır. Bu makalede, Firestore güvenlik kurallarının ne olduğunu, nasıl çalıştığını ve nasıl efektif olarak yapılandırılabileceğini detaylı bir şekilde ele alacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5HK4Qb7SrjATpTkD7uMZw.jpeg" /></figure><h3>Firestore Güvenlik Kuralları Nedir?</h3><p>Firestore güvenlik kuralları, veritabanınıza erişimi ve veritabanındaki verilerin nasıl okunup yazılabileceğini kontrol eden bir kural setidir. Bu kurallar, Firebase Authentication ile entegre çalışarak, kullanıcı kimliğine göre erişim kontrolü sağlar. Ayrıca, verilerin doğruluğunu ve bütünlüğünü korumak için çeşitli koşullar ekleyebilirsiniz. Bu işlemler ile dışarıdan bir müdahale sonucunda bilgilerinizin değiştirilmesini ve çalınmasını önleyebilirsiniz.</p><h3>Güvenlik Kurallarının Temel Yapısı</h3><p>Firestore güvenlik kuralları, firestore.rules adlı bir dosyada tanımlanır. Bu dosya, genellikle aşağıdaki gibi bir yapıya sahiptir:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /{document=**} {<br>      allow read, write: if false;<br>    }<br>  }<br>}</pre><p>Bu yapı, service, match, allow anahtar kelimeleri ile oluşturulur.</p><ul><li>service: Hangi Firebase hizmeti için kurallar yazıldığını belirtir (cloud.firestore).</li><li>match: Kuralların hangi veri yolları için geçerli olduğunu belirtir.</li><li>allow: Hangi işlemlere (okuma, yazma vb.) izin verildiğini belirtir.</li></ul><h3>Erişim Kontrolü</h3><p>Firestore güvenlik kuralları ile erişim kontrolü yapmak için allow anahtar kelimesini kullanırız. Örneğin, bir koleksiyona yalnızca kimliği doğrulanmış kullanıcıların erişmesine izin vermek için aşağıdaki gibi bir kural yazabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null;<br>    }<br>  }<br>}</pre><p>Bu kural, users koleksiyonundaki belgelere yalnızca kimliği doğrulanmış kullanıcıların erişebileceğini belirtir. Gündelik hayatta kullandığımız bir çok uygulama daha detaylı iş akışına sahip olur bu nedenle yukarıdaki gibi basit bir kural seti ihtiyaçlarımıza tam karşılık veremeyebilir. Bu gibi durumlarda da koşullu erişimler tanımlamamız gerekir.</p><h3>Koşullu Erişim</h3><p>Firestore güvenlik kuralları, erişim kontrolünde daha ayrıntılı koşullar belirlememize olanak tanır. Örneğin, bir kullanıcının yalnızca kendi verilerine erişebilmesi için aşağıdaki gibi bir kural yazabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><p>Bu kural, kimliği doğrulanmış bir kullanıcının yalnızca kendi userId ile eşleşen belgelerine erişmesine izin verir. Bazı durumlarda yazmak istediğimiz dökümanın içerisindeki alanları kontrol etmek isteyebiliriz. Bir e-ticaret uygulaması yaptığınızı varsayalım. Yüklenecek ürünün fiyatının 0 veya altında olmasını istemeyiz. Bu gibi durumlarda da veri doğrulama ile bu işlemi yapabilirsiniz.</p><h3>Veri Doğrulama</h3><p>Firestore güvenlik kuralları, verilerin doğruluğunu sağlamak için de kullanılabilir. Örneğin, bir belgedeki belirli bir alanın belirli bir koşulu sağlamasını zorunlu kılabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /products/{productId} {<br>      allow create: if request.resource.data.price &gt; 0;<br>      allow update: if request.resource.data.price &gt; 0;<br>    }<br>  }<br>}</pre><p>Bu kural, products koleksiyonundaki belgelerin price alanının her zaman 0&#39;dan büyük olmasını zorunlu kılar. Çok daha detaylı ve karmaşık işlemler için kurallar içerisine function tanımlayabiliriz. Birden fazla veya bağımlılık içeren koşulları tek fonksiyon ile kontrol edebiliriz.</p><h3>Temel Fonksiyon Tanımlama</h3><p>Bir işlev tanımlamak için function anahtar kelimesini kullanırız. İşlev, bir veya daha fazla parametre alabilir ve bir değer döndürebilir.</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    <br>    // Kullanıcı kimliğini doğrulayan bir işlev tanımlama<br>    function isAuthenticated() {<br>      return request.auth != null;<br>    }<br><br>    // Kullanıcının kendi belgesine erişimini doğrulayan bir işlev tanımlama<br>    function isUserDocument(userId) {<br>      return request.auth.uid == userId;<br>    }<br><br>    match /users/{userId} {<br>      // İşlevleri kullanarak erişim kontrolü<br>      allow read, write: if isAuthenticated() &amp;&amp; isUserDocument(userId);<br>    }<br>  }<br>}</pre><p>Bu örnekte, isAuthenticated işlevi kullanıcının kimliğinin doğrulanıp doğrulanmadığını kontrol ederken, isUserDocument işlevi kullanıcının yalnızca kendi belgesine erişip erişemeyeceğini kontrol eder.</p><h3>Karmaşık Mantık İçin Fonksiyonlar</h3><p>Daha karmaşık mantık gerektiren durumlar için işlevleri kullanarak kuralları daha yönetilebilir hale getirebilirsiniz. Örneğin, bir kullanıcının bir belgenin sahibi olup olmadığını ve belgedeki belirli alanların doğru değerlere sahip olup olmadığını kontrol eden bir işlev yazabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Kullanıcının belge sahibi olup olmadığını kontrol eden işlev<br>    function isOwner(doc) {<br>      return request.auth != null &amp;&amp; request.auth.uid == doc.data.ownerId;<br>    }<br><br>    // Belgedeki fiyatın geçerli olup olmadığını kontrol eden işlev<br>    function isValidPrice(price) {<br>      return price &gt; 0;<br>    }<br><br>    match /products/{productId} {<br>      // Ürün belgelerine erişim kontrolü<br>      allow create, update: if isOwner(request.resource) &amp;&amp; isValidPrice(request.resource.data.price);<br>      allow read: if true;  // Herkesin okumasına izin ver<br>    }<br>  }<br>}</pre><p>Bu örnekte, isOwner işlevi bir belgenin sahibini doğrularken, isValidPrice işlevi fiyatın pozitif bir değer olup olmadığını kontrol eder. Bu işlevler, products koleksiyonundaki belgelere erişimi kontrol etmek için kullanılır.</p><h3>Fonksiyonlarla Koşullu Erişim</h3><p>İşlevleri kullanarak belirli koşullara dayalı erişim kontrolü yapabilirsiniz. Örneğin, bir kullanıcının yalnızca belirli bir rolü varsa belirli işlemleri yapmasına izin vermek için bir işlev yazabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Kullanıcının belirli bir role sahip olup olmadığını kontrol eden işlev<br>    function hasRole(role) {<br>      return request.auth != null &amp;&amp; request.auth.token.role == role;<br>    }<br><br>    match /adminData/{document=**} {<br>      // Yalnızca admin rolüne sahip kullanıcıların erişimine izin ver<br>      allow read, write: if hasRole(&#39;admin&#39;);<br>    }<br><br>    match /userData/{userId} {<br>      // Kendi verilerine erişim için doğrulama<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><p>Bu örnekte, hasRole işlevi kullanıcının belirli bir role sahip olup olmadığını kontrol eder. adminData koleksiyonuna yalnızca admin rolüne sahip kullanıcıların erişmesine izin verilirken, userData koleksiyonunda kullanıcıların yalnızca kendi verilerine erişmesine izin verilir.</p><h3>Fonksiyonlarla Veri Doğrulama</h3><p>Veri doğrulama işlemlerini işlevler ile yaparak kuralları daha modüler hale getirebilirsiniz. Örneğin, bir belgedeki tarih alanının geçerli bir tarih olup olmadığını kontrol eden bir işlev yazabiliriz:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Tarihin geçerli olup olmadığını kontrol eden işlev<br>    function isValidDate(date) {<br>      return date &gt; timestamp.date(2000, 1, 1) &amp;&amp; date &lt; timestamp.now();<br>    }<br><br>    match /events/{eventId} {<br>      // Etkinlik belgelerine erişim kontrolü<br>      allow create, update: if isValidDate(request.resource.data.eventDate);<br>      allow read: if true;  // Herkesin okumasına izin ver<br>    }<br>  }<br>}</pre><p>Bu örnekte, isValidDate işlevi bir tarihin 1 Ocak 2000&#39;den sonra ve şu anki tarihten önce olup olmadığını kontrol eder. events koleksiyonundaki belgelerin oluşturulması ve güncellenmesi sırasında bu işlev kullanılır.</p><h3>Güvenlik Kurallarının Test Edilmesi</h3><p>Güvenlik kurallarını test etmek, kuralların beklediğiniz gibi çalıştığından emin olmanın önemli bir parçasıdır. Firebase, güvenlik kurallarını test etmek için kullanabileceğiniz bir simülasyon aracı sağlar. Ayrıca, Firebase Emulator Suite kullanarak yerel ortamınızda kuralları test edebilirsiniz.</p><h3>Sonuç</h3><p>Firestore güvenlik kuralları, veritabanınıza erişimi kontrol etmek ve verilerin bütünlüğünü korumak için güçlü bir araçtır. Bu makalede, temel yapısını, erişim kontrolünü, koşullu erişimi ve veri doğrulamasını ele aldık. Güvenlik kurallarını doğru bir şekilde yapılandırmak, uygulamanızın güvenliğini ve kullanıcı verilerinin korunmasını sağlamak için kritik öneme sahiptir.</p><p>Güvenlik kurallarını yazarken ve test ederken dikkatli olmanız ve her zaman en iyi güvenlik uygulamalarını takip etmeniz önemlidir.</p><p><em>Not: Bu yazının yazılma aşamasında yapay zekadan destek alındı.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707b177db61b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Firestore Security Rules Effectively]]></title>
            <link>https://medium.com/@berkancnr/using-firestore-security-rules-effectively-2880a4d86e68?source=rss-fab1648686e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2880a4d86e68</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Berkan Çınar]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 20:36:16 GMT</pubDate>
            <atom:updated>2024-08-12T20:36:16.864Z</atom:updated>
            <content:encoded><![CDATA[<p>Firestore is a scalable and flexible database service offered by Google Cloud. To ensure secure and controlled data access, Firestore uses security rules. In this article, we will detail what Firestore security rules are, how they work, and how to configure them effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KKO_RjV_3mzIk780Oxm_A.jpeg" /></figure><h3>What are Firestore Security Rules?</h3><p>Firestore security rules are a set of rules that control access to your database and determine how data in the database can be read and written. These rules work in conjunction with Firebase Authentication to control access based on user identity. Additionally, you can add various conditions to ensure the accuracy and integrity of the data. By doing so, you can prevent your information from being altered or stolen due to external interference.</p><h3>Basic Structure of Security Rules</h3><p>Firestore security rules are defined in a file named firestore.rules. This file typically has a structure like the following:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /{document=**} {<br>      allow read, write: if false;<br>    }<br>  }<br>}</pre><p>This structure is created using the service, match, and allow keywords.</p><ul><li>service: Specifies the Firebase service for which the rules are written (cloud.firestore).</li><li>match: Specifies the data paths for which the rules apply.</li><li>allow: Specifies which operations (read, write, etc.) are allowed.</li></ul><h3>Access Control</h3><p>To control access using Firestore security rules, we use the allow keyword. For example, to allow only authenticated users to access a collection, we can write a rule like this:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null;<br>    }<br>  }<br>}</pre><p>This rule specifies that only authenticated users can access documents in the users collection. In real-world applications, we often need more detailed workflows, so a simple rule set like the one above may not fully meet our needs. In such cases, we need to define conditional accesses.</p><h3>Conditional Access</h3><p>Firestore security rules allow us to define more detailed conditions for access control. For example, to ensure that a user can only access their own data, we can write a rule like this:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><p>This rule allows authenticated users to access only their documents that match their userId. In some cases, we might want to check fields within the document we want to write. Suppose you are developing an e-commerce application and you want to ensure that the price of a product being uploaded is not zero or negative. You can use data validation to enforce this requirement.</p><h3>Data Validation</h3><p>Firestore security rules can also be used to ensure data accuracy. For example, we can require that a specific field in a document meets a certain condition:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /products/{productId} {<br>      allow create: if request.resource.data.price &gt; 0;<br>      allow update: if request.resource.data.price &gt; 0;<br>    }<br>  }<br>}</pre><p>This rule requires that the price field in documents in the products collection must always be greater than zero. For much more detailed and complex operations, we can define functions within the rules. We can control multiple or dependent conditions with a single function.</p><h3>Defining Basic Functions</h3><p>We use the function keyword to define a function. A function can take one or more parameters and return a value.</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    <br>    // Define a function that verifies user identity<br>    function isAuthenticated() {<br>      return request.auth != null;<br>    }<br><br>    // Define a function that verifies user access to their document<br>    function isUserDocument(userId) {<br>      return request.auth.uid == userId;<br>    }<br><br>    match /users/{userId} {<br>      // Use functions for access control<br>      allow read, write: if isAuthenticated() &amp;&amp; isUserDocument(userId);<br>    }<br>  }<br>}</pre><p>In this example, the isAuthenticated function checks whether the user is authenticated, while the isUserDocument function checks whether the user can access only their document.</p><h3>Functions for Complex Logic</h3><p>For situations requiring more complex logic, you can use functions to make the rules more manageable. For example, we can write a function that checks whether a user is the owner of a document and whether certain fields in the document have valid values:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Function to check if the user is the owner of the document<br>    function isOwner(doc) {<br>      return request.auth != null &amp;&amp; request.auth.uid == doc.data.ownerId;<br>    }<br><br>    // Function to check if the price in the document is valid<br>    function isValidPrice(price) {<br>      return price &gt; 0;<br>    }<br><br>    match /products/{productId} {<br>      // Access control for product documents<br>      allow create, update: if isOwner(request.resource) &amp;&amp; isValidPrice(request.resource.data.price);<br>      allow read: if true;  // Allow everyone to read<br>    }<br>  }<br>}</pre><p>In this example, the isOwner function verifies the owner of a document, while the isValidPrice function checks if the price is a positive value. These functions are used to control access to documents in the products collection.</p><h3>Conditional Access with Functions</h3><p>You can use functions to control access based on specific conditions. For example, we can write a function to allow certain operations only if a user has a specific role:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Function to check if the user has a specific role<br>    function hasRole(role) {<br>      return request.auth != null &amp;&amp; request.auth.token.role == role;<br>    }<br><br>    match /adminData/{document=**} {<br>      // Allow only users with the admin role to access<br>      allow read, write: if hasRole(&#39;admin&#39;);<br>    }<br><br>    match /userData/{userId} {<br>      // Verification for access to own data<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><p>In this example, the hasRole function checks if a user has a specific role. Access to the adminData collection is granted only to users with the admin role, while users are allowed to access only their data in the userData collection.</p><h3>Data Validation with Functions</h3><p>By using functions for data validation, you can make your rules more modular. For example, we can write a function to check if a date field in a document is a valid date:</p><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br><br>    // Function to check if the date is valid<br>    function isValidDate(date) {<br>      return date &gt; timestamp.date(2000, 1, 1) &amp;&amp; date &lt; timestamp.now();<br>    }<br><br>    match /events/{eventId} {<br>      // Access control for event documents<br>      allow create, update: if isValidDate(request.resource.data.eventDate);<br>      allow read: if true;  // Allow everyone to read<br>    }<br>  }<br>}</pre><p>In this example, the isValidDate function checks if a date is after January 1, 2000, and before the current date. This function is used when creating and updating documents in the events collection.</p><h3>Testing Security Rules</h3><p>Testing security rules is an important part of ensuring that they work as expected. Firebase provides a simulator tool to test security rules. Additionally, you can use the Firebase Emulator Suite to test rules in your local environment.</p><h3>Conclusion</h3><p>Firestore security rules are a powerful tool for controlling access to your database and ensuring data integrity. In this article, we covered their basic structure, access control, conditional access, and data validation. Configuring security rules correctly is critical to ensuring the security of your application and the protection of user data.</p><p>It is important to be careful when writing and testing security rules and always follow best security practices.</p><p><em>Note: This text was written with the assistance of artificial intelligence.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2880a4d86e68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social Media Applications with Firebase: Managing Follow, Unfollow and Feeds]]></title>
            <link>https://medium.com/@berkancnr/social-media-applications-with-firebase-managing-follow-unfollow-and-feeds-2c492fc7f890?source=rss-fab1648686e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c492fc7f890</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Berkan Çınar]]></dc:creator>
            <pubDate>Thu, 16 May 2024 21:38:42 GMT</pubDate>
            <atom:updated>2024-05-17T07:38:21.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Firebase is a popular platform for managing real-time data and authentication in mobile and web applications. In this article, we will detail how to manage follow and unfollow operations using Firebase Realtime Database and Firestore. Additionally, we will show you how to optimize these operations using Firebase Cloud Functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YhbYtXwIr9452AX9UkxlQ.jpeg" /></figure><h3>Introduction</h3><p>Following and unfollowing operations are commonly used features in social media applications. By following other users, individuals gain the ability to view their posts. These types of complex operations require specific database requests. Firestore and Realtime Database alone may not be sufficient for these tasks. To manage these operations efficiently and securely, we will use the tools provided by Firebase and create a complementary workflow.</p><h3>Requirements</h3><p>To follow this guide, make sure you have the following tools installed:</p><ul><li>Firebase CLI</li><li>Node.js</li><li>Flutter (optional)</li><li>Firebase SDK for Flutter</li></ul><h3>Step 1: Setting Up Your Firebase Project</h3><p>First, create a Firebase project and configure the necessary settings:</p><ol><li>Go to the Firebase Console and create a new project.</li><li>Enable Firebase Authentication.</li><li>Add Firestore and Realtime Database to your project.</li><li>Connect your Flutter app to Firebase.</li></ol><h3>Step 2: Structuring Your Database</h3><p>The structure of our database will be as follows:</p><h3>Firestore</h3><ul><li>users collection:</li><li>followingCount: The number of users a user is following.</li><li>followerCount: The number of followers a user has.</li></ul><h3>Realtime Database</h3><ul><li>users:</li><li>{userId}/following/{targetUserId}</li><li>{userId}/followers/{targetUserId}</li><li>posts:</li><li>{postId}: Post information.</li><li>userFlows:</li><li>{userId}/{postId}: Posts the user is following.</li></ul><h3>Step 3: Firestore and Realtime Database Security Rules</h3><p>Database security is crucial to ensure that only authorized users can access and modify the data. Add the following security rules:</p><h3>Firestore Rules</h3><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><h3>Realtime Database Rules</h3><pre>{<br>  &quot;rules&quot;: {<br>    &quot;users&quot;: {<br>      &quot;$userId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;following&quot;: {<br>          &quot;$targetUserId&quot;: {<br>            &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;<br>          }<br>        },<br>        &quot;followers&quot;: {<br>          &quot;$followerId&quot;: {<br>            &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $followerId&quot;<br>          }<br>        }<br>      }<br>    },<br>    &quot;posts&quot;: {<br>      &quot;$postId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; data.child(&#39;authorId&#39;).val() == auth.uid&quot;<br>      }<br>    },<br>    &quot;userFlows&quot;: {<br>      &quot;$userId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;<br>      }<br>    }<br>  }<br>}</pre><h3>Step 4: Using Firebase Cloud Functions for Follow and Unfollow</h3><p>Cloud Functions are ideal for performing complex operations on the server side from the client side. Below, we will show you how to implement follow and unfollow operations using Cloud Functions.</p><h3>index.js File</h3><pre>const functions = require(&#39;firebase-functions&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br><br>admin.initializeApp();<br><br>const firestore = admin.firestore();<br>const realtimeDatabase = admin.database();<br><br>exports.followUser = functions.https.onCall(async (data, context) =&gt; {<br>    const userId = data.userId;<br>    const targetUserId = data.targetUserId;<br><br>    if (!context.auth) {<br>        throw new functions.https.HttpsError(&#39;failed-precondition&#39;, &#39;The function must be called while authenticated.&#39;);<br>    }<br><br>    try {<br>        await firestore.runTransaction(async (transaction) =&gt; {<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(userId), {<br>                followingCount: admin.firestore.FieldValue.increment(1)<br>            });<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(targetUserId), {<br>                followerCount: admin.firestore.FieldValue.increment(1)<br>            });<br>        });<br><br>        const followUpdates = {};<br>        followUpdates[`users/${userId}/following/${targetUserId}`] = admin.database.ServerValue.TIMESTAMP;<br>        followUpdates[`users/${targetUserId}/followers/${userId}`] = admin.database.ServerValue.TIMESTAMP;<br><br>        await realtimeDatabase.ref().update(followUpdates);<br><br>        const flowUpdates = {};<br><br>        const userPostsSnapshot = await realtimeDatabase.ref(&#39;posts&#39;).orderByChild(&#39;authorId&#39;).equalTo(targetUserId).once(&#39;value&#39;);<br>        const userPosts = userPostsSnapshot.val();<br><br>        if (userPosts) {<br>            Object.keys(userPosts).forEach((postId) =&gt; {<br>                flowUpdates[`userFlows/${userId}/${postId}`] = admin.database.ServerValue.TIMESTAMP;<br>            });<br><br>            await realtimeDatabase.ref().update(flowUpdates);<br>        }<br><br>        return { isSuccess: true };<br>    } catch (e) {<br>        console.error(e);<br>        return { isSuccess: false };<br>    }<br>});<br><br>exports.unfollowUser = functions.https.onCall(async (data, context) =&gt; {<br>    const userId = data.userId;<br>    const targetUserId = data.targetUserId;<br><br>    if (!context.auth) {<br>        throw new functions.https.HttpsError(&#39;failed-precondition&#39;, &#39;The function must be called while authenticated.&#39;);<br>    }<br><br>    try {<br>        await firestore.runTransaction(async (transaction) =&gt; {<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(userId), {<br>                followingCount: admin.firestore.FieldValue.increment(-1)<br>            });<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(targetUserId), {<br>                followerCount: admin.firestore.FieldValue.increment(-1)<br>            });<br>        });<br><br>        const unfollowUpdates = {};<br>        unfollowUpdates[`users/${userId}/following/${targetUserId}`] = null;<br>        unfollowUpdates[`users/${targetUserId}/followers/${userId}`] = null;<br><br>        await realtimeDatabase.ref().update(unfollowUpdates);<br><br>        const flowUpdates = {};<br><br>        const userPostsSnapshot = await realtimeDatabase.ref(&#39;posts&#39;).orderByChild(&#39;authorId&#39;).equalTo(targetUserId).once(&#39;value&#39;);<br>        const userPosts = userPostsSnapshot.val();<br><br>        if (userPosts) {<br>            Object.keys(userPosts).forEach((postId) =&gt; {<br>                flowUpdates[`userFlows/${userId}/${postId}`] = null;<br>            });<br><br>            await realtimeDatabase.ref().update(flowUpdates);<br>        }<br><br>        return { isSuccess: true };<br>    } catch (e) {<br>        console.error(e);<br>        return { isSuccess: false };<br>    }<br>});</pre><h3>Deploying Functions</h3><p>To deploy these functions to Firebase, follow these steps:</p><ol><li>Install Firebase CLI and log in:</li></ol><pre>npm install -g firebase-tools<br>firebase login</pre><p>2. Initialize your Firebase project:</p><pre>firebase init functions</pre><p>3. Update your index.js file with the above code.</p><p>4. Deploy the functions:</p><pre>firebase deploy --only functions</pre><h3>Step 5: Flutter Client Code</h3><p>Finally, here’s an example of how to call these functions from your Flutter client:</p><pre>import &#39;package:cloud_functions/cloud_functions.dart&#39;;<br><br>Future&lt;void&gt; followUser(String userId, String targetUserId) async {<br>  HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(&#39;followUser&#39;);<br>  final results = await callable.call(&lt;String, dynamic&gt;{<br>    &#39;userId&#39;: userId,<br>    &#39;targetUserId&#39;: targetUserId,<br>  });<br><br>  if (results.data[&#39;isSuccess&#39;]) {<br>    print(&#39;Follow successful&#39;);<br>  } else {<br>    print(&#39;Follow failed&#39;);<br>  }<br>}<br><br>Future&lt;void&gt; unfollowUser(String userId, String targetUserId) async {<br>  HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(&#39;unfollowUser&#39;);<br>  final results = await callable.call(&lt;String, dynamic&gt;{<br>    &#39;userId&#39;: userId,<br>    &#39;targetUserId&#39;: targetUserId,<br>  });<br><br>  if (results.data[&#39;isSuccess&#39;]) {<br>    print(&#39;Unfollow successful&#39;);<br>  } else {<br>    print(&#39;Unfollow failed&#39;);<br>  }<br>}</pre><h3>Conclusion</h3><p>In this article, you learned how to manage follow and unfollow operations using Firebase Realtime Database and Firestore. You also saw how to optimize these operations using Firebase Cloud Functions. These methods allow you to efficiently and securely manage user interactions in your mobile and web applications.</p><p>By using the tools provided by Firebase, you can improve user experience and increase performance in your social media applications. We hope this guide helps you in your projects. Good luck!</p><p><em>Note: This text was written with the assistance of artificial intelligence.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c492fc7f890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase ile Sosyal Medya Uygulamaları: Takip, Takipten Çıkarma ve Akış Yönetimi]]></title>
            <link>https://medium.com/@berkancnr/firebase-ile-sosyal-medya-uygulamalar%C4%B1-takip-takipten-%C3%A7%C4%B1karma-ve-ak%C4%B1%C5%9F-y%C3%B6netimi-cd2d4c6e56eb?source=rss-fab1648686e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2d4c6e56eb</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Berkan Çınar]]></dc:creator>
            <pubDate>Thu, 16 May 2024 21:38:11 GMT</pubDate>
            <atom:updated>2024-05-17T07:36:50.583Z</atom:updated>
            <content:encoded><![CDATA[<p>Firebase, mobil ve web uygulamalarında gerçek zamanlı veri yönetimi ve kimlik doğrulama işlemleri için popüler bir platformdur. Bu makalede, Firebase Realtime Database ve Firestore kullanarak takip ve takipten çıkarma işlemlerini nasıl yönetebileceğinizi detaylı bir şekilde anlatacağız. Ayrıca, bu işlemleri Firebase Cloud Functions kullanarak nasıl optimize edeceğinizi de göstereceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnQubEl-gmD2C5rtdStiMQ.jpeg" /></figure><h3>Giriş</h3><p>Takip ve takipten çıkarma işlemleri, sosyal medya uygulamalarında yaygın olarak kullanılan özelliklerdir. Kullanıcılar, diğer kullanıcıları takip ederek onların gönderilerini görme yetkisine sahip olurlar. Bu tip karmaşık işlemler spesifik veritabanı isteklerine ihtiyaç duyarlar. Firestore ve Realtime Database bu işlemler için tek başına yeterli olamayabiliyor. Bu işlemleri verimli ve güvenli bir şekilde yönetmek için Firebase’in sağladığı araçları kullanacağız ve birbirini tamamlayan bir iş akışı sağlayacağız.</p><h3>Gereksinimler</h3><p>Bu rehberi takip edebilmek için aşağıdaki araçların kurulu olduğundan emin olun:</p><ul><li>Firebase CLI</li><li>Node.js</li><li>Flutter (isteğe bağlı)</li><li>Firebase SDK for Flutter</li></ul><h3>Adım 1: Firebase Projesi Kurulumu</h3><p>Öncelikle, Firebase projesini oluşturun ve gerekli konfigürasyonları yapın:</p><ol><li>Firebase Console’a gidin ve yeni bir proje oluşturun.</li><li>Firebase Authentication’ı etkinleştirin.</li><li>Firestore ve Realtime Database’i ekleyin.</li><li>Flutter uygulamanızı Firebase’e bağlayın.</li></ol><h3>Adım 2: Veritabanı Yapısını Oluşturma</h3><p>Veritabanı yapımız şu şekilde olacak:</p><h3>Firestore</h3><ul><li>users koleksiyonu:</li><li>followingCount: Kullanıcının takip ettiği kişi sayısı.</li><li>followerCount: Kullanıcının takipçi sayısı.</li></ul><h3>Realtime Database</h3><ul><li>users :</li><li>{userId}/following/{targetUserId}</li><li>{userId}/followers/{targetUserId}</li><li>posts :</li><li>{postId}: Post bilgileri.</li><li>userFlows :</li><li>{userId}/{postId}: Kullanıcının takip ettiği postlar.</li></ul><h3>Adım 3: Firestore ve Realtime Database Güvenlik Kuralları</h3><p>Veritabanı güvenliği, sadece yetkili kullanıcıların verilere erişimini sağlamak için önemlidir. Aşağıdaki güvenlik kurallarını ekleyin:</p><h3>Firestore Kuralları</h3><pre>service cloud.firestore {<br>  match /databases/{database}/documents {<br>    match /users/{userId} {<br>      allow read, write: if request.auth != null &amp;&amp; request.auth.uid == userId;<br>    }<br>  }<br>}</pre><h3>Realtime Database Kuralları</h3><pre>{<br>  &quot;rules&quot;: {<br>    &quot;users&quot;: {<br>      &quot;$userId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;following&quot;: {<br>          &quot;$targetUserId&quot;: {<br>            &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;<br>          }<br>        },<br>        &quot;followers&quot;: {<br>          &quot;$followerId&quot;: {<br>            &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $followerId&quot;<br>          }<br>        }<br>      }<br>    },<br>    &quot;posts&quot;: {<br>      &quot;$postId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; data.child(&#39;authorId&#39;).val() == auth.uid&quot;<br>      }<br>    },<br>    &quot;userFlows&quot;: {<br>      &quot;$userId&quot;: {<br>        &quot;.read&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;,<br>        &quot;.write&quot;: &quot;auth != null &amp;&amp; auth.uid == $userId&quot;<br>      }<br>    }<br>  }<br>}</pre><h3>Adım 4: Firebase Cloud Functions ile Takip ve Takipten Çıkarma</h3><p>Cloud Functions, istemci tarafındaki karmaşık işlemleri sunucu tarafında gerçekleştirmek için idealdir. Aşağıda, takip ve takipten çıkarma işlemlerini Cloud Functions kullanarak nasıl yapacağınızı göstereceğiz.</p><h3>index.js Dosyası</h3><pre>const functions = require(&#39;firebase-functions&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br><br>admin.initializeApp();<br><br>const firestore = admin.firestore();<br>const realtimeDatabase = admin.database();<br><br>exports.followUser = functions.https.onCall(async (data, context) =&gt; {<br>    const userId = data.userId;<br>    const targetUserId = data.targetUserId;<br><br>    if (!context.auth) {<br>        throw new functions.https.HttpsError(&#39;failed-precondition&#39;, &#39;The function must be called while authenticated.&#39;);<br>    }<br><br>    try {<br>        await firestore.runTransaction(async (transaction) =&gt; {<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(userId), {<br>                followingCount: admin.firestore.FieldValue.increment(1)<br>            });<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(targetUserId), {<br>                followerCount: admin.firestore.FieldValue.increment(1)<br>            });<br>        });<br><br>        const followUpdates = {};<br>        followUpdates[`users/${userId}/following/${targetUserId}`] = admin.database.ServerValue.TIMESTAMP;<br>        followUpdates[`users/${targetUserId}/followers/${userId}`] = admin.database.ServerValue.TIMESTAMP;<br><br>        await realtimeDatabase.ref().update(followUpdates);<br><br>        const flowUpdates = {};<br><br>        const userPostsSnapshot = await realtimeDatabase.ref(&#39;posts&#39;).orderByChild(&#39;authorId&#39;).equalTo(targetUserId).once(&#39;value&#39;);<br>        const userPosts = userPostsSnapshot.val();<br><br>        if (userPosts) {<br>            Object.keys(userPosts).forEach((postId) =&gt; {<br>                flowUpdates[`userFlows/${userId}/${postId}`] = admin.database.ServerValue.TIMESTAMP;<br>            });<br><br>            await realtimeDatabase.ref().update(flowUpdates);<br>        }<br><br>        return { isSuccess: true };<br>    } catch (e) {<br>        console.error(e);<br>        return { isSuccess: false };<br>    }<br>});<br><br>exports.unfollowUser = functions.https.onCall(async (data, context) =&gt; {<br>    const userId = data.userId;<br>    const targetUserId = data.targetUserId;<br><br>    if (!context.auth) {<br>        throw new functions.https.HttpsError(&#39;failed-precondition&#39;, &#39;The function must be called while authenticated.&#39;);<br>    }<br><br>    try {<br>        await firestore.runTransaction(async (transaction) =&gt; {<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(userId), {<br>                followingCount: admin.firestore.FieldValue.increment(-1)<br>            });<br>            transaction.update(firestore.collection(&#39;users&#39;).doc(targetUserId), {<br>                followerCount: admin.firestore.FieldValue.increment(-1)<br>            });<br>        });<br><br>        const unfollowUpdates = {};<br>        unfollowUpdates[`users/${userId}/following/${targetUserId}`] = null;<br>        unfollowUpdates[`users/${targetUserId}/followers/${userId}`] = null;<br><br>        await realtimeDatabase.ref().update(unfollowUpdates);<br><br>        const flowUpdates = {};<br><br>        const userPostsSnapshot = await realtimeDatabase.ref(&#39;posts&#39;).orderByChild(&#39;authorId&#39;).equalTo(targetUserId).once(&#39;value&#39;);<br>        const userPosts = userPostsSnapshot.val();<br><br>        if (userPosts) {<br>            Object.keys(userPosts).forEach((postId) =&gt; {<br>                flowUpdates[`userFlows/${userId}/${postId}`] = null;<br>            });<br><br>            await realtimeDatabase.ref().update(flowUpdates);<br>        }<br><br>        return { isSuccess: true };<br>    } catch (e) {<br>        console.error(e);<br>        return { isSuccess: false };<br>    }<br>});</pre><h3>Fonksiyonları Deploy Etme</h3><p>Bu fonksiyonları Firebase’e deploy etmek için şu adımları izleyin:</p><ol><li>Firebase CLI’yi yükleyin ve giriş yapın:</li></ol><pre>npm install -g firebase-tools<br>firebase login</pre><p>2. Projenizi Firebase’e başlatın:</p><pre>firebase init functions</pre><p>3. index.js dosyanızı güncelleyin ve yukarıdaki kodu ekleyin.</p><p>4. Fonksiyonları deploy edin:</p><pre>firebase deploy --only functions</pre><h3>Adım 5: Flutter İstemci Kodu</h3><p>Son olarak, Flutter istemcinizde bu fonksiyonları nasıl çağıracağınızı gösteren bir örnek:</p><pre>import &#39;package:cloud_functions/cloud_functions.dart&#39;;<br><br>Future&lt;void&gt; followUser(String userId, String targetUserId) async {<br>  HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(&#39;followUser&#39;);<br>  final results = await callable.call(&lt;String, dynamic&gt;{<br>    &#39;userId&#39;: userId,<br>    &#39;targetUserId&#39;: targetUserId,<br>  });<br><br>  if (results.data[&#39;isSuccess&#39;]) {<br>    print(&#39;Follow successful&#39;);<br>  } else {<br>    print(&#39;Follow failed&#39;);<br>  }<br>}<br><br>Future&lt;void&gt; unfollowUser(String userId, String targetUserId) async {<br>  HttpsCallable callable = FirebaseFunctions.instance.httpsCallable(&#39;unfollowUser&#39;);<br>  final results = await callable.call(&lt;String, dynamic&gt;{<br>    &#39;userId&#39;: userId,<br>    &#39;targetUserId&#39;: targetUserId,<br>  });<br><br>  if (results.data[&#39;isSuccess&#39;]) {<br>    print(&#39;Unfollow successful&#39;);<br>  } else {<br>    print(&#39;Unfollow failed&#39;);<br>  }<br>}</pre><h3>Sonuç</h3><p>Bu makalede, Firebase Realtime Database ve Firestore kullanarak takip ve takipten çıkarma işlemlerini nasıl yöneteceğinizi öğrendiniz. Ayrıca, Firebase Cloud Functions kullanarak bu işlemleri nasıl optimize edeceğinizi gördünüz. Bu yöntemler, mobil ve web uygulamalarınızda kullanıcı etkileşimlerini verimli ve güvenli bir şekilde yönetmenizi sağlar.</p><p>Firebase’in sunduğu araçları kullanarak, sosyal medya uygulamalarınızda kullanıcı deneyimini iyileştirebilir ve performansı artırabilirsiniz. Umarız bu rehber, projelerinizde size yardımcı olur. Başarılar!</p><p><em>Not: Bu yazının yazılma aşamasında yapay zekadan destek alındı.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2d4c6e56eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>