如何做与openstack对接的用户验证

可以在openstack horizon中加一个文件夹Security,里面按照horizon的要求放置好子目录和文件。


nsfocus@controller:/usr/src/horizon$ ls
build  HACKING.rst  horizon.egg-info  Makefile   MANIFEST.in            openstack_dashboard  requirements.txt  security   setup.py  test-requirements.txt  tox.ini
doc    horizon      LICENSE           manage.py  openstack-common.conf  README.rst           run_tests.sh      setup.cfg  static    tools
nsfocus@controller:/usr/src/horizon$ cd security/
nsfocus@controller:/usr/src/horizon/security$ ls
ads     appmanager  byod          dashboard.pyc  flowviewer  __init__.py   knowledge       misc       models.pyc    static     waf
adsapp  assetcheck  dashboard.py  devicemanager  ids         __init__.pyc  liveprotection  models.py  moduleviewer  templates  webprotection
nsfocus@controller:/usr/src/horizon/security$ vi liveprotection/
__init__.py   __init__.pyc  panel.py      panel.pyc     templates/    urls.py       urls.pyc      views.py      views.pyc
查看liveprotection/view.py
from django.core.urlresolvers import reverse_lazy # noqa 
from django.utils.translation import ugettext_lazy as _ # noqa 
from horizon import tables 
from horizon import exceptions 
from openstack_dashboard import api 
from django.http import HttpResponse 
from django.template import RequestContext, loader 
from horizon import forms def index(request): template_name = 'security/liveprotection/index.html' 
template = loader.get_template(template_name) context = RequestContext(request, { 'target': 'http://liveprotection.research.intra.nsfocus.com:8000/?username=%s&token=%s'%(request.user,request.user.token.id), }) 
return HttpResponse(template.render(context))

在liveprotection页面中,处理函数为:

def index(request):
    print request.GET
    error = None
    username = auth.verify(request)
    if username is None:
        error = "You are not logined in"
    return render_to_response("routers.html")

from datetime import datetime
import time
import client

import iso8601
def parse_isotime(timestr):
    """Parse time from ISO 8601 format."""
    try:
        return iso8601.parse_date(timestr)
    except iso8601.ParseError as e:
        raise ValueError(six.text_type(e))
    except TypeError as e:
        raise ValueError(six.text_type(e))

def valid_token(expires):
    #return datetime.now() > time.replace(tzinfo=None)
    now = time.time()
    return now < expires

def verify(request):

    token = None
    expire = None
    username = None
    verified_username = None

    if request.session.has_key("token"):
        token = request.session["token"]
    if request.session.has_key("expires"):
        expires = request.session["expires"]
    if request.session.has_key("username"):
        username = request.session["username"]

    if not token is None :
        if valid_token(expires):
            return username
    print 'session :%s' %request.session
    print 'Get :%s'%request.GET
    token =request.GET.get('token')
    username =request.GET.get('username')
    print 'username :%s'%username
    if token is None or username is None:
        return None
    headers = {
        "X-Auth-Token": token,
        }
    code, data = client.http_request(url="http://192.168.19.1:35357/v2.0"+"/tokens/"+token+"?belongsTo", headers=headers)
    print '__________________________++++++++++++++++++++++++_____________________'
    print data
    if code != "200":
        valid = 0
        print "token invalid: return code:%s" % code
    else:
        expires_dt = parse_isotime(data["access"]["token"]["expires"])
        expires_dt = expires_dt.replace(tzinfo=None)
        expires = long(time.mktime(expires_dt.timetuple()))

        verified_username = data["access"]["user"]["username"]
        if valid_token(expires):
            valid = 1
        else:
            valid = 0

    print 'valid :%d'%valid
    print 'token :%s'%token
    if valid:
        request.session["username"] = verified_username
        request.session["token"] = token
        request.session["expires"] = expires
    return verified_username

Leave a Reply

Your email address will not be published. Required fields are marked *