Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving static files with authentication in the playframework

Is there an easy/build-in way to have a controller check if a connection is authorized to access a static file not the server (with the use of a DB lookup) and then provide access if needed.

There are large video files, and I want a) check if the user is allowed to access the file, and b) if the user is authorized I want to record that the video has been watched.

like image 794
Luuk D. Jansen Avatar asked Jun 02 '26 16:06

Luuk D. Jansen


1 Answers

There are two ways of doing this.

The first and most elegant way of doing it would be using the Play Plugin feature.

You can find more info at How to extend the playframework? Here is the javadoc: http://www.playframework.org/documentation/api/1.2.3/play/PlayPlugin.html

The second would be to serve the files from a route

If the files are route/controller based then you can just protect them like you would any other controller. Someone correct me if I'm wrong.

I would do something like (note this code has not been tested):

protect with @With(Secure.class)

public static void getImage() {
    File file = new File( "~/image.png" );
    response.contentType = "image/png";
    renderBinary( file );
}

Then the route

GET     /static/image1    Application.getImage

Or you could make it more elegant.

GET     /static/image/{fileName}   Application.getImage
GET     /static/image/{id}         Application.getImageById

and

   public static void getImage(String fileName) {
        File file = new File( "~/" + fileName );
        response.contentType = "image/png";
        renderBinary( file );
    }

Or take it further.

public static void getImage( String fileName, String username ) {
    File file = new File( "~/" + fileName );

    if ( file.exists() ) {
        User user = User.find( "byName", username ).fetch();
        user.watch = true;
        user.save();

        response.contentType = "image/png";
        renderBinary( file );
    }
}

Obviously you would need some trys and catches in there if the file didn't exist.

Good luck.

like image 113
Drew H Avatar answered Jun 05 '26 12:06

Drew H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!