<?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 Mohammed S. Yaghi on Medium]]></title>
        <description><![CDATA[Stories by Mohammed S. Yaghi on Medium]]></description>
        <link>https://medium.com/@yaghi.moh?source=rss-a266562c7805------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zBXSRqI327tZvGyAUbAGmw.jpeg</url>
            <title>Stories by Mohammed S. Yaghi on Medium</title>
            <link>https://medium.com/@yaghi.moh?source=rss-a266562c7805------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:20:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yaghi.moh/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[Part #1 : How about “Mastering GitHub Integration: A Comprehensive Guide to Syncing Your VS Code…]]></title>
            <link>https://medium.com/@yaghi.moh/how-about-mastering-github-integration-a-comprehensive-guide-to-syncing-your-vs-code-project-with-fe4b1170dc4e?source=rss-a266562c7805------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4b1170dc4e</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Mohammed S. Yaghi]]></dc:creator>
            <pubDate>Fri, 05 May 2023 15:19:23 GMT</pubDate>
            <atom:updated>2023-05-05T15:53:10.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part #1 : How about “Mastering GitHub Integration: A Comprehensive Guide to Syncing Your VS Code Project with GitHub”?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*4tp_HFf4fn9RaJxx.png" /></figure><p><strong>How To set it up?</strong></p><ol><li>Install Git: If you don’t have Git installed on your system, download and install it from <a href="https://git-scm.com/downloads">https://git-scm.com/downloads</a>.</li><li>Create a GitHub account: If you don’t have a GitHub account, sign up at <a href="https://github.com/">https://github.com</a>.</li><li>Create a new repository on GitHub: Log in to your GitHub account, click the “+” icon in the top-right corner, and select “New repository.” Choose a name for your repository, add a description (optional), and decide whether you want it to be public or private. You can also initialize the repository with a README, but if you’re adding an existing project, leave this option unchecked. Click “Create repository” to proceed.</li><li>Open your project in VS Code: Launch Visual Studio Code and open the project folder you want to add to GitHub by clicking on “File” &gt; “Open Folder.”</li><li>Initialize a Git repository: Open the terminal in VS Code by clicking on “Terminal” &gt; “New Terminal.” In the terminal, navigate to your project folder (if not already there) and run the following command:</li></ol><pre>git init</pre><p>This command initializes a new Git repository in your project folder.</p><p>6. Configure your Git user information (if not done previously):</p><pre>git config --global user.name &quot;Your Name&quot;<br>git config --global user.email &quot;your.email@example.com&quot;</pre><p><strong>How to Stage and commit your changes?</strong></p><ol><li>Stage and commit your changes: To stage all changes in the project, run:</li></ol><pre>git add .</pre><p>Then, commit the changes with a message:</p><pre>git commit -m &quot;Initial commit&quot;</pre><p>2. Add the remote repository: To link your local Git repository to the GitHub repository you created earlier, run:</p><pre>git remote add origin https://github.com/your-username/your-repository-name.git</pre><pre>git remote add origin https://github.com/your-username/your-repository-name.git</pre><p>Replace “your-username” and “your-repository-name” with your GitHub username and the name of the repository you created in step 3.</p><p>3. Push your changes to GitHub: To push your changes to the remote repository, run:</p><pre>git push -u origin master</pre><p>If prompted, enter your GitHub username and password (or personal access token for two-factor authentication).</p><p>4. Verify the changes on GitHub: Visit your repository on GitHub to confirm that your project files have been successfully pushed.</p><p>Now your project has been added to GitHub from VS Code. You can use the Git integration in VS Code to stage, commit, and push changes to your repository directly from the editor.</p><p>Please keep in touch. I will update this article weekly to cover all GitHub commands.</p><p>Thanks :)</p><p>Mohammed Sallah Yaghi</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4b1170dc4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Separating the business logic and user interface (UI)]]></title>
            <link>https://medium.com/@yaghi.moh/separating-the-business-logic-and-user-interface-ui-223c841bbfed?source=rss-a266562c7805------2</link>
            <guid isPermaLink="false">https://medium.com/p/223c841bbfed</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Mohammed S. Yaghi]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 15:01:29 GMT</pubDate>
            <atom:updated>2023-04-27T08:14:58.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*EiurP4mfd4hKNkBC" /></figure><p><strong>Introduction</strong></p><p>In software development, separating the business logic and user interface (UI) is a common practice. This separation of concerns has several benefits, including improved maintainability, reusability, scalability, and testing.</p><p><strong>1.Maintainability</strong></p><p>When the business logic and UI are separated, changes to one component will not affect the other. This means that if you need to update the business logic, you can do so without having to modify the UI. Similarly, if you need to update the UI, you can do so without having to change the business logic. This makes it easier to maintain and update the application over time.</p><p>For example, let’s say you have a web application that allows users to purchase products. The business logic handles the payment processing, while the UI displays the product catalog and checkout form. If you need to update the payment processing to use a new payment gateway, you can make that change in the business logic without having to modify the UI<strong>. This can save time and reduce the risk of introducing bugs into the application.</strong></p><p>One example of the benefits of separating business logic and UI for maintainability can be seen in a complex e-commerce website. Let’s say the website has a complex system for handling shipping and returns. The business logic for this system is separated from the UI, which displays the product information, shopping cart, and checkout process.</p><p>If the website needs to update its shipping and returns policy, the developers can simply update the business logic without having to modify the UI. <strong>This means that customers can continue to use the website as usual while the updates are being made</strong>. This can save time and reduce the risk of introducing bugs or errors into the website.</p><p><strong>2.Reusability</strong></p><p>Separating the business logic and UI allows you to reuse the business logic in multiple applications or UIs. For example, you can use the same business logic for a web application and a mobile application. This can save time and reduce development costs.</p><p><strong>By separating the business logic and UI, you can also create different UIs for different platforms</strong> <strong>without having to modify the business logic</strong>. For example, you can create a web UI and a mobile UI that both use the same business logic. This can make it easier to target different audiences and expand your user base.</p><p>An example of reusability can be seen in a mobile application that uses the same business logic for both iOS and Android versions. The business logic handles the core functionality of the application, such as user authentication, data retrieval, and data manipulation.</p><p>The UI layer for each platform is separate, which allows the developers to use platform-specific UI components and design patterns. However, the business logic is the same for both platforms, which saves time and reduces development costs.</p><p><strong>3.Scalability</strong></p><p>Separating the business logic and UI can make it easier to scale the application. You can scale the UI layer separately from the business logic layer, which allows you to handle more users and traffic without affecting the performance of the application.</p><p>For example, if you have a web application that is experiencing increased traffic, you can add more servers to handle the increased load. This can help you avoid performance issues and downtime. <strong>Similarly, if you have a mobile application that is experiencing increased usage, you can scale the UI layer without having to modify the business logic.</strong></p><p><strong>An example of scalability can be seen in a web application that uses a microservices architecture</strong>. The application is composed of several microservices, each of which handles a specific business function. The microservices are connected to a UI layer, which displays the data and functionality to the user.</p><p>When the application experiences increased traffic, the developers can scale the UI layer separately from the microservices. This means that they can add more servers to handle the increased load on the UI layer, while leaving the microservices unchanged. This can help the application maintain its performance and avoid downtime.</p><p><strong>4.Testing</strong></p><p>Separating the business logic and UI makes it easier to test each component separately. You can test the business logic without having to worry about the UI, and you can test the UI without having to worry about the business logic. This can improve the quality of the application and reduce the risk of bugs and errors.</p><p>For example, you can write automated tests for the business logic layer that simulate various scenarios, such as successful payments, failed payments, and refunds. Similarly, you can write automated tests for the UI layer that simulate user interactions, such as adding items to a cart and checking out. By testing each component separately, you can catch bugs and errors before they reach production.</p><p>An example of testing can be seen in an online banking application. The business logic handles the user authentication, account information, and transaction processing. The UI layer displays the account information, transaction history, and transfer forms.</p><p>When the developers need to test the application, they can write automated tests for the business logic layer that simulate various scenarios, such as successful logins, failed logins, account balance queries, and transfer requests. They can also write automated tests for the UI layer that simulate user interactions, such as clicking on links, entering text into forms, and submitting forms.</p><p>By testing each component separately, the developers can catch bugs and errors before they reach production, which can improve the quality of the application and reduce the risk of data breaches or other security issues.</p><p><strong>While separating business logic and UI has many advantages, there are also some potential disadvantages that should be considered:</strong></p><p><strong>1.Increased complexity</strong></p><p>Separating business logic and UI can increase the overall complexity of the system. Developers must design and implement communication channels between the business logic and UI layers, which adds additional complexity and potential points of failure. Additionally, developers may need to learn and work with new frameworks or libraries for each layer, which can be time-consuming.</p><p><strong>2.Tight coupling</strong></p><p>Despite separating business logic and UI, there may be cases where they need to be tightly coupled. For example, if the UI layer needs to display real-time data or notifications, it may need to frequently interact with the business logic layer. In these cases, tightly coupling the layers can make the system more efficient, but also more difficult to maintain.</p><p><strong>3.Performance issues</strong></p><p>Separating business logic and UI can potentially cause performance issues. For example, if the business logic layer needs to retrieve large amounts of data for the UI layer to display, it may slow down the UI layer’s response time. Similarly, if the UI layer needs to frequently query the business logic layer for data, it may add latency and affect the overall performance of the system.</p><p><strong>4.Increased development time and cost</strong></p><p>Separating business logic and UI can increase development time and cost. Developers must spend additional time designing and implementing communication channels between the layers, testing each layer separately, and maintaining multiple codebases. This can increase development costs, especially for small or medium-sized projects.</p><p><strong>In summary, </strong>while separating business logic and UI has many benefits, it may also introduce complexity, tight coupling, performance issues, and increased development time and cost. Developers should carefully consider these potential disadvantages before deciding to separate the layers in their project.</p><p>Thanks :)</p><p><a href="https://bio.link/yaghi_moh">bio.link/yaghi_moh</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223c841bbfed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fortifying Your Laravel Application: Best Practices for Securing Your Web Application]]></title>
            <link>https://medium.com/@yaghi.moh/fortifying-your-laravel-application-best-practices-for-securing-your-web-application-b6d4242d0bb8?source=rss-a266562c7805------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d4242d0bb8</guid>
            <dc:creator><![CDATA[Mohammed S. Yaghi]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 19:09:01 GMT</pubDate>
            <atom:updated>2023-04-22T19:13:01.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*BBE-0hfNqgG87Ipq.jpg" /></figure><p><strong>Use Strong Passwords:</strong></p><p>In Laravel, user passwords are usually stored in a hashed format in the database. Laravel includes the bcrypt algorithm for hashing passwords, which is a one-way encryption algorithm that is considered to be very secure. To use bcrypt in your application, you can use the Hash::make method, like this:</p><pre>$password = &#39;mysecurepassword&#39;;<br>$hashedPassword = Hash::make($password);</pre><p>To ensure that users are using strong passwords, you can implement password complexity rules and enforce them when users create or update their passwords. You can use the Validator class to define password validation rules, like this:</p><pre>$validator = Validator::make($request-&gt;all(), [<br>    &#39;password&#39; =&gt; [<br>        &#39;required&#39;,<br>        &#39;string&#39;,<br>        &#39;min:8&#39;,<br>        &#39;regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/&#39;,<br>        &#39;confirmed&#39;<br>    ],<br>]);</pre><p>This validator enforces the following rules for passwords:</p><p>· The password field is required</p><p>· The password must be a string</p><p>· The password must be at least 8 characters long</p><p>· The password must contain at least one lowercase letter, one uppercase letter, and one number</p><p>· The password must be confirmed (i.e. the user must enter the same password twice)</p><p><strong>Implement Two-Factor Authentication:</strong></p><p>Laravel provides built-in support for two-factor authentication using Time-Based One-Time Passwords (TOTP). To enable two-factor authentication in your application, you can use the laravel/ui package to generate the necessary views and controllers, and then configure the config/auth.php file to use the totp driver for authentication.</p><p>Here are the steps to enable two-factor authentication in your Laravel application:</p><ol><li>Install the laravel/ui package:</li></ol><pre>composer require laravel/ui</pre><p>2. Generate the two-factor authentication views and controllers:</p><pre>php artisan ui:controllers --auth<br>php artisan ui:views auth</pre><p>3. Configure the config/auth.php file to use the totp driver:</p><pre>&#39;guards&#39; =&gt; [<br>    &#39;web&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;session&#39;,<br>        &#39;provider&#39; =&gt; &#39;users&#39;,<br>    ],<br><br>    &#39;api&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;token&#39;,<br>        &#39;provider&#39; =&gt; &#39;users&#39;,<br>        &#39;hash&#39; =&gt; false,<br>    ],<br><br>    &#39;totp&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;totp&#39;,<br>        &#39;provider&#39; =&gt; &#39;users&#39;,<br>    ],<br>],</pre><p>4. Update the User model to implement the HasTwoFactorAuthentication trait:</p><pre>use Laravel\Fortify\TwoFactorAuthenticatable;<br><br>class User extends Authenticatable<br>{<br>    use HasFactory, Notifiable, TwoFactorAuthenticatable;<br>}</pre><p>5. Update the FortifyServiceProvider to use the totp driver:</p><pre>use Laravel\Fortify\Fortify;<br><br>public function boot()<br>{<br>    Fortify::twoFactorAuthView(&#39;auth.two-factor&#39;);<br>    Fortify::enableTwoFactorAuthenticationUsing(function ($request) {<br>        return $request-&gt;user()-&gt;two_factor_secret;<br>    });<br>    Fortify::registerView(function () {<br>        return view(&#39;auth.register&#39;);<br>    });<br>    Fortify::loginView(function () {<br>        return view(&#39;auth.login&#39;);<br>    });<br>    Fortify::requestPasswordResetLinkView(function () {<br>        return view(&#39;auth.forgot-password&#39;);<br>    });<br>    Fortify::resetPasswordView(function ($request) {<br>        return view(&#39;auth.reset-password&#39;, [&#39;request&#39; =&gt; $request]);</pre><p>6. Update the LoginController to redirect users to the two-factor authentication page if necessary:</p><pre>use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;<br><br>public function authenticated(Request $request, $user)<br>{<br>    if ($user-&gt;two_factor_secret) {<br>        $request-&gt;session()-&gt;put(&#39;auth&#39;, [<br>            &#39;user_id&#39; =&gt; $user-&gt;id,<br>            &#39;two_factor_challenge&#39; =&gt; true,<br>        ]);<br><br>        $provider = app(TwoFactorAuthenticationProvider::class);<br><br>        $provider-&gt;sendVerificationToken($user);<br>        return redirect()-&gt;route(&#39;login.two-factor&#39;);<br>    }<br><br>    return redirect()-&gt;intended(config(&#39;fortify.home&#39;));<br>}</pre><p>7. Update the TwoFactorController to handle the two-factor authentication challenge:</p><pre>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Auth;<br>use Laravel\Fortify\Contracts\TwoFactorChallengeResponse;<br><br>public function store(Request $request, TwoFactorChallengeResponse $response)<br>{<br>    $user = Auth::user();<br><br>    if (!$response-&gt;attempt($request, $user)) {<br>        return back()-&gt;withErrors([<br>            &#39;token&#39; =&gt; __(&#39;The provided two factor authentication token was invalid.&#39;),<br>        ]);<br>    }<br><br>    return redirect()-&gt;intended(config(&#39;fortify.home&#39;));<br>}</pre><p>With these changes, your Laravel application will now require users to provide a TOTP token in addition to their password to log in. This provides an additional layer of security against account takeovers and other attacks.</p><p><strong>Use HTTPS:</strong></p><p>To secure your Laravel application, you should always use HTTPS to encrypt traffic between the browser and the server. You can enable HTTPS by obtaining a TLS/SSL certificate for your domain and configuring your web server to use it.</p><p>For example, if you are using Apache, you can enable HTTPS by adding the following lines to your virtual host configuration:</p><pre>SSLEngine on<br>SSLCertificateFile /path/to/your/cert.pem<br>SSLCertificateKeyFile /path/to/your/privatekey.pem</pre><p><strong>Use Secure File Permissions:</strong></p><p>To ensure that sensitive files in your Laravel application are not accessible by unauthorized users, you should set secure file permissions on your server. Typically, your web server should have read-only access to your application files, while sensitive configuration files should not be publicly accessible.</p><p>Here are some recommended file permissions for a Laravel application:</p><pre># Set the permissions for directories to 755<br>find /path/to/your/laravel/app -type d -exec chmod 755 {} \;<br><br># Set the permissions for files to 644<br>find /path/to/your/laravel/app -type f -exec chmod 644 {} \;<br><br># Set the permissions for storage and bootstrap/cache to 777<br>chmod -R 777 /path/to/your/laravel/app/storage<br>chmod -R 777 /path/to/your/laravel/app/bootstrap/cache</pre><p><strong>Store Sensitive Data Securely:</strong></p><p>To store sensitive data, such as database credentials or API keys, securely in your Laravel application, you should use environment variables. Laravel includes the dotenv package to enable you to load environment variables from a .env file.</p><p>Here’s an example .env file:</p><pre>DB_HOST=localhost<br>DB_PORT=3306<br>DB_DATABASE=mydatabase<br>DB_USERNAME=myuser<br>DB_PASSWORD=mypassword</pre><p>In your Laravel application, you can access these environment variables using the env function:</p><pre>$host = env(&#39;DB_HOST&#39;);<br>$port = env(&#39;DB_PORT&#39;);<br>$database = env(&#39;DB_DATABASE&#39;);<br>$username = env(&#39;DB_USERNAME&#39;);<br>$password = env(&#39;DB_PASSWORD&#39;);</pre><p><strong>Use CSRF Protection:</strong></p><p>Cross-Site Request Forgery (CSRF) attacks occur when a malicious website or script forces a user to perform an action on another website without their knowledge or consent. To protect your Laravel application from CSRF attacks, you should enable CSRF protection.</p><p>Laravel includes CSRF protection middleware by default, which adds a CSRF token to all HTML forms and AJAX requests. To enable CSRF protection, add the VerifyCsrfToken middleware to the $middleware array in app/Http/Kernel.php:</p><pre>protected $middleware = [<br>    // ...<br>    \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,<br>];</pre><p>Once CSRF protection is enabled, you should include a CSRF token in all forms and AJAX requests in your application. You can do this using the @csrf Blade directive or the csrf_token() function.</p><p><strong>Use Content Security Policy:</strong></p><p>Content Security Policy (CSP) is a security mechanism that helps prevent cross-site scripting (XSS) attacks by restricting the types of content that can be loaded on a web page. By setting a CSP header, you can specify which sources of content are allowed to be loaded on your Laravel application.</p><p>To enable CSP in your Laravel application, add a Content-Security-Policy header to your web server configuration or use a Laravel middleware to set the header. Here’s an example middleware that sets a basic CSP header:</p><pre>namespace App\Http\Middleware;<br><br>use Closure;<br><br>class ContentSecurityPolicy<br>{<br>    public function handle($request, Closure $next)<br>    {<br>        $response = $next($request);<br><br>        $csp = &quot;default-src &#39;self&#39;; script-src &#39;self&#39; &#39;unsafe-inline&#39;;&quot;;<br>        $response-&gt;header(&#39;Content-Security-Policy&#39;, $csp);<br><br>        return $response;<br>    }<br>}</pre><p>Add the ContentSecurityPolicy middleware to the $middleware array in app/Http/Kernel.php:</p><pre>protected $middleware = [<br>    // ...<br>    \App\Http\Middleware\ContentSecurityPolicy::class,<br>];</pre><p><strong>Use Rate Limiting:</strong></p><p>To prevent brute-force attacks and other types of abuse, you can implement rate limiting in your Laravel application. Laravel includes rate limiting middleware that you can use to limit the number of requests per IP address or per user.</p><p>To enable rate limiting, add the throttle middleware to your routes:</p><pre>Route::middleware(&#39;throttle:60,1&#39;)-&gt;group(function () {<br>    Route::get(&#39;/profile&#39;, function () {<br>        // ...<br>    });<br>});</pre><p>In this example, the throttle middleware limits requests to 60 per minute per IP address.</p><p>You can also customize the rate limiting settings by adding a throttle key to your app/Http/Kernel.php file:</p><pre>protected $routeMiddleware = [<br>    // ...<br>    &#39;throttle&#39; =&gt; \Illuminate\Routing\Middleware\ThrottleRequests::class,<br>];<br><br>// ...<br><br>protected $middlewareGroups = [<br>    &#39;web&#39; =&gt; [<br>        // ...<br>        \Illuminate\Routing\Middleware\ThrottleRequests::class.&#39;:60,1&#39;,<br>    ],<br>];</pre><p>In this example, the throttle middleware limits requests to 60 per minute per IP address for all routes in the web middleware group.</p><p><strong>Use Security Headers:</strong></p><p>HTTP headers can be used to provide additional security for your Laravel application. Here are some recommended security headers:</p><p>· X-XSS-Protection: Enables the browser’s built-in cross-site scripting (XSS) protection.</p><p>· X-Content-Type-Options: Prevents content sniffing, which can lead to cross-site scripting (XSS) attacks.</p><p>· X-Frame-Options: Prevents clickjacking by disabling framing of the web page.</p><p>· Referrer-Policy: Controls the information that is sent in the Referer header.</p><p>To set security headers in your Laravel application, you can add them to your web server configuration or use a middleware to set them. Here’s an example middleware that sets some basic security headers:</p><pre>namespace App\Http\Middleware;<br><br>use Closure;<br><br>class SecurityHeaders<br>{<br>    public function handle($request, Closure $next)<br>    {<br>        $response = $next($request);<br><br>        $response-&gt;header(&#39;X-XSS-Protection&#39;, &#39;1; mode=block&#39;);<br>        $response-&gt;header(&#39;X-Content-Type-Options&#39;, &#39;nosniff&#39;);<br>        $response-&gt;header(&#39;X-Frame-Options&#39;, &#39;SAMEORIGIN&#39;);<br>        $response-&gt;header(&#39;Referrer-Policy&#39;, &#39;same-origin&#39;);<br><br>        return $response;<br>    }<br>}</pre><p>Add the SecurityHeaders middleware to the $middleware array in app/Http/Kernel.php:</p><pre>protected $middleware = [<br>    // ...<br>    \App\Http\Middleware\SecurityHeaders::class,<br>];</pre><p><strong>Use SSL/TLS:</strong></p><p>SSL/TLS is a security protocol that encrypts data sent between a web server and a client, preventing it from being intercepted by a third party. To secure your Laravel application, you should use SSL/TLS to encrypt all traffic.</p><p>You can obtain an SSL/TLS certificate from a trusted certificate authority (CA) and configure your web server to use HTTPS. Here are some resources to help you configure SSL/TLS in various web servers:</p><p>· Apache: <a href="https://httpd.apache.org/docs/2.4/ssl/">https://httpd.apache.org/docs/2.4/ssl/</a></p><p>· Nginx: <a href="https://www.nginx.com/blog/https-nginx/">https://www.nginx.com/blog/https-nginx/</a></p><p>· IIS: <a href="https://docs.microsoft.com/en-us/iis/manage/configuring-security/how-to-set-up-ssl-on-iis">https://docs.microsoft.com/en-us/iis/manage/configuring-security/how-to-set-up-ssl-on-iis</a></p><p>Once you have SSL/TLS configured, you should enforce HTTPS by redirecting all HTTP traffic to HTTPS. You can do this in your Laravel application by adding the following code to your AppServiceProvider:</p><pre>public function boot()<br>{<br>    if (config(&#39;app.env&#39;) === &#39;production&#39;) {<br>        \URL::forceScheme(&#39;https&#39;);<br>    }<br>}</pre><p>This code forces all URLs generated by Laravel to use the https scheme in production mode.</p><p><strong>Sanitize user input:</strong></p><p>To prevent attacks such as SQL injection and cross-site scripting (XSS), you should always sanitize user input before using it in your application.</p><p>Laravel provides several functions for sanitizing user input:</p><p>· htmlspecialchars(): Converts special characters to HTML entities.</p><p>· strip_tags(): Removes HTML and PHP tags from a string.</p><p>· addslashes(): Escapes quotes and other special characters.</p><p>You can also use Laravel’s Illuminate\Support\Facades\Validator class to validate user input and ensure it meets certain criteria.</p><p><strong>Keep dependencies up to date:</strong></p><p>To ensure your Laravel application remains secure, you should keep all dependencies up to date. This includes Laravel itself, as well as any third-party packages you use in your application.</p><p>You can use Composer to update dependencies in your Laravel application. Run the following command in your project directory to update all dependencies to their latest versions:</p><pre>composer update</pre><p>You should also regularly review security advisories for Laravel and its dependencies and take action if any vulnerabilities are discovered.</p><p><strong>Monitor and log:</strong></p><p>Even with all these security measures in place, it’s important to monitor your Laravel application for any suspicious activity or security breaches. You can use logging and monitoring tools to keep an eye on your application and detect any security issues.</p><p>Laravel provides built-in logging functionality that allows you to log errors and other information to various channels, such as files, databases, or external services. You can configure logging in the config/logging.php file.</p><p>You can also use third-party monitoring and alerting services, such as Sentry or New Relic, to monitor your Laravel application for performance and security issues. These services can alert you when an issue is detected and provide detailed information about the problem.</p><p><strong>Perform security testing:</strong></p><p>It’s important to perform regular security testing on your Laravel application to identify any vulnerabilities that may have been missed. There are several types of security testing you can perform, including:</p><p>· Vulnerability scanning: Use automated tools to scan your application for known vulnerabilities.</p><p>· Penetration testing: Simulate an attack on your application to identify potential security issues.</p><p>· Code review: Review the source code of your application to identify potential security issues.</p><p>You can perform security testing yourself or hire a professional security company to do it for you. If you perform testing yourself, be sure to use reputable tools and follow best practices to avoid causing any damage to your application.</p><p><strong>Harden your server:</strong></p><p>In addition to securing your Laravel application, you should also harden your server to prevent unauthorized access. This includes:</p><p>· Disabling unused services and ports.</p><p>· Enabling a firewall to restrict access to your server.</p><p>· Using strong passwords and enforcing password policies.</p><p>· Regularly updating your server’s operating system and software.</p><p>· Implementing intrusion detection and prevention measures.</p><p><strong>Backup regularly:</strong></p><p>In the event of a security breach or data loss, it’s important to have a backup of your Laravel application and its data. You should regularly backup your application and store backups in a secure location.</p><p><strong>Use secure session management:</strong></p><p>Laravel provides a secure way to manage user sessions using encrypted cookies. You can configure session encryption in the config/session.php file. Additionally, you should configure session timeouts to ensure that inactive sessions are automatically destroyed after a specified period of time.</p><p>How to configure session?</p><p>1. Open the config/session.php file in your Laravel application.</p><p>2. Set the driver option to the desired session driver. The default is encrypt, but you can also use file, database, redis, or other drivers.</p><p>3. Set the lifetime option to the number of minutes you want a session to last before it expires. The default is 120 minutes (2 hours). For example, to set the session lifetime to 30 minutes, you would add the following line to the config/session.php file:</p><pre>&#39;lifetime&#39; =&gt; 30,</pre><p>4. If you are using the encrypt session driver, make sure that the key option is set to the application’s encryption key. You can generate a new encryption key by running the php artisan key:generate command in your application’s root directory.</p><pre>&#39;encrypt&#39; =&gt; true,<br>&#39;key&#39; =&gt; env(&#39;APP_KEY&#39;),</pre><p>5. Save the config/session.php file.</p><p><strong>Implement role-based access control:</strong></p><p>Role-based access control (RBAC) allows you to control what actions users can perform based on their roles or permissions. Laravel provides built-in support for RBAC through the Laravel Jetstream package. You can define roles and permissions and assign them to users or user groups.</p><p>To implement role-based access control (RBAC) in Laravel using the Laravel Jetstream package, you can follow these steps:</p><ol><li>Install Laravel Jetstream using Composer by running the following command in your terminal:</li></ol><pre>composer require laravel/jetstream</pre><p>2. Run the Jetstream installer using the following command:</p><pre>php artisan jetstream:install livewire</pre><p>This will install Jetstream with the Livewire stack. If you prefer the Inertia stack, you can use php artisan jetstream:install inertia.</p><p>3. Run the migrations to create the necessary tables in your database by running the following command:</p><pre>php artisan migrate</pre><p>4. Define roles and permissions in your application. Jetstream provides a Role model and a Permission model out of the box, which you can use to define roles and permissions.</p><p>You can create new roles and permissions using the Jetstream UI or by manually creating them in your database.</p><p>5. Assign roles and permissions to users or user groups. Jetstream provides a Team model out of the box, which you can use to group users together. You can assign roles and permissions to users or teams by updating the relevant database tables.</p><p>6. Use Laravel’s built-in @can directive in your views or controllers to check if a user has a certain permission. For example, you can use the following code to check if the current user has the create_post permission:</p><pre>@can(&#39;create_post&#39;)<br>    // Display create post button or execute create post action<br>@endcan</pre><p>7. Protect your routes or actions using Laravel’s built-in middleware. For example, you can use the auth middleware to protect a route, and the can middleware to check if the current user has a certain permission. For example:</p><pre>Route::middleware([&#39;auth&#39;, &#39;can:create_post&#39;])-&gt;group(function () {<br>    // Routes that require the create_post permission<br>});</pre><p><strong>In conclusion,</strong> securing your Laravel application is a crucial aspect of web development that cannot be overlooked. By implementing the best practices discussed in this article, you can reduce the risk of security threats and ensure the safety of your users’ sensitive data. Remember to always stay vigilant, keep your application up-to-date, and follow security-focused coding practices. With a proactive and comprehensive security strategy, you can protect your Laravel application from potential threats and provide a safe and secure experience for your users.</p><p>Enjoy! :) And please let me know if you have any comments.</p><p>Mohammed</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d4242d0bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Multi-Tenant Applications with Laravel]]></title>
            <link>https://medium.com/@yaghi.moh/creating-multi-tenant-applications-with-laravel-5e02b42bbdf7?source=rss-a266562c7805------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e02b42bbdf7</guid>
            <dc:creator><![CDATA[Mohammed S. Yaghi]]></dc:creator>
            <pubDate>Thu, 20 Apr 2023 01:15:39 GMT</pubDate>
            <atom:updated>2023-04-20T01:15:39.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8qT4G3XYe_BN3buK.png" /></figure><p>Using the multi-tenancy design pattern, a single application can serve several tenants, each with specific needs and data. Applications that support numerous clients or organizations may find this to be quite advantageous.</p><p>In this article, we’ll look at how to create multi-tenant applications with Laravel, one of the most popular PHP web frameworks.</p><p>We’ll cover the following topics:</p><p>· Planning for multi-tenancy</p><p>· Implementing multi-tenancy with middleware</p><p>· Handling user authentication and authorization</p><p>· Scaling a multi-tenant application</p><p>By the end of this article, you’ll have a good understanding of how to create robust, secure, and scalable multi-tenant applications with Laravel.</p><p><strong>Planning a Multi-Tenant Application</strong></p><p>Before we begin implementing multi-tenancy in Laravel, it’s important to consider some key design decisions. These include:</p><p>1.Data Isolation:</p><p>The act of segregating tenant data so that one tenant’s data cannot be accessed by another tenant is known as data isolation. This can be accomplished by keeping the data belonging to each tenant in a different database or schema. Each tenant’s data might be kept in a separate database with a unique identity that maps to the tenant’s account, for instance, if you’re developing a SaaS application that aids firms in managing their inventories.</p><p>Another important aspect of data isolation is securing any shared data, such as reference tables, to ensure that tenants cannot modify or access each other’s data. For example, if your application includes a list of product categories that is shared across tenants, you may want to limit access to this data to administrators or add additional constraints to ensure that tenants cannot modify the data.</p><p>To achieve data isolation, you can store each tenant’s data in a separate database or schema. In Laravel, you can use a package such as Tenancy to handle this. Here’s an example of how to use Tenancy to create a new tenant and switch to their database:</p><pre>use Hyn\Tenancy\Contracts\Repositories\WebsiteRepository;<br>use Hyn\Tenancy\Contracts\Repositories\HostnameRepository;<br>use Hyn\Tenancy\Models\Website;<br>use Hyn\Tenancy\Models\Hostname;<br><br>$website = new Website;<br>$website-&gt;uuid = &#39;unique-tenant-identifier&#39;;<br>app(WebsiteRepository::class)-&gt;create($website);<br><br>$hostname = new Hostname;<br>$hostname-&gt;fqdn = &#39;tenant.domain.com&#39;;<br>$hostname = app(HostnameRepository::class)-&gt;create($hostname);<br>app(HostnameRepository::class)-&gt;attach($hostname, $website);<br><br>tenancy()-&gt;init($website, $hostname);</pre><p>This code creates a new tenant with a unique identifier and a hostname of “tenant.domain.com”. It then switches to the new tenant’s database, allowing you to perform database operations that only affect that tenant’s data.</p><p>2.Tenant Management:</p><p>Tenant management is another key consideration when building a multi-tenant application. It includes features for creating new tenants, suspending or deleting existing tenants, and managing tenant resources such as storage and bandwidth.</p><p>For example, if you’re building a multi-tenant e-commerce platform, you may need to provide tools for merchants to create their online store and manage their inventory, orders, and payments. Additionally, you may need to include features for administrators to manage tenants, such as creating new tenants, setting resource limits, and monitoring usage.</p><p>To implement tenant management features, you can create a dedicated controller that handles tasks such as creating new tenants, suspending or deleting existing tenants, and managing tenant resources.</p><pre>namespace App\Http\Controllers\Admin;<br><br>use App\Http\Controllers\Controller;<br>use App\Models\Tenant;<br>use Illuminate\Http\Request;<br><br>class TenantController extends Controller<br>{<br>    public function index()<br>    {<br>        $tenants = Tenant::all();<br>        return view(&#39;admin.tenants.index&#39;, compact(&#39;tenants&#39;));<br>    }<br><br>    public function create()<br>    {<br>        return view(&#39;admin.tenants.create&#39;);<br>    }<br><br>    public function store(Request $request)<br>    {<br>        $tenant = new Tenant;<br>        $tenant-&gt;name = $request-&gt;name;<br>        $tenant-&gt;domain = $request-&gt;domain;<br>        $tenant-&gt;save();<br>        return redirect()-&gt;route(&#39;admin.tenants.index&#39;);<br>    }<br><br>    public function suspend(Tenant $tenant)<br>    {<br>        $tenant-&gt;suspended_at = now();<br>        $tenant-&gt;save();<br>        return redirect()-&gt;route(&#39;admin.tenants.index&#39;);<br>    }<br><br>    public function delete(Tenant $tenant)<br>    {<br>        $tenant-&gt;delete();<br>        return redirect()-&gt;route(&#39;admin.tenants.index&#39;);<br>    }<br>}</pre><p>This code creates a TenantController with methods for displaying a list of tenants, creating a new tenant, suspending a tenant, and deleting a tenant. You can add additional methods as needed to handle other tenant management tasks.</p><p>3.Customization:</p><p>Customization is another important consideration when building a multi-tenant application. Depending on the nature of the application, tenants may require varying degrees of customization. For example, tenants may want to configure their own branding, payment gateway, or integration with external systems.</p><p>For example, if you’re building a SaaS platform for project management, you may want to provide tenants with the ability to customize their project workflows, add custom fields to tasks, and configure notifications based on their specific needs.</p><p>To implement customization features, you can create a settings page where tenants can configure their settings. You can store the settings in the tenant’s database and retrieve them as needed.</p><pre>namespace App\Http\Controllers\Tenant;<br><br>use App\Http\Controllers\Controller;<br>use Illuminate\Http\Request;<br><br>class SettingsController extends Controller<br>{<br>    public function index()<br>    {<br>        $settings = auth()-&gt;user()-&gt;settings;<br>        return view(&#39;tenant.settings.index&#39;, compact(&#39;settings&#39;));<br>    }<br><br>    public function update(Request $request)<br>    {<br>        $settings = auth()-&gt;user()-&gt;settings;<br>        $settings-&gt;update($request-&gt;all());<br>        return redirect()-&gt;route(&#39;tenant.settings.index&#39;);<br>    }<br>}</pre><p>This code creates a SettingsController with methods for displaying a settings page and updating the tenant’s settings. You can add additional methods as needed to handle other customization tasks.</p><p>4.Performance:</p><p>Performance is critical for multi-tenant applications, as a slow application can lead to a poor user experience and lost revenue. To ensure optimal performance, the application should be designed to scale horizontally across multiple servers or cloud instances.</p><p>For example, if you’re building a multi-tenant CRM platform, you may need to distribute tenant data across multiple servers to ensure that the application can handle high traffic and provide fast response times. Additionally, you may need to use caching and load balancing techniques to optimize performance.</p><p>To ensure optimal performance, you can implement caching and load balancing strategies. For example, you can use Laravel’s built-in caching mechanisms such as Redis or Memcached to cache frequently accessed data, or use a load balancer such as NGINX or HAProxy to distribute traffic evenly across multiple application instances.</p><p>Here’s an example of how to implement caching in a Laravel-based multi-tenant application using Redis:</p><pre>namespace App\Services;<br><br>use Illuminate\Support\Facades\Cache;<br><br>class TenantService<br>{<br>    public function getTenantData($tenantId)<br>    {<br>        $data = Cache::remember(&quot;tenant_data_$tenantId&quot;, 60, function () use ($tenantId) {<br>            return Tenant::find($tenantId)-&gt;data;<br>        });<br>        return $data;<br>    }<br>}</pre><p>This code creates a TenantService with a method that retrieves a tenant’s data from the database, but caches the data for 60 seconds to avoid unnecessary database queries. You can adjust the cache duration as needed based on your application’s requirements.</p><p>5.Security:</p><p>Security is another critical consideration for multi-tenant applications. The application should have a robust security model that ensures the confidentiality, integrity, and availability of tenant data. Security considerations include data encryption, access control, auditing, and monitoring.</p><p>For example, if you’re building a multi-tenant financial management platform, you may need to encrypt sensitive data such as credit card numbers and bank account information. Additionally, you may need to implement access controls to ensure that only authorized users can access tenant data, and include auditing and monitoring tools to track user activity and detect security breaches.</p><p>To ensure the security of your multi-tenant application, you should implement robust authentication and authorization mechanisms. Laravel provides built-in authentication features such as the Auth facade and Laravel Passport for implementing OAuth2 authentication.</p><p>Here’s an example of how to implement authentication in a Laravel-based multi-tenant application using Laravel Passport:</p><pre>Route::middleware(&#39;auth:api&#39;)-&gt;group(function () {<br>    Route::get(&#39;/user&#39;, function (Request $request) {<br>        return $request-&gt;user();<br>    });<br>});</pre><p>This code creates a route group that requires authentication using the auth:api middleware. You can use this route group to define API endpoints that require authentication before they can be accessed.</p><p>6.Monitoring and Reporting:</p><p>Monitoring and reporting tools are critical for multi-tenant applications, as they allow tenants to understand how they’re using the application and identify areas for optimization. For example, if you’re building a multi-tenant analytics platform, you may need to provide tenants with tools for monitoring their website traffic, conversion rates, and other key performance indicators.</p><p>Additionally, you may need to provide administrators with tools for monitoring resource usage, such as disk space and bandwidth, to ensure that tenants are not exceeding their resource limits.</p><p>In conclusion, building a multi-tenant application requires careful planning and consideration of several factors, including data isolation, tenant management, customization, performance, security, and monitoring and reporting. By addressing these considerations, you can ensure that your application meets the needs of its users and can scale to meet the demands of a growing user base.</p><p><strong>Implementing Multi-Tenancy with Middleware</strong></p><p>Once we have a plan for our multi-tenant application, we can begin implementing it in Laravel. The first step is to create middleware that will set up the correct database connection and credentials for each request.</p><p>We can create a TenantMiddleware class that will identify the current tenant and set up the correct database connection. Here’s an example:</p><pre>namespace App\Http\Middleware;<br><br>use Closure;<br>use Illuminate\Support\Facades\DB;<br><br>class TenantMiddleware<br>{<br>    public function handle($request, Closure $next)<br>    {<br>        $tenant = $this-&gt;resolveTenant($request);<br><br>        // Set the database connection for the current tenant<br>        config([&#39;database.connections.tenant&#39; =&gt; [<br>            &#39;driver&#39; =&gt; &#39;mysql&#39;,<br>            &#39;host&#39; =&gt; $tenant-&gt;db_host,<br>            &#39;port&#39; =&gt; $tenant-&gt;db_port,<br>            &#39;database&#39; =&gt; $tenant-&gt;db_database,<br>            &#39;username&#39; =&gt; $tenant-&gt;db_username,<br>            &#39;password&#39; =&gt; $tenant-&gt;db_password,<br>        ]]);<br><br>        DB::purge(&#39;tenant&#39;);<br>        DB::setDefaultConnection(&#39;tenant&#39;);<br><br>        // Store the current tenant in the request object<br>        $request-&gt;merge([&#39;tenant&#39; =&gt; $tenant]);<br><br>        return $next($request);<br>    }<br><br>    protected function resolveTenant($request)<br>    {<br>        // Resolve the current tenant based on the request<br>        // This could be done using a subdomain, path prefix, or custom header<br>        $tenantId = $request-&gt;header(&#39;X-Tenant-ID&#39;);<br><br>        return Tenant::findOrFail($tenantId);<br>    }<br>}</pre><p>In this example, we’re using the resolveTenant method to identify the current tenant based on a custom HTTP header. We’re then using the config function to set up the database connection for the current tenant, and the DB facade to set the default database connection and purge any existing connections. Finally, we’re storing the current tenant in the request object using the merge method.</p><p>To use the middleware, we can add it to the application’s middleware stack. This can be done in the App\Http\Kernel class:</p><pre>protected $middleware = [<br>    // Other middleware...<br>    \App\Http\Middleware\TenantMiddleware::class,<br>];</pre><p>Once the middleware is in place, we can use it to implement tenant isolation in our controllers, models, and other components.</p><p>For example, in a controller that manages a tenant’s data, we can retrieve the current tenant from the request object and use it to query the database:</p><pre>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Http\Controllers\Controller;<br><br>class TenantController extends Controller<br>{<br>    public function index(Request $request)<br>    {<br>        $tenant = $request-&gt;input(&#39;tenant&#39;);<br>        $users = User::where(&#39;tenant_id&#39;, $tenant-&gt;id)-&gt;get();<br><br>        // ...<br>    }<br><br>    // ...<br>}</pre><p><strong>Handling User Authentication and Authorization</strong></p><p>In a multi-tenant application, we need to ensure that users can only access data that belongs to their own tenant. Laravel provides a robust authentication and authorization system that can be extended to support multi-tenancy.</p><p>One approach is to use Laravel’s built-in Gate class to define policies that restrict access to data based on the user’s tenant. Here’s an example:</p><pre>namespace App\Policies;<br><br>use App\User;<br>use App\Tenant;<br>use Illuminate\Auth\Access\HandlesAuthorization;<br><br>class TenantPolicy<br>{<br>    use HandlesAuthorization;<br><br>    public function view(User $user, Tenant $tenant)<br>    {<br>        return $user-&gt;tenant_id === $tenant-&gt;id;<br>    }<br><br>    // ...<br>}</pre><p>In this example, we’re defining a policy that allows users to view a tenant only if they belong to the same tenant. We can then use this policy in our controllers and other components:</p><pre>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Http\Controllers\Controller;<br>use App\Tenant;<br><br>class TenantController extends Controller<br>{<br>    public function index(Request $request)<br>    {<br>        $this-&gt;authorize(&#39;view&#39;, $request-&gt;input(&#39;tenant&#39;));<br><br>        $tenant = $request-&gt;input(&#39;tenant&#39;);<br>        $users = User::where(&#39;tenant_id&#39;, $tenant-&gt;id)-&gt;get();<br><br>        // ...<br>    }<br><br>    // ...<br>}</pre><p><strong>Scaling a Multi-Tenant Application</strong></p><p>As our multi-tenant application grows, we may need to scale it to handle more tenants and more data. One approach is to use database sharding, which involves splitting data across multiple database instances based on a sharding key.</p><p>Laravel provides support for database sharding through the Illuminate\Database\Eloquent\Shardable trait. We can use this trait in our models to automatically route queries to the correct database based on the sharding key:</p><pre>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Shardable;<br><br>class User extends Model<br>{<br>    use Shardable;<br><br>    protected $shardKey = &#39;tenant_id&#39;;<br><br>    // ...<br>}</pre><p>In this example, we’re using the Shardable trait and specifying the tenant_id column as the sharding key. Laravel will automatically route queries for each tenant to the correct database based on their tenant_id.</p><p><strong>Conclusion</strong></p><p>In this article, we’ve explored how to create multi-tenant applications with Laravel. We’ve covered key considerations for planning a multi-tenant application, how to implement multi-tenancy with middleware, how to handle user authentication and authorization, and how to scale a multi-tenant application. With these techniques, you can create powerful and flexible applications that can serve multiple customers or organizations with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e02b42bbdf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>