<?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 Alhasan A. Al-Nasiry on Medium]]></title>
        <description><![CDATA[Stories by Alhasan A. Al-Nasiry on Medium]]></description>
        <link>https://medium.com/@alhasaniq?source=rss-627818269f4b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HqNAK5U6ukU86tNF8BzSXg.jpeg</url>
            <title>Stories by Alhasan A. Al-Nasiry on Medium</title>
            <link>https://medium.com/@alhasaniq?source=rss-627818269f4b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:39:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alhasaniq/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Walk Through PiTrol — Part 1]]></title>
            <link>https://medium.com/@alhasaniq/a-walk-through-pitor-part-1-888a30f6ecd3?source=rss-627818269f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/888a30f6ecd3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pitrol]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Alhasan A. Al-Nasiry]]></dc:creator>
            <pubDate>Tue, 14 Feb 2017 22:28:00 GMT</pubDate>
            <atom:updated>2017-02-14T22:46:41.788Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explaining the project(PiTrol) and its basic structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkrZ9WrNI2GWdcFghYc6Ug.jpeg" /></figure><h3>If you don’t know what PiTrol is</h3><p><strong>PiTrol is a project that </strong><a href="https://www.facebook.com/groups/geekerz/"><strong>we </strong></a><strong>started on github.<br>Someone suggested that we make weekly projects on </strong><a href="https://www.facebook.com/groups/geekerz/"><strong>our facebook group</strong></a><strong> and we began voting for the idea/development-stack/features/… <br>We agreed on:</strong></p><ul><li>making a <strong>RaspberryPi Controller project</strong> that lets people control the Pi <strong>from the web</strong> , supporting plugins and custom things</li><li>using <strong>Nodejs</strong>-v6 + ExpressJS as backend</li><li>using <strong>ReactJS </strong>as frontend</li></ul><p>so we made <a href="https://github.com/fadeenk/PiTrol"><strong>this repo(fadeenk/PiTrol)</strong> </a>and started</p><h3>How to understand an existent project</h3><p>You start by reading the repo’s readme.md, we see the usage section saying <br>“to Start the app execute : node server ”<br>this command means that it will start the server/index.js with nodejs.</p><p>we go to server/index.js to see how it works,<br>the only thing it is doing is loading server/app.js and storing it in the variable app via using require(). then using the app.listen()method.</p><p>we go to server/app.js to see what is going on there and what is this listen() method,<br>most of the code in the beginning is ExpressJS boilerplate code, which is (ExpressJS) a framework for Nodejs that helps you utilize a web-server functionality without headaches.<br>Its topology is very simple, <br>you define a route, and tell the framework what to do when this route is requested. for example :</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; res.status(200).render(&#39;index.html&#39;))</pre><p>This tells ExpressJS to serve an HTTP 200(OK) response that contains index.html when the route / is requested with a Get request</p><p>The second part (the one full with loops) is responsible for registering the plugins api routes ( for example: the system-uptime plugin PiStatus , every plugin has what we call features, each feature should serve a single functionality and has one route, the feature SystemUptime is one of the PiStatus features that has a Get route, which will return the system-uptime.)<br>This will help us save time so that we wont need to edit app.js when we add a new plugin.</p><p>At this point we know that there is a server in server/app.js , plugins in plugins/ , react app in src/ , static files in public/ .</p><h3>Plugins structure</h3><p>Plugins are found in plugins/ , this folder contains an plugins/index.js which is like a package.json but for plugins (it loads plugins),<br>The folder also has a folder for each plugin.</p><pre>plugins/<br>      + index.js<br>      + AnEpicPlugin/<br>      + AnotherPlugin/</pre><h4>Putting a Plugin under the microscope:</h4><p>when we look at the plugin PiStatus we see 3 files:</p><pre>index.js -----------------&gt; a wrapper for the other 2 files<br>requesthandler.js --------&gt; handles the API requests<br>uicomponent.js -----------&gt; contains the front-end (html/css/js)</pre><p><strong>plugins/PiStatus/index.js : </strong>this file is a wrapper that exports the other 2 files to the plugins loader ( plugins/index.js ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*o8KYyIwXirFzhqDzkxeT2w.png" /><figcaption>the index.js of PiStatus</figcaption></figure><p>The plugins is divided into 2 parts,</p><ul><li><strong>Front-end</strong>: ( React component ) which is defined in the module as uiComponent , it must contain 2 obligatory props:<br><strong><em>loadFrom </em></strong>tells the react component the API route<br><strong><em>reloadEvery </em></strong><em>tells the react component the reload interval</em></li><li><strong>Back-End:</strong> ( the API requests handlers ),<br>a plugin might have multiple features such as a GPIO plugin that has Read&amp;Write functionalities. Each one should have its own <strong>route </strong>and each route should point to its own <strong>handler</strong>. <br>Every feature will be defined In the features: [] as in the picture above.<br>the method and the reference to the handler have to be included as: methods &amp; ref .</li></ul><p><strong>The Front-End </strong>( uicomponent.js ) is pretty straight forward.<br>loadData() does an AJAX request to fetch data from the server.<br>getData() formats the data for presentation<br>render() contains the JSX (HTML+JS) that will be shown in the page<br>componentDidMount() tells the browser to reload Data based on the interval</p><p><strong>The Back-End</strong> ( requesthandler.js ) is really simple.<br>it contains the logic&amp;behavior of the plugin that will be executed when the API route is requested.</p><h3>How do i Contribute ?? :\</h3><p><strong>If you dont know how to use github</strong> professionally this is an amazing chance for you to do mistakes without getting blamed or shamed. just go read about basic github things like (repo/branch/commit/fork/pull request/merge &amp; most importantly github Issues)</p><p><strong>If you do know github</strong></p><ul><li>Fork<a href="https://github.com/fadeenk/PiTrol"> the repo</a> then clone it on your pc</li><li>Read the issues to see what needs to be done/fixed</li><li>start coding in your local clone</li><li>commit<strong> (to your fork only) </strong>when you have something achieved/fixed/done.</li><li>push your commits to your fork on github.com (remote)</li><li>make a <strong>Pull-Request ( PR ) </strong>which tells the repo owner to merge your commits into the original repo</li></ul><h3>Dont forget to</h3><ul><li><strong>reference issues in your commit</strong> description or title,<br>this will help us understand what is this commit trying to achieve <br>this is done by writing # then the number of the issue<br>ex:</li></ul><pre>Example messages if you are committing about an issue numbered <strong>15<br>Some sample commit messages (titles) would be:<br> - Fixes #15<br> - WIP #15<br> - debugging #15 with console.log</strong></pre><p>and have a look <a href="https://help.github.com/articles/closing-issues-via-commit-messages/">at this small trick </a>to automatically close an issue.</p><ul><li><strong>reference issues in Pull-Requests</strong> for the same reason as above,<br>also by writing # then the number of the issue.</li><li><strong>review others code (commits &amp; PR’s) </strong>to stay on the same page with everyone.<br>btw, feel free to ask about any line of the code by commenting on that line.</li><li><strong>ask questions</strong></li><li><strong>give commits descriptive titles</strong></li><li><strong>have fun while coding</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888a30f6ecd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add token-based authentication to a laravel app ( to use in API’s )]]></title>
            <link>https://medium.com/@alhasaniq/how-to-add-token-based-authentication-to-laravel-app-s-to-use-in-api-s-1a0e45f9106?source=rss-627818269f4b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a0e45f9106</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Alhasan A. Al-Nasiry]]></dc:creator>
            <pubDate>Sat, 21 Nov 2015 19:18:50 GMT</pubDate>
            <atom:updated>2015-11-21T19:44:58.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVGQEn383bu10KxGN7hkrg.jpeg" /></figure><h4>Introduction :</h4><p>So, starting with a mind-sketch is always the best way to start programming something.<br>What we want to achieve is to find a way to authenticate users with a special token so that we can use it to work with API Clients that wont be able to send cookie’s .</p><p>So basically we want to :</p><ul><li><strong>Generate </strong>an<strong> <em>auth_token</em></strong> for each user</li><li>make a route so that the user can<strong> login</strong> with his email/password <strong>and get </strong>back <strong>the <em>auth_token</em></strong> in the response</li><li>make a <strong>middleware </strong>to check the auh in each request</li></ul><h3>Starting the work :</h3><h4>1. Generating the auth_token :</h4><p>So the first thing we will do is to add a column in the users table called <em>“</em><strong><em>auth_token</em></strong><em>” .</em> So head to your users_table_migration file and add this line then refresh the migration’s and remigrate</p><pre>$table-&gt;string(&#39;auth_token&#39; , 60);</pre><p>Now we will make a method that will hash the auth_token in the AuthController</p><pre>protected function auth_token($password)<br> {<br>   $auth_token = &#39;auth_token_&#39;.$password;<br>   return bcrypt($auth_token);<br> }</pre><p>and add it to the <strong><em>create </em></strong>method</p><pre>protected function create(array $data)<br> {<br>   return \User::create([<br>     // some data ..... </pre><pre>     <strong>&#39;auth_token&#39; =&gt; auth_token($data[&#39;password&#39;])</strong><br>  ]);<br> }</pre><p>This should cover the token-generating part .<br>just keep in mind that you need to change the <strong><em>auth_token</em></strong> when the user resets/changes his password.</p><h4>2. API Login Route</h4><p>We will need a route to let the user enter his credentials and get back his token<br>so head to the <strong><em>routes.php</em></strong> file and add the following<br><em>* i will be using the groups wrapping way which will make your job much easier for larger API’s but will be a little messy for smaller projects</em></p><pre>Route::group([‘prefix’ =&gt; ‘api’], function()<br>{<br>   Route::group([‘prefix’ =&gt; ‘v1’], function()<br>   {<br>      Route::group([‘prefix’ =&gt; ‘auth’], function()<br>      {<br>          <strong>Route::post(‘login’,’APIController@login’);</strong><br>      });<br> <br>    <strong>  Route::post(‘something’,’APIController@something&#39;);</strong></pre><pre>   });<br>});</pre><p>so, we have the <strong>/api/v1/<em>auth/login</em></strong> and we have another path <strong>/api/v1/something </strong>which could be anything protected so that the user cant reach without authentication</p><p>No we make the APIController and make the <strong><em>login </em></strong>method</p><pre>public function login(Request $request)<br>{<br>   $validator = \Validator::make($request-&gt;all(), [<br>      ‘email’ =&gt; ‘required’,<br>      ‘password’ =&gt; ‘required’,<br>   ]);</pre><pre>   if ($validator-&gt;fails()) {<br>     return \Response::json([<br>        ‘status’ =&gt; false ,<br>        ‘errors’ =&gt; $validator-&gt;errors()-&gt;all(),<br>     ]);<br>   }</pre><pre>//Here we will use Auth::once as it wont create a session that we wont need</pre><pre>// we use $request-&gt;input() as this will work with json objects and we wont have to worry about it</pre><pre>   if ( \Auth::once([‘email’ =&gt; $request-&gt;input(‘email’), ‘password’ =&gt; $request-&gt;input(‘password’) ]) )<br>   {<br>      return \Response::json([<br>        ‘status’ =&gt; true ,<br>        ‘user’ =&gt; Auth::user(),<br>        ‘errors’=&gt; array()<br>      ]);</pre><pre>   }<br>   else{<br>      return \Response::json([<br>         ‘status’ =&gt; false ,<br>         ‘errors’ =&gt; array($this-&gt;getFailedLoginMessage()) ,<br>      ]);<br>   }<br> <br>}</pre><p>and we can try it by sending this json object with a REST Client ( i use postman ) to our route</p><pre>{<br>    “email”:”admin@admin.com”,<br>    “password”:”some password or what ever”<br>}</pre><p>So lets say we got back the User object,save the <strong><em>id </em></strong>,<strong><em> auth_token </em></strong>somewhere to use it later.</p><h4>3.The Middleware</h4><p>Lets create the middleware that will check the auth_token &amp; user_id in every request to a protected route</p><p>So we make this file</p><pre>laravel/app/Http/Middleware/Auth_Token.php</pre><p>and add it in the <strong>$routeMiddleware</strong> variable in the<strong> kernal file</strong></p><pre>laravel/app/Http/Kernel.php</pre><p>it should look like this :</p><pre>‘auth_token’ =&gt; \App\Http\Middleware\Auth_Token::class,</pre><p>Now lets write our middleware’s handle function’s content :</p><pre>$validator = \Validator::make($request-&gt;all(), [<br>    ‘auth.id’ =&gt; ‘required|numeric|exists:users,id’,<br>    ‘auth.auth_token’ =&gt; ‘required’,<br> ]);</pre><pre>if ($validator-&gt;fails()) {<br>    return \Response::json([<br>       ‘status’ =&gt; false ,<br>       ‘errors’ =&gt; $validator-&gt;errors()-&gt;all(),<br>    ]);<br> }</pre><pre>$user = User::find($request-&gt;input(‘auth.id’));</pre><pre>if ($user-&gt;auth_token == $request-&gt;input(‘auth.auth_token’)) {<br>    return $next($request);<br> }</pre><pre>else{<br>    return \Response::json([<br>       ‘status’ =&gt; false ,<br>       ‘errors’ =&gt; array(‘token/id combination validation failed.’),<br>    ]);<br> }</pre><p>So lets brake the code :</p><ul><li>We make a validator to make sure that : the <strong><em>id</em></strong>,<strong><em>auth_token</em></strong> are there , the id is numeric , the id exists in the table users, column id.<br>And if the validator fails we return an error</li><li>Now we Select the user from the database and<strong> check if the<em> auth_token</em> is correct</strong><br>-If so, we pass the request.<br>-If not , we return an error</li></ul><p>All we have to do now is to link the middleware to the methods<br>this can be achieved in 2 ways ,<br><strong>1</strong>. by defining the middleware in the <strong>routes</strong><br><strong>2</strong>. by defining the middleware in the <strong>ApiController </strong>( which is what i use )</p><p>Go to the <strong>ApiController </strong>and place this in the very beginning of the class</p><pre>function __construct() {<br>    $this-&gt;middleware(‘auth_token’,<br>     [‘except’ =&gt; array(‘login’,’something_unprotected’)]<br>    );<br> }</pre><p>So every call to a method in this controller will trigger the middleware first, and if it passes the execution will continue.</p><p>We added a second argument which is <strong><em>except </em></strong>.<br>This will let us exclude some methods from triggering the middleware</p><p>*note that you <strong>HAVE </strong>to exclude the <strong><em>login method</em></strong><em> </em>from the middleware</p><p>So if we make the <strong><em>something method </em></strong>that we defined earlier in the routes file<br>lets say <strong>something </strong>is a function that returns a welcome message</p><pre>public function <strong>something</strong>(Request $request)<br> {<br>    $name = $request-&gt;input(&#39;msg&#39;);</pre><pre>    return Response::json([<br>       ‘status’=&gt;true,<br>       ‘msg’=&gt;&quot;Hello,&quot;.$name,<br>       ‘errors’=&gt;array()<br>    ]);<br> }</pre><p>and we send the following json object to the route <em>/api/v1/something</em></p><pre>{<br>   &quot;auth&quot;:{<br>            &quot;id&quot; : 1 ,<br>            &quot;auth_token&quot; : &quot;some auth token that we saved earlier&quot;<br>          },<br>   <br>   &quot;name&quot;: &quot;John Doe&quot;</pre><pre>}</pre><p>This will return the “Hello, John Doe”</p><h3>Notes:</h3><ul><li>make sure you are setting the <strong>Content type</strong> to : <strong>application/json </strong>in the client (postman for me),<br>otherwise the <strong>$request-&gt;input</strong> will not work and you will get ( auth.id is required ) error.</li><li>The whole code i wrote here is not tested so i might have done some typo’s</li><li>If you have any questions , feel free to email me at: <strong>alhasan.nasiry@gmail.com</strong></li><li>Dont forget to change the auth_token when the user changes his password</li><li>add an exception to the <strong>CSRF Protection Middleware </strong>because it wont be needed.<br>you can do that by going to</li></ul><pre>laravel/app/Http/Middleware/VerifyCsrfToken.php</pre><p>and adding</p><pre>protected $except = [<br>     ‘api/*’<br> ];</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a0e45f9106" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>