Reequiring login for a static file

47 views
Skip to first unread message

Dave S

unread,
Aug 29, 2019, 4:27:17 AM8/29/19
to web2py-users
I have a file that I want authorized users to be able to download, but I'm not sure I want it in the uploads directory (so that user/download can find it).  I'm thinking about putting it in static, but I realize that doesn't default to secure (well, many static files are needed by the login page, for example).

Is there an easy way, say with routes.py, to require login for a specific static file, or is the check_access() technique in the book and in <URL:https://groups.google.com/d/msg/web2py/3rEQJ9SfIWo/8SEH-bPxAAAJ> the way to do this (using nginx with a very specific pattern)?

/dps


Massimo Di Pierro

unread,
Sep 1, 2019, 10:28:05 PM9/1/19
to web2py-users
By definition static files have no authorization because we recommend they being served directly by the web server bypassing web2py entirely.

You can put then in a myfiles subfolder of the app and create your own action:

@auth.requires_login()
def static():
     import contenttype
     filename = os.path.join(request.folder, 'myfiles', '/'.join(rqeuest.args))
     response.headers['Content-Type'] = contenttype.contenttype(filename)
     if not user_permissions(auth, filename): # <-- you implement this
          raise HTTP(401)
     if not os.path.exists(filename):
          raise HTTP(404)    
     with open(filename) as fp:
          return fp.read()

Dave S

unread,
Sep 3, 2019, 3:12:36 AM9/3/19
to web2py-users


On Sunday, September 1, 2019 at 7:28:05 PM UTC-7, Massimo Di Pierro wrote:
By definition static files have no authorization because we recommend they being served directly by the web server bypassing web2py entirely.

You can put then in a myfiles subfolder of the app and create your own action:

@auth.requires_login()
def static():
     import contenttype
     filename = os.path.join(request.folder, 'myfiles', '/'.join(rqeuest.args))
     response.headers['Content-Type'] = contenttype.contenttype(filename)
     if not user_permissions(auth, filename): # <-- you implement this
          raise HTTP(401)
     if not os.path.exists(filename):
          raise HTTP(404)    
     with open(filename) as fp:
          return fp.read()


That is essentially what I ended up doing (with the minor change of using a stream),  I haven't gotten around to hotwiring the static files into the frontend (missed that comment in "deployment"), but I did think about it and using the frontend to handle that authentication, but decided not to wait for my learning curve.

Thanks.

/dps
Reply all
Reply to author
Forward
0 new messages