If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

I needed to authenticate a few pages and JSONRPC service based on IP address of the client. This is what i came up with:

Note: I am using python-IPy to work with IPs. It has support for both IPv4 and IPv6 IPs. Plus it is very simple to use. You can get the module here

 

In the Model :

import IPy #please include IPy in site packages folder

SERVICE_ALLOWED_IPS = ['127.0.0.1','192.168.1.0/24']
PAGE_ALLOWED_IPS =  ['127.0.0.1','192.168.0.0/16']

service_allowed_ips = [IPy.IP(i) for i in SERVICE_ALLOWED_IPS]
page_allowed_ips = [IPy.IP(i) for i in PAGE_ALLOWED_IPS]

def NOT_ALLOWED(*anything):
    return (False,'Error! Your IP ADDRESS is not allowed!')# you could just return False

def service_allowed_ip(f,ips=service_allowed_ips):
    allowed = False
    client_ip = request.client
    for x in ips:
        if client_ip in x: allowed = True
    if allowed == True:
        return f
    else:
        f_name = f.__name__
        f = NOT_ALLOWED # this could be done with a lambda too
        f.__name__ = f_name
        return f

def page_allowed_ip(f,ips=page_allowed_ips):
    allowed = False
    client_ip = request.client
    for x in ips:
        if client_ip in x: allowed = True
    if allowed == True:
        return f
    else:
        redirect(URL('error','ip_not_allowed')

 

Now in any controller which requires IP authentication:

@service.jsonrpc # expose function as jsonrpc function
@service_allowed_ip # to authenticate by IP address
def add(a,b):
    return a + b

Similarly for a Page

@page_allowed_ip
def ip_authenticated_page():
    return dict(message='Hello World!')

I am sure this can be improved. Suggestions are welcome.

Related slices

Comments (2)


Hosting graciously provided by:
Python Anywhere