Posts Tagged ‘cakephp’

How to limit user access in CakePHP: findMy

May 7th, 2010

Perhaps like many people starting a CakePHP project, I created a site where users could log in and create/modify their own files (in my case Japanese flashcards and tests) while not being able to screw with other people’s stuff.

One would think that you could solve this with some nifty ACL and Auth work, but if you thought that, then you would be wrong.

Unforunately ACL only lets you determine what actions a user is allowed to perform, not on which items they’re allowed to perform it.

And Auth only checks to make sure a person is logged in, not who they are or what they’re doing.

The Traditional Way

However, thanks to the glory of cake, it’s not that hard to limit a search by user! Just replace your find with the following function.

$my_file = $this->SomeModel->findAllByUserId($this>Auth->user(id);

And we’re done!

Oops! Not so fast!

We just got all of the SomeModels! Well crap, I guess we’ll have to make an option array

$opt = array(
   'conditions' => array(
      'SomeModel.user_id' => $this->Auth->user('id'),
   ),
   'order' => 'SomeModel.date DESC',
);
$my_file = $this->SomeModel->find('first', $opt);

That’s a lot of work for just getting my latest SomeModel. Even more work if I have to replace every instance of a simple find with something like that. I also need to do the same thing for every save and delete as well to make sure that they’re not saving over someone else’s data.

Sure, I could put that code throughout all my Controllers, but that’s messy — and if I forget to put it somewhere someone gets their data deleted.

So what can we do?

Well, I don’t know about you, but I put a function in my AppModel file that lets me easily make sure that whoever’s touching the file has permission to do so.

function findMy($type, $options=array())
{
   if($this->hasField('user_id') && !empty($_SESSION['Auth']['User']['id'])){
      $options['conditions'][$this->alias.'.user_id'] = $_SESSION['Auth']['User']['id'];
      return parent::find($type, $options);
   }
   else{
      return parent::find($type, $options);
   }
}

What this does

  1. Make sure that the model has an ‘user_id’ field
  2. Make sure that the user is logged in
  3. Add the user_id condition to the find options
    • Be sure to use the $this->alias in case you’re using an alias for the Model in a BelongsTo or HasMany relationship.
  4. Find the data

This is a pretty simple function, and can form the base for any logic that you want to do.

For example, if you want to allow Admins to view anything, just add an $_SESSION['Auth']['User']['role'] == ‘admin’ to the mix.

If you want to allow users access to any ‘public’ items, add a condition for ‘OR is_public == true’

Extending the function

This function is set in the AppModel, so it can be overridden in any of your defined models if you need to do any custom filtering on a per-model basis.

Also, it is possible to extend this to save and delete functions, to make sure that users are only saving or deleting their own files. If they try to delete a file that doesn’t belong to them, return false and alert the user that that file could not be found.

function deleteMy($id = null, $cascade = true)
{
   if (!empty($id)) {
      $this->id = $id;
   }
   $id = $this->id;

   if($this->hasField('user_id') && !empty($_SESSION['Auth']['User']['id'])){
      $opt = array(
         'conditions' => array(
            $this->alias.'.user_id' => $_SESSION['Auth']['User']['id'],
            $this->alias.'.id' => $id,
            ),
         );
      if($this->find('count', $opt) > 0){
         return parent::delete($id, $cascade);
      }
      else{
         return false;
      }

   }
   else
      return parent::delete($id, $cascade);
}

Conclusion

The power of CakePHP comes from it’s infinite extensibility, and the fact that at it’s core, it’s still just a PHP program.

While I recommend following MVC practices, and to use the built-in CakePHP functions as much as possible, there are times when you just need to do it the simple way.

Also, for those who balk at my use of $_SESSION, I talked with one of the CakePHP core developers at a conference a while ago, and was asking him about this problem.

I asked,

“Why is Auth only available in controllers? It would be much more useful if we could use it everywhere. Is it a design decision?”

He replied.

“Because it’s a component. That’s the only reason.”

Remember: the framework is there to help you. You are not its slave.

Taking the pain out of CakePHP deployment: Batch Scripts and SVN

April 23rd, 2010

If you take a look at the update rate of this blog, or the wait time on my email responses, or even the changelogs from my Subversion repository, you will notice one thing — I am a horrible procrastinator.

Well, not actually true. I’m a great procrastinator.

I found out a long time ago that something I think will take 10 minutes ends up taking an hour, and things I think will take an hour end up taking 10 minutes. The downside to this thought pattern is that it makes it hard for me to start anything I know that I can’t get done in 1 minute, unless I have a lot of time to kill on it.

The more steps there are to a process, the less likely I am to feel that I can get it done in the small amount of time I have allowed.

What is the process for deploying a project with CakePHP?

The process for deploying a cakePHP website is monotonous enough, but at the same time contains enough fiddly bits to be annoying to do more than once in a blue moon.

  1. Export the data from the SVN to the directory of your choice (dev or live in my case)
  2. If you’re anal about keeping logs of what you exported (like me), write the version info to a file.
  3. Update the config file so that your local version (which is probably running in debug 1 or 2) runs without debug info.
  4. Remove all the old cache data in case you made any changes to your models
  5. Done

Kind of a pain in the rear.

And we all know what are great for repetitive tasks with lots of fiddly steps that are a pain in the rear:

Enter the bash file

I created a simple batch file that I can run directly on my SliceHost server. It allows me to deploy a specific folder from my SVN, pick whether to deploy to the dev site or the live site, clear the cache, and set the debug settings.

Now let’s do it in one line

./deploy live app

Done.

Here’s what comes out the other end:

Setting LIVE
.....
Lots of SVN Export Data
.....
Reset Config File: [livesite]/app/config/core.php
Cleared out Cache

This gives me a sense of security when updating my site, because I know that I won’t have forgotten any of the tiny repetitive details, and can fill my deploy checklist with more important things (such as “Check that users can login”) instead of “Set Debug to 0.”

Here’s the Code

I know, I know. All you want is the code. Well here you go. Feel free to edit and use as you like, but be sure to set your svn and target paths.

#!/bin/sh
# usage: ./deploy TYPE DIR
# TYPE = live | (anything else)
#
# Be sure to edit the following:
# _MY_SVN_DIR_ -- the base SVN dir for this project
# _MY_LIVE_PATH_ ex: /home/ippatsu/japanesetesting.com/public
# _MY_DEV_PATH_ ex: /home/ippatsu/beta.japanesetesting.com/public

# Set as Life or Dev
if [ "$1" != "live" ]; then
echo "Setting DEVsite"
TARGETP="_MY_DEV_PATH_"
else
echo "Setting LIVE"
TARGETP="_MY_LIVE_PATH_"
fi

# Export Data
svn export --force svn://127.0.0.1/_MY_SVN_DIR_/$2  $TARGETP/$2

# Write Version to File
svn info svn://127.0.0.1/_MY_SVN_DIR_/$2 > $TARGETP/version.txt
svn info svn://127.0.0.1/_MY_SVN_DIR_/$2

# Update Config File
OLD="Configure::write('debug', 2);"
NEW="Configure::write('debug', 0);"
CONFIGFILE="$TARGETP/app/config/core.php"

sed -i "s/$OLD/$NEW/g" $CONFIGFILE
echo "Reset Config File: $CONFIGFILE"

# Clearout Cake Model Cache
rm $TARGETP/app/tmp/cache/models/cake*
rm $TARGETP/app/tmp/cache/persistent/cake*
rm $TARGETP/app/tmp/cache/views/cake*
echo "Cleared out Cache"

exit 0

Hope you enjoy it, and if you have any advice or questions, just leave them in the comments!

The Programmer’s Folly: Simple is best

November 24th, 2009

First, let me get this out in the open: I am not a marketer. I am not a content-organizer. I am a programmer. I like writing code, and I like creating new ways to do things. I like making things because it helps me see how they work — out-of-the-box-solutions bore me.

And that’s where I screw up

On Monday it was a national holiday here in Japan (勤労感謝の日) and I had about 4 hours to kill while the wife was out on her daily walk. I decided to work on my site — and what I needed more than anything was a nice heatmap to log user clicks.

I used the amazing ClickHeat which is a free heat-mapping application written in PHP. It works right out of the box, is amazingly configurable, and runs quickly thanks to it being written in clear PHP.

Wouldn’t this be great as a CakePHP Plugin!

This is where things start to get messy.

I love CakePHP. It makes development easy, is rather fast, and is highly extensible. So, I decided to wrap the ClickHeat application in a cake plugin, make it “easy to integrate” and put it in the CakePHP Bakery, instantly receiving fame, fortune and the accolades of my peers!

4 hours later

I had a mostly-working prototype that logged the data beautifully (although I couldn’t decide how to group the data on a dynamic site),  but didn’t have any of the nifty functions of the ClickHeat software such as sorting by date, admin panels, etc. because I hadn’t built those views yet. But I was hopeful!

Then my wife came home and I stopped programming for the day.

The next day, in 10 minutes

I decided to install ClickHeat on one of my corporate sites at work.

  1. Copy ClickHeat folder
  2. Set Cache & Log permissions
  3. Turn on Japanese Interface
  4. Done

10 minutes. In ten minutes I had accomplished what I couldn’t complete in 4 hours, because I was prepared to use an out-of-the-box solution instead of trying the be the programming bad-ass and integrate it with CakePHP.

So this morning, I copied the folder to my CakePHP dir, made one change to the .htaccess file:

RewriteRule    clickheat/(.*)   -   [L]

And now I have working heatmaps on my site. (I also put them on my wordpress blog, so that you can see them in action for yourself).

See the amazing Japanese Programming Heatmaps! (User: demo / Password: demo)

The final Score

So, what’s the final score?

Being a “bad-ass” programmer

  1. 4 Hours Development
  2. 1 extra hour of planning before sleep
  3. No Viewing Functionality
  4. Installation NOT user friendly
  5. Call time of 300ms per click for spinning up the cake processor
  6. Logging Works

Being a smart programmer

  1. 1 Change in my htaccess file
  2. 10 minutes to install/configure
  3. Call time of 150ms / click
  4. Not following “best practices” for cakephp

I think it’s pretty obvious what the best choice here is.

While I adore CakePHP and the things it lets you do simply by following convention — it’s very easy to get sucked into the “Best Practice” mindset, and waste a lot of time working on something that honestly doesn’t need to be tinkered with.

Don’t re-invent the wheel

It’s amazing how many times you can read that phrase and still find yourself re-inventing wheel after wheel after wheel. If you have a tool that does a job — use it. Do not worry about your fiddly code, and your “it’s not made here” mentality.

If the application is LACKING you can always edit it. But it makes no sense to start with something that does everything that you want, and then try to hack it apart just because you can. (Although I have to admit, it can be fun)

With those four hours, I could have

  • written 1 article for my site,
  • uploaded around 10 flashcard packs
  • added 2 tests to the site
  • read a book
  • played a lot of video games
  • watched a movie
  • watched four (4) episodes of Doctor Who or The Green Wing.

So Keith, this is a message to you:

  • Don’t be a tool
  • Use your time wisely
  • If something works, do NOT break it just because you want to see how it works.
  • (Eat your veggies — love mom)

CakePHP DebugKit: Take Back your Debugging

November 12th, 2009

Yet another foray into the WORD: The Subtitle blog posts; today we’re going to look at the amazing features of the CakePHP DebugKit.

The DebugKit is a standard plugin for CakePHP written by Mark Story. It provides a lot more information that the standard debugging features of cake (Errors, warnings, SQL Queries) and also keeps them in a nice contained collapsible icon at the top of your page so you don’t have to have error messages and sql queries appearing all over the page.

The Debug Kit Interface

DebugKit Icon

DebugKit Icon

Click the Cake icon at the top of your page, and it expands to all the tools you’ll need.

DebugKit Expanded

DebugKit Expanded

If you click any of the titles there, it shows you various debug information such as the current Session information, how the Request was processed, the SQL Log, a timer for all the functions that were called, currently accessible variables and the current memory usage.

DebugKit Variables View

DebugKit Variables View

DebugKit Timer View

DebugKit Timer View

All in all, an amazing amount of information. And best of all? It stays out of the way so your designs don’t get cluttered with debug information while you’re testing.

Installation

Installation is easy.

Download

Download the debug kit from ohloh. http://www.ohloh.net/p/cakephp-debugkit

Install

Place the DebugKig in the plugins folder of your application:

/app/plugins/debug_kit/[INSERT ME HERE]

Connect

Add the DebugKit Toolbar component to your app_controller, so it will be available to all your controllers.


// app_controller.php
var $components = array('DebugKit.Toolbar');

Then set the debug mode to at least 1.

Problems

DebugKit isn’t a perfect system (or maybe my understanding of it isn’t quite perfect). In any case, these are some problems I’ve had with DebugKit, but even they’re not enough to really gripe about.

Speed

DebugKit does seem to take a lot more processing power to run it than the standard Debug functions of cake.

This is easy to understand, though, as with the timers, reporters and everything, it’s doing quite a bit more than the standard Debug functions, and gives you a lot more information. I’ve had my dev-laptop exceed the 30sec execution time limit quite a few times while running DebugKit, but nothing like that has ever happened on my dev-server, so I doubt it’s anything major. It does make navigation a bit slower though, so when testing user flow, I would recommend turning it off by setting the Debug level to 0 for the duration of the session.

And remember, if you switch your debug to 0, then the DebugKit isn’t run at all, so there’s no worries about it eating precious resources on your live server.

Ajax Reporting

Ajax doesn't seem to be affected

Ajax doesn't seem to be affected

When you make a request with Ajax, the DebugKit doesn’t seem to get spun up like it should — which results in it reverting to the standard CakePHP reporting, which (while not bad) is definitely a grade down compared to the glory of DebugKit. It would have been nice to have the reporting fed into another icon inside the div that displays the ajax result, or something to that effect. Perhaps there is a way, and I just haven’t found it yet. Always a possibility.

Conclusion

Really, there isn’t much else to say except: why are you waiting? Go download this thing now!