Category: Technology

  • Laravel 5: create route group that is only available during testing (Middleware)


    Today I needed to protect a group of routes from everything except my testing environment. I need to run PHPUnit tests that depend on certain routes, but I don’t want those routes to be available anywhere else. I’ll share in this blog post what I did to get what I need.

    Assumptions in this tutorial:

    You already have Laravel 5 installed on your computer and you are running the app in “testing” mode (e.g. PHPUnit testing)

    Introduction

    In Laravel, Middleware filters requests that are coming into our application. One of the pre-made Middleware in Laravel 5.2 is Authenticate, which looks like this:

    Inside the handle() method, it checks if the request is using AJAX -or- is asking for JSON, and if either condition returns TRUE, it blocks access and returns ‘Unauthorized’ as response. Otherwise, client is redirected to the ‘login’ route, which should happen when client is requesting via web browser.

    What I did to make my grouped routes available only in testing environment (in my case, when running PHPUnit) was create a new Middlewave. I’ll show you how. 🙂

    Create a new file under Http/Middleware and name it TestingEnvOnly.php

    In the handle method, we check if app environment is set to testing, and if so, we allow the request to access the requested route. Otherwise, the request should fail and repond with ‘Unavailable’.

    Now, let’s register this Middleware to Http/Middleware. Add the following to the $routeMiddleware array:

    It’s time to add a testing-only route:

    If you use PHPUnit like I do, you can test our new Middleware by creating this test method:

    I’m only using var_dump so that we can easily see the printed string response which should say “This should be visible only for testing environment” when you run PHPUnit.

    Now, in your web browser, visit the route your set for /api/v1/testing_env_only. It should say ‘Unauthorized’.

    Here’s how the files I edited in Laravel look like now:

    I’m using Laravel 5.2 and these are codes I uploaded at Gist

  • Laravel 5: activate API token guard and print “Unauthorized” instead of login redirect

    In Laravel 5, I wrap my API routes in a route group like this:

    Notice that I use auth:api and throttle on my middleware array.

    auth:api turns on the auth middleware with API token as guard, while throttle activates rate limiter for APIs.

    To get started with API token authentication, you may read https://gistlog.co/JacobBennett/090369fbab0b31130b51.

    I followed the same tutorial to set mine up, but had this issue: Upon using invalid api_token or no token at all, I am redirected to the /login route, which in my case is a currently nonexistent route.

    As instructed by the guide, I already edited my app/Http/Middleware/Authenticate.php file to add the || $request->wantsJson() condition, but my API routes still redirected to /login route upon detection of invalid api_token.

    The solution

    What I did was add another condition: || $guard == "api"

    And now, my app/Http/Middleware/Authenticate.php file looks like this:

  • Android app dev: ShareActionProvider in Activity & Fragment

    I’ve been taking the Developing Android Apps course on Udacity, and yesterday I encountered a difficulty in solving the Quiz: Share Intent.

    One of the course’s goal is to build the Sunshine App – an Android app with weather forecast.

    In that quiz I had to implement ShareActionProvider on my DetailsFragment so that a share icon becomes available on my app’s ActionBar.

    One of the main difficulties was the error that stated ActionProvider cannot be cast into ShareActionProvider. And at some point there was also an error saying that the methods/classes I’m using require API 14, while my minimum supported API is 9. The Udacity course required that I set it to 9 so I couldn’t change that.

    Now, the sharing in my app is working file, and I will share how I did it via Gist. I actually ended up taking a peek at the code provided by Developing Android Apps course on Udacity because I didn’t want to waste any more time doing trial-and-error (I have another project to work on! lol), but I still had to edit their code for ShareActionProvider here and there to make it bug-free.

    And so, take a look at how my Sunshine app codes ended up:

  • Mac OS X – Sublime Text 2 key bindings suddenly stopped working (SOLVED)

    https://www.sublimetext.com/docs/2/revert.html

    I’m using a Mac Mini with OS X El Capitan (v. 10.11) with Sublime Text v.2.0.2.

    Today, Sublime Text shortcuts like Cmd + / (line comment), Cmd + D (multiple selection), Cmd + F (find) and others stopped working. I had no problem with those key bindings before until today.

    Based on research, I found that it could be caused by packages installed to Sublime Text. Aha! It could be the GoToClass package that I just installed today! I uninstalled it since I was desperate and the package didn’t work as I need it to anyway. Still no luck, my favorite Sublime Text shortcuts still didn’t work.

    I decided to revert my Sublime Text into a clean install. That fixed my key bindings that stopped working.

    I’ll show you how.

    First, quit Sublime Text 2.

    Then remove the “Sublime Text 2” folder that’s located at ~/Library/Application Support/. You may try to do so by running this command in the terminal:

    FYI: The backslashes are required to escape the white spaces in file/folder names. rm is the command for removing files/folders. The -rf flag means that we want to remove the folder we specified and all its contents recursively.

    Once deleted, run Sublime Text 2 again. You’ll notice that it’s back to its freshly installed state. 🙂

  • Laravel 5 RESTful API with Basic Auth: PHPUnit Testing

    I’ve been using PHPUnit to test my RESTful API. PHPUnit is ready to use in Laravel.

    In my Laravel-based RESTful API, I have an endpoint /api/users which returns JSON data when you send a GET request. The API will only return such data if the client sends the corrent username and password (Basic Authentication). The JSON data looks like this:

    I’m gonna show you how to create a PHPUnit test for this kind of JSON API data in Laravel 5.

    To create a test case, use this command:

    This will create a new test case named ApiUsersTest.php in your directory /tests

    Paste the following code in it.

    Edit the test case as needed.

  • Android M runtime permissions utility class


    Hello world, I prepared a PermissionsUtil.java class and it’s on GitHub.

    Check it out: AndroidPermissionsUtil

    Why use it? It will help by letting you write less code as you add conditions to your Android app that supports Android 6.0 (Marshmallow). The utility class defines helper methods that were used in the following example.

    Sample usage of Android M PermissionUtils

    On the activity where you need to check for runtime permissions, add these:

    And add the callback function to the same activity:

    Feel free to use in on any project. And please let me know if you have suggestions on how to improve that Android M runtime permissions utility class.

  • Android app codes for Google Maps with clustering

    I prepared Android app codes with Google Maps and clustering feature. Feel free to use these as basis for your new projects.

    They are on GitHub:

    Android map clustering with default markers

    [1] Default Map Markers:
    catzie/SimpleAndroidMapClustering

     

     

    I simply took the necessary classes and res files from Android Maps Utility demo, and then placed them into bare Android Studio projects for simplicity. For me, it’s easier to start a new “maps with clustering” project on simple apps like these, rather than downloading the entire Android Maps Utility Demo, picking out the necessary files, and fixing errors before getting started each time. 😆

     

  • Android Maps: Get current location coordinates with Google API Client Builder

    To get your current location via Google Map in an Android app, this was how we do it:

    Stop. Don’t use that! The method GoogleMap.getMyLocation() is deprecated. Instead, we need to use FusedLocationApi and the callback onLocationChanged().

    Here’s an example code that works for me ( consider copying the contents of onResume() into onStart() ):

    Code source: How to get current location of device on google maps api v2, getMyLocation() method is deprecated

  • Bash: rename all files in directory, replacing all hyphens (-) with underscores (_)

    I don’t want to waste time doing things manually when I can run a script that will help me save time and effort.

    When using Linux or Mac command line (bash?), if you want to rename all files in your present directory and replace all hyphens - with underscores _, run this command:

    And if you want to do the reverse, i.e., replace all underscores _ with hyphens -, run this command instead:

    To remove substring from file names, (e.g., remove @3x string), run this:

    I had to do this after importing image files with hyphens in their names into my Android project. I can’t use images with hyphens in their names.

  • Android Studio: add Google Map from empty activity (dev note)

    //Update: I prepared a simple Android app that features a Google Map with markers that form clusters together when zoomed out. Check it out: Simple Android Map Clustering on GitHub.

    This “dev note” of mine will give you a rough idea on how to add a Google Map to your Android up from an empty activity, not from a pre-made Google Maps activity.

    I won’t be able to write everything in detail here because I’m in a hurry, and so I’m calling this article a “dev note” instead of tutorial. 🙂 This dev note can be considered a “guide” too.

    This dev note was based on Android Studio v.2.1 running on MAC OS X

    From your Android Studio’s SDK Manager, install Google Play Services.

    Add this as child of <application> tag in AndroidManifest.xml:

    Later we’ll replace YOUR_API_KEY with a key from Google API Console.

    Also add these to your AndroidManifest.xml as direct child of manifest tag:

    We need to get an API KEY for the value attribute of this meta data. Let’s get one from the Google API Console — create a new project there and then search for Google Maps Android API. Enable it.

    After enabling it, you’ll find a way to get an API key that we need from Google API Console. Go to Credentials -> Create Credentials -> API Key -> Android Key. Before we are given the API key, we need to provide Google API Console a SHA1 certificate fingerprint from our computer and our app’s package name.

    To generate SHA1 certificate fingerprint on a Mac, type this on the terminal:

    On Windows, try this command:

    When prompted for a keystore password, enter the word debug as your password.

    Copy the SHA1 certificate fingerprint and then paste it into Google API Console. Enter your package name as well (e.g. com.yourdomain.projname). You’ll be given an API Key in return.

    Note: My Android Studio says ‘In the Google Developer Console (https://console.developers.google.com), ensure that the “Google Maps Android API v2” is enabled.’ but I can’t find the option for V2.

    Remember the meta-data tag we added in the AndroidManifest.xml? Replace the value with the API key that you just copied from Google API Console.

    Resource: https://developers.google.com/maps/documentation/android-api/signup

    Open app/build.gradle file and add the following as dependency:

    Sync your project with Gradle files.

    This was one of the tutorials I followed: GOOGLE MAPS ANDROID API V2 TUTORIAL USING ANDROID STUDIO and I based my XML plus Java codes on the author’s.

    My files in the end…

    Here were the codes of my Android app when I finally made the Google Map show up in the activity:

    app/build.gradle

    build.gradle

    app/src/main/res/layout/activity_main.xml

    app/src/main/java/net/catzie/maptest/MainActivity.java

    app/src/main/AndroidManifest.xml

    …even though the Google Map now shows up on my Android activity, I get these errors that I’m not able to fix yet: