Subscribe

  • When POSTs suddenly turn into 301 redirects in Rails

    Everything worked fine in my development environment, but when I ran the application from my server every POST would just show the page it was suppost to POST to via GET. Displaying a 301 redirect in Chrome’s developers tools.

    After some fiddling around, I commented line 351 in the .htaccess file:

    <IfModule mod_rewrite.c>
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
      #RewriteRule ^(.*)$ /$1/ [R=301,L] # <-- this one
    </IfModule>
    

    After that everything worked as expected. Weird..

  • Girrst displays your Gists as RSS

    Do you use GitHub’s Gists? Then you might like this.

    Sharing code among co-workers and friends is quite easy using various ‘code snippit’ sharing websites. I personally like GitHub’s Gists. To make sharing even easier and keep everybody up to date of what’s being shared, I wanted to create a feed out of my Gists. Of course I could just use GitHub’s own RSS feeds, but that would screw up my reason to do something with App Engine.

    App Engine

    Using Python and App Engine I threw together a script that will take your GitHub username and turn all your Gists into a convenient RSS feed. You can then use the feed to include it anywhere, like your favorite RSS reader or your blog.

    To make things even easier, use the GitHub bundle for TextMate to be able to create Gists from your favorite editor. Don’t forget to setup your GitHub username and token:

    $ git config --global github.user username
    $ git config --global github.token 0123456789yourf0123456789token
    

    Try it: girrst.appspot.com

  • The Delicious API access over Yahoo OAuth in Ruby on Rails adventure

    I spent a little time today getting Yahoo’s OAuth implementation to work with Omniauth. This seems pretty straightforward, but it isn’t.

    First, what I tried to accomplish:

    1. Have a user sign in with his/her Delicious account
    2. Use the Delicious username to retrieve a bunch of feeds

    Step 1 might seem unnecessary as Delicious’ API only requires authentication to post/update stuff, but I want to store some user settings and stuff. OAuth allows me to use their existing data, instead of creating my own registration process.

    I continued to setup a project in rails, init a Git repo and fill my Gemfile with the gems required for using omniauth plus some extra:

    Gems

    Touch omniauth.rb in config/initializers and the basics for using the Yahoo OAuth provider. Yahoo isn’t supported by default, so we’ll be creating our own strategy later in lib/oauth-strategies/yahoo.rb.

    module OmniAuth
      module Strategies
        autoload :Yahoo, 'lib/oauth-strategies/yahoo'
      end
    end
    
    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :yahoo, 'consumer key', 'consumer secret'
    end
    

    Visit Yahoo’s developer page and create a new project. Choose standard and fill out the rest of the form to match your application. Pay extra attention to Application Domain, enter a url that’s accessible to the outside world. You’ll see why when you’ve completed the form. I’m building a Delicious app so I specified that I require extra user data and choose to have read/write access to Delicious.

    Yahoo Projects

    When you press the Get API Key button, you’re required to upload a file to your server, accessible via the url you’ve just entered under Application Domain. There are three buttons, one of which falsely suggests that you can skip this step. Pressing it will only tell you that you have to do it anyway.. nice. This still gave me the impression that this the whole Application Domain thing was optional, though. Mistake.. I’ll tell you why in a minute.

    Alright, so we’ve completed the form and are presented with our consumer key and consumer secret. Add them to the omniauth.rb configuration.

    Create the folder lib/oauth-strategies and touch yahoo.rb. I tried the default OAuth implementation, didn’t work. After some research on GitHub. I found that there was already a pull request waiting with a Yahoo OAuth strategy, neato. Paste the code into your yahoo.rb strategy file. At this point I was pretty confident that this wouldn’t be a hassle after all. Run bundle install and start your server. Now visit the yahoo auth url at http://localhost:3000/auth/yahoo. The first thing you’ll run into happens when you’re an oldskool Delicious user. This means you’re account is not yet hooked up to your Yahoo account and you’ll get an error saying that you’re login is incorrect. After merging my Delicious and Yahoo accounts, I hoped I had fixed the issue and tried again. Aaaand BAM: “401 Forbidden”. Stumped me at first, but after checking the full response Yahoo told me this: “Custom port is not allowed or the host is not registered with this consumer key”. So I thought I was clever and started the WEBRick server on port 80. No effect, same error.

    Forbidden

    This is when I remembered the Application Domain field.. Yahoo apparently does not like you developing on your localhost, while every other OAuth provider works fine, fuck. So, I setup the whole thing on my server and ran the thing again. Success! It redirects to Yahoo and asks for permission. The callback doesn’t go too well, though. Use this guide to add the route to a custom callback, even though it’s not working yet.

    I started debugging by overriding the callback_phase method and checking out where things started failing. The standard callback_phase method uses name.to_sym to get the name of the provider (yahoo in this case). This didn’t work, so I hardcoded it. Calling super also caused trouble. Long story short, it needed a lot of tweaking.

    Eventually I got it to work, but noticed that the nickname Yahoo OAuth returns is not the one from Delicious.. crap! Luckily Delicious adds the username to it’s authenticated post feeds. Allowing me to grab it and add it to the user profile. The full yahoo.rb now looks like this:

    module OmniAuth
      module Strategies
        class Yahoo >; OmniAuth::Strategies::OAuth
        unloadable
    
        def initialize(app, consumer_key, consumer_secret)
            super(app, :yahoo, consumer_key, consumer_secret,
                  :site               => "https://api.login.yahoo.com",
                  :request_token_path => "/oauth/v2/get_request_token",
                  :authorize_path     => "/oauth/v2/request_auth",
                  :access_token_path  => "/oauth/v2/get_token"
            )
          end
    
          def callback_phase
            request_token = ::OAuth::RequestToken.new(consumer, session[:oauth][:yahoo].delete(:request_token), session[:oauth][:yahoo].delete(:request_secret))
            @access_token = request_token.get_access_token(:oauth_verifier => request.params['oauth_verifier'])
    
            @env['omniauth.auth'] = auth_hash
            call_app!
    
          rescue ::OAuth::Unauthorized => e
            fail!(:invalid_credentials, e)
          end
    
          def auth_hash
            OmniAuth::Utils.deep_merge(super, {
              'uid' => @access_token.params[:xoauth_yahoo_guid],
              'user_info' => user_info,
              'extra' => {'user_hash' => user_hash}
            })
          end
    
          def user_info
            user_hash
            profile = user_hash['profile'] || {}
            username = Nokogiri::XML::parse(@access_token.get("http://api.del.icio.us/v2/posts/recent?count=1").body).root['user']
            {
              'nickname'    => username,
              'name'        => "%s %s" % [profile['givenName'], profile['familyName']],
              'location'    => profile['location'],
              'image'       => (profile['image'] || {})['imageUrl'],
              'description' => nil,
              'urls'        => {'Profile' => profile['uri']}
            }
          end
    
          def user_hash
            @user_hash ||= MultiJson.decode(@access_token.get("http://social.yahooapis.com/v1/user/#{@access_token.params[:xoauth_yahoo_guid]}/profile?format=json").body)
          end
    
       end
      end
    end
    

    Alright, everything is setup to work marvelously with ASCIIcast’s guide, which explains how to allow users to sign in with OAuth and remain logged in until they decide to sign out. Thanks to Yahoo for adding some pitfalls (some of which I probably forgot to describe) here and there to keep things interesting.

    *note to self: install pretty code plugin for WordPress.. EDIT: Done!

  • WordPress Project Creator

    Working on WordPress projects can be a hassle. Especially if there’s more than one developer. There are a lot of files and chances are huge that you’ll be working on the same files quite often. This slows down development tremendously, not to mention the annoyance it causes.

    You can fix the ‘working on the same file’ and ‘working on the live server’ issues quite adequately by using version control. I prefer Git, because of it’s distributed character. WordPress has another issue however, when trying to run the same site on different machines. Among the data it stores are urls, absolute urls.. This means that if you’d load a database dump from a live WordPress site into your local install, nothing will work correctly.

    WordPress Project Creator [github] is a tool I created to streamline working on WordPress projects with multiple people. It does a couple of things:

    • Download WordPress
    • Create a new Git repo out of your wp-content folder or clone an existing wp-content folder into the WordPress folder
    • Easily import database dumps by alterering absolute urls
    • Create wp-config.php file
    • Create .htaccess file

    Adding new developers to your project is as easy as allowing them access to the Git repo and running wpprojectcreator. If you clone an existing project, the only things you’ll have to do is run the python script, import the dump using setup.php and you’re ready to work on the website as if it were live.

    Wordpress Project Creator

    I released it on GitHub so everyone can give it a go. Or everyone.. at least everyone running OSX, Linux or 32bit Windows. Git on 64bit Windows can’t be installed in such a way that it’s accessible from the command line, which is required by wpprojectcreator. Be sure to read the README .

    Check out WordPress Project Creator on GitHub.

  • New internet technology: use what’s already out there

    I’ve had this article on my computer for three months now, but never got around to finishing it. Finally found some time to put it up.

    It’s interesting to see that the standard process of thinking of something new, trying to figure out how to make money from it, creating it and then releasing it to the public seems to have changed. A business model does not necessarily come first anymore. A new process could be described similar to this: have an idea, create a very basic implementation and provide an extensive platform for people to use what you’ve created, hand it over to the community, now find a way to make money or hope for a takeover by some enterprise (Google). This makes new technology much more accessible than it’s ever been. A lot of effort is put into making it easy for other people to use and mashup what’s been created.

    Detect and use

    Needless to say a skill that’s becoming increasingly useful, is the ability to detect these services and find ways to implement them in your own concepts. YouTube, Twitter and Flickr have all been fully embraced by the community, which means the movies, images and messages they store show up on all kinds of applications. Some with a lot easier business model than the services they’ve incorporated. Twitter clients for instance, have a price tag or use adds to turn a profit, while Twitter is still struggling to find a way to make money.

    Reasons to use public API’s

    Does that mean Twitter is in trouble? Probably not, what they have is data and a lot of people who use that data. Apparently that’s worth multi million dollar investments. Money they need to provide a reliable system and store data the client applications are generating. Which is awesome, because you don’t have to worry about that anymore. It means you could create fairly extensive applications with a minimal amount of effort, as the services provide you with a solid backend.

    Maybe the biggest benefit is popularity and content. It’s easier to use an existing user base than to create your own. Let’s say you want to create a website about the Olympic Games. You want visitors to contribute text, photos and videos. This would require quite a lot of work to create from scratch. Incorporating Twitter, Flickr and YouTube would reduce that dramatically. More importantly however, it would generate a lot more content, as it allows your audience to use the tools they’re already accustomed to.

    What you have to take in consideration though, is that you’re not in direct control of the content you’re provided with. This may seem daunting at first and it makes the use of services unsuitable for some applications. It takes a new way of moderating the content you’re provided with. Both YouTube and Flickr allow you to only search through video’s and images that are marked safe. Other than that, it’s always a good idea to think about how you can stay in control of your own application.

    Start your own projects

    The list of services that are available right now seems endless. Some are more successful than others, obviously. Like I said, popularity is a good measure to determine if a service is worth checking out. To get you started, Programmable Web keeps an incredible list of public API’s. I’ve been spending a lot of time with the Google Apps API’s lately, which are pretty awesome and really allow for some cool applications. Especially if you look further than mashing up some of the individual components. For instance, it’s very easy to use Google Spreadsheet as a cloud database. How neat is that :)? Anyway, have fun!