Commit b72ff507 by Fukász Rómeó Ervin

added authentication, added a test client application

parent a0fda40b
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login
class OcciAuthForm(AuthenticationForm):
def __init__(self, request, *args, **kwargs):
super(OcciAuthForm, self).__init__(*args, **kwargs)
self.request = request
def confirm_login_allowed(self, user):
super(OcciAuthForm, self).confirm_login_allowed(user)
login(self.request, user)
import requests
from requests.exceptions import ConnectionError
import json
import urllib3
# Mivel nincs a devenv-nek SSL tanusitvanya, ezert az urllib3 csomag minden keresnel
# InsecureRequestWarning-ot adna. Ezt elkeruljuk ugy, hogy kikapcsoljuk a
# figyelmezteteseket
# urllib3.disable_warnings()
# A szerver base url-je es a felhasznalo adatai
server = "https://vm.ik.bme.hu:15766/occi/"
username = "admin"
password = "retekretek"
loginData = {"username": username, "password": password}
# Csinalunk egy sessiont, hogy a cookie ami az auth-ert felelos automatikusan benne
# maradjon az osszes keresunkben
with requests.Session() as session:
try:
# Bejelentkezes
headers = {"Content-Type": "application/json"}
req = session.post(server + "login/", data=json.dumps(loginData),
headers=headers, verify=False)
print("login")
print("-----")
print("status_code: " + str(req.status_code))
if req.status_code == 200:
print(json.loads(req.text)["result"])
else:
print(json.loads(req.text)["result"])
errors = json.loads(req.text)["errors"]
for error in errors:
print(error)
print
# Gep ebresztes teszt (meg nem OCCI)
req = session.get(server + "wakeup/", verify=False)
print("wakeup")
print("------")
print("status_code: " + str(req.status_code))
print(req.text)
print
# Gep altatas teszt (meg nem OCCI)
req = session.get(server + "sleep/", verify=False)
print("sleep")
print("-----")
print("status_code: " + str(req.status_code))
print(req.text)
print
# Kijelentkezes
req = session.get(server + "logout/", verify=False)
print("logout")
print("------")
print("status_code: " + str(req.status_code))
print(json.loads(req.text)["result"])
except ConnectionError as e:
print(e)
def set_optional_attributes(self, optional_attributes, kwargs): """ Implementation of the OCCI - Core model classes """
for k, v in kwargs.iteritems():
if k in optional_attributes:
setattr(self, k, v) from occi_utils import set_optional_attributes
class Attribute: class Attribute:
......
""" Implementation of the OCCI - Infrastructure extension classes """
from occi_core import Resource
class Compute(Resource):
""" OCCI 1.2 - Infrastructure extension - Compute """
def __init__(self, vm):
""" Creates a Compute instance of a VM instance object """
self.location = "/compute/%d" % (vm.pk)
self.vm = vm
"""" Utilities for the OCCI implementation of CIRCLE """
def set_optional_attributes(self, optional_attributes, kwargs):
""" Sets the optional arguments of an instance.
If the kwargs dictionary has any values with the keys defined in
the optional_attributes tuple, it sets them on the instance """
for k, v in kwargs.iteritems():
if k in optional_attributes:
setattr(self, k, v)
from django.conf.urls import url from django.conf.urls import url
from views import testView from views import OcciLoginView, OcciLogoutView, WakeUpVM, SleepVM
urlpatterns = [ urlpatterns = [
url(r'^test$', testView.as_view()), url(r'^login/$', OcciLoginView.as_view()),
url(r'^logout/$', OcciLogoutView.as_view()),
url(r'^wakeup/$', WakeUpVM.as_view()),
url(r'^sleep/$', SleepVM.as_view()),
] ]
from django.shortcuts import render """ The views of the OCCI implementation of CIRCLE.
These views handle the http requests of the API. """
from django.views.generic import View from django.views.generic import View
from django.http import HttpResponse from django.contrib.auth import logout
from django.http import HttpResponse, JsonResponse
from vm.models.instance import Instance
from common.models import HumanReadableException
from forms import OcciAuthForm
import json
# TODO: csrf token
class OcciLoginView(View):
""" Authentication for the usage of the OCCI api.
This view responds with 200 and the access token in a Cookie if the
authentication succeeded, and with 400 if the provided username and
password is not valid. """
def get(self, request, *args, **kwargs):
""" Returns a response with a cookie to be used for requests other
than get. """
result = {"result": "OK"}
return JsonResponse(result)
def post(self, request, *args, **kwargs):
data = json.loads(request.body.decode("utf-8"))
""" Returns a response with a cookie to be used for the OCCI api
requests. """
form = OcciAuthForm(data=data, request=request)
if form.is_valid():
result = {"result": "OK"}
return JsonResponse(result)
else:
errors = dict([(k, [unicode(e) for e in v])
for k, v in form.errors.items()])
result = {"result": "ERROR", "errors": errors["__all__"]}
return JsonResponse(result, status=400)
class OcciLogoutView(View):
""" Logout """
def get(self, request, *args, **kwargs):
logout(request)
result = {"result": "OK"}
return JsonResponse(result)
class WakeUpVM(View):
""" A test service which gets a VM to wake up """
def get(self, request, *args, **kwargs):
vm = Instance.objects.get(pk=6)
try:
vm.wake_up(user=request.user)
except HumanReadableException as e:
return HttpResponse(e.get_user_text(), status=400)
return HttpResponse("Virtual machine waked up")
# Create your views here. class SleepVM(View):
# MY VIEWS ARE SOOOO GOOD """ A test service which gets a VM to sleep """
class testView(View):
""" This view is a big test """
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
return HttpResponse('<!DOCTYPE html><html lang="hu"><head>' vm = Instance.objects.get(pk=6)
'<title>TEST</title></head>' try:
'<body style="background: black; color: white' vm.sleep(user=request.user)
'; text-align: center;"><h1>TEST</h1><p>' except HumanReadableException as e:
'Csilli-villi service</p></body></html>') return HttpResponse(e.get_user_text(), status=400)
return HttpResponse("Virtual machine fell asleep")
class startVM(View):
""" A test service, which starts a VM """
class ComputeListView(View):
""" OCCI 1.2 - HTTP protocol - Collections - Compute """
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
pass pass
class ComputeView(View):
pass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment