Merge branch 'nico/meow-pay-master' into HEAD

This commit is contained in:
ahmadbilalkhalid 2020-02-23 20:25:35 +05:00
commit e4f2f446f5
75 changed files with 573 additions and 182 deletions

3
uncloud/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
db.sqlite3
uncloud/secrets.py
debug.log

47
uncloud/README.md Normal file
View file

@ -0,0 +1,47 @@
## Install
### OS package requirements
Alpine:
```
apk add openldap-dev postgresql-dev
```
### Python requirements
If you prefer using a venv, use:
```
python -m venv venv
. ./venv/bin/activate
```
Then install the requirements
```
pip install -r requirements.txt
```
### Database requirements
Due to the use of the JSONField, postgresql is required.
First create a role to be used:
```
postgres=# create role nico login;
```
Then create the database owner by the new role:
```
postgres=# create database uncloud owner nico;
```
### Secrets
cp `uncloud/secrets_sample.py` to `uncloud/secrets.py` and replace the
sample values with real values.

21
uncloud/manage.py Executable file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uncloud.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

View file

View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class OpennebulaConfig(AppConfig):
name = 'opennebula'

View file

@ -0,0 +1,42 @@
import os
import json
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from xmlrpc.client import ServerProxy as RPCClient
from xmltodict import parse
from opennebula.models import VM as VMModel
import uncloud.secrets
class Command(BaseCommand):
help = 'Syncronize VM information from OpenNebula'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
with RPCClient(uncloud.secrets.OPENNEBULA_URL) as rpc_client:
success, response, *_ = rpc_client.one.vmpool.infoextended(
uncloud.secrets.OPENNEBULA_USER_PASS, -2, -1, -1, -1
)
if success:
vms = json.loads(json.dumps(parse(response)))['VM_POOL']['VM']
for i, vm in enumerate(vms):
vm_id = vm['ID']
vm_owner = vm['UNAME']
try:
user = get_user_model().objects.get(username=vm_owner)
except get_user_model().DoesNotExist:
user = get_user_model().objects.create_user(username=vm_owner)
VMModel.objects.update_or_create(
defaults= { 'data': vm,
'owner': user },
vmid=vm_id
)
else:
print(response)

View file

@ -0,0 +1,26 @@
# Generated by Django 3.0.3 on 2020-02-23 10:02
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='VM',
fields=[
('vmid', models.IntegerField(primary_key=True, serialize=False)),
('data', django.contrib.postgres.fields.jsonb.JSONField()),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View file

@ -0,0 +1,19 @@
# Generated by Django 3.0.3 on 2020-02-23 10:55
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('opennebula', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='vm',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False),
),
]

View file

@ -0,0 +1,19 @@
# Generated by Django 3.0.3 on 2020-02-23 10:58
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('opennebula', '0002_vm_uuid'),
]
operations = [
migrations.AlterField(
model_name='vm',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
),
]

View file

@ -0,0 +1,23 @@
# Generated by Django 3.0.3 on 2020-02-22 07:13
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('opennebula', '0003_auto_20200221_1113'),
]
operations = [
migrations.RemoveField(
model_name='vm',
name='id',
),
migrations.AddField(
model_name='vm',
name='uuid',
field=models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False),
),
]

View file

@ -0,0 +1,50 @@
import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import JSONField
class VM(models.Model):
vmid = models.IntegerField(primary_key=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
data = JSONField()
@property
def cores(self):
return int(self.data['TEMPLATE']['VCPU'])
@property
def ram_in_gb(self):
return (int(self.data['TEMPLATE']['MEMORY'])/1024.)
@property
def disks(self):
"""
If there is no disk then the key DISK does not exist.
If there is only one disk, we have a dictionary in the database.
If there are multiple disks, we have a list of dictionaries in the database.
"""
disks = []
if 'DISK' in self.data['TEMPLATE']:
if type(self.data['TEMPLATE']['DISK']) is dict:
disks = [ self.data['TEMPLATE']['DISK'] ]
else:
disks = self.data['TEMPLATE']['DISK']
disks = [
{
'size_in_gb': int(d['SIZE'])/1024. ,
'opennebula_source': d['SOURCE'],
'opennebula_name': d['IMAGE'],
}
for d in disks
]
return disks

View file

@ -0,0 +1,14 @@
from rest_framework import serializers
from opennebula.models import VM
class VMSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = VM
fields = ['vmid', 'owner', 'data']
class OpenNebulaVMSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = VM
fields = ['vmid', 'owner', 'cores', 'ram_in_gb', 'disks' ]

View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View file

@ -0,0 +1,22 @@
from rest_framework import viewsets, generics, permissions
from .models import VM
from .serializers import VMSerializer, OpenNebulaVMSerializer
#class VMList(generics.ListAPIView):
# queryset = VM.objects.all()
# serializer_class = VMSerializer
class RawVMViewSet(viewsets.ModelViewSet):
# lookup_field = 'vmid'
queryset = VM.objects.all()
serializer_class = VMSerializer
permission_classes = [permissions.IsAuthenticated]
class VMViewSet(viewsets.ModelViewSet):
queryset = VM.objects.all()
serializer_class = OpenNebulaVMSerializer
permission_classes = [permissions.IsAuthenticated]

5
uncloud/requirements.txt Normal file
View file

@ -0,0 +1,5 @@
django
djangorestframework
django-auth-ldap
stripe
xmltodict

1
uncloud/uncloud/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
secrets.py

View file

16
uncloud/uncloud/asgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
ASGI config for uncloud project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uncloud.settings')
application = get_asgi_application()

View file

@ -0,0 +1,12 @@
# Live/test key from stripe
STRIPE_KEY = ''
# XML-RPC interface of opennebula
OPENNEBULA_URL = 'https://opennebula.ungleich.ch:2634/RPC2'
# user:pass for accessing opennebula
OPENNEBULA_USER_PASS = 'user:password'
AUTH_LDAP_BIND_DN = 'something'
AUTH_LDAP_BIND_PASSWORD = r'somepass'

199
uncloud/uncloud/settings.py Normal file
View file

@ -0,0 +1,199 @@
"""
Django settings for uncloud project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
import stripe
import ldap
import uncloud.secrets as secrets
from django_auth_ldap.config import LDAPSearch
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'dx$iqt=lc&yrp^!z5$ay^%g5lhx1y3bcu=jg(jx0yj0ogkfqvf'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'uncloud_api',
'uncloud_auth',
'opennebula'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'uncloud.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'uncloud.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
################################################################################
# AUTH/LDAP
AUTH_LDAP_SERVER_URI = "ldaps://ldap1.ungleich.ch,ldaps://ldap2.ungleich.ch"
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=customer,dc=ungleich,dc=ch"
AUTH_LDAP_BIND_DN = secrets.AUTH_LDAP_BIND_DN
AUTH_LDAP_BIND_PASSWORD = secrets.AUTH_LDAP_BIND_PASSWORD
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"ou=customer,dc=ungleich,dc=ch", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
)
################################################################################
# AUTH/Django
AUTHENTICATION_BACKENDS = [
"django_auth_ldap.backend.LDAPBackend",
"django.contrib.auth.backends.ModelBackend"
]
AUTH_USER_MODEL = 'uncloud_auth.User'
################################################################################
# AUTH/REST
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
]
}
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
stripe.api_key = secrets.STRIPE_KEY
<<<<<<< HEAD:nicohack202002/uncloud/uncloud/settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'debug.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
'django_auth_ldap': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True
}
},
=======
# Uncommitted file with secrets
import uncloud.secrets
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': uncloud.secrets.POSTGRESQL_DB_NAME,
}
>>>>>>> nico/meow-pay-master:uncloud/uncloud/settings.py
}

55
uncloud/uncloud/stripe.py Normal file
View file

@ -0,0 +1,55 @@
import stripe
def handle_stripe_error(f):
def handle_problems(*args, **kwargs):
response = {
'paid': False,
'response_object': None,
'error': None
}
common_message = "Currently it's not possible to make payments."
try:
response_object = f(*args, **kwargs)
response = {
'response_object': response_object,
'error': None
}
return response
except stripe.error.CardError as e:
# Since it's a decline, stripe.error.CardError will be caught
body = e.json_body
err = body['error']
response.update({'error': err['message']})
logging.error(str(e))
return response
except stripe.error.RateLimitError:
response.update(
{'error': "Too many requests made to the API too quickly"})
return response
except stripe.error.InvalidRequestError as e:
logging.error(str(e))
response.update({'error': "Invalid parameters"})
return response
except stripe.error.AuthenticationError as e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
logging.error(str(e))
response.update({'error': common_message})
return response
except stripe.error.APIConnectionError as e:
logging.error(str(e))
response.update({'error': common_message})
return response
except stripe.error.StripeError as e:
# maybe send email
logging.error(str(e))
response.update({'error': common_message})
return response
except Exception as e:
# maybe send email
logging.error(str(e))
response.update({'error': common_message})
return response
return handle_problems

47
uncloud/uncloud/urls.py Normal file
View file

@ -0,0 +1,47 @@
"""uncloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from uncloud_api import views
from opennebula import views as oneviews
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'opennebula', oneviews.VMViewSet)
router.register(r'opennebula_raw', oneviews.RawVMViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls),
path('products/', views.ProductsView.as_view(), name='products'),
<<<<<<< HEAD:nicohack202002/uncloud/uncloud/urls.py
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('opennebula/vm/list/', oneviews.VMList.as_view(), name='vm_list'),
path('opennebula/vm/detail/<int:vmid>/', oneviews.VMDetail.as_view(), name='vm_detail'),
path('vm/list/', oneviews.UserVMList.as_view(), name='user_vm_list'),
=======
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
# path('vm/list/', oneviews.VMList.as_view(), name='vm_list'),
# path('vm/detail/<int:vmid>/', oneviews.VMDetail.as_view(), name='vm_detail'),
>>>>>>> nico/meow-pay-master:uncloud/uncloud/urls.py
]

16
uncloud/uncloud/wsgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
WSGI config for uncloud project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'uncloud.settings')
application = get_wsgi_application()

View file

View file

@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Product, Feature
#admin.site.register(Product)
#admin.site.register(Feature)

View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'uncloud_api'

View file

@ -0,0 +1,26 @@
import time
from django.conf import settings
from django.core.management.base import BaseCommand
import uncloud_api.models
import inspect
import sys
import re
class Command(BaseCommand):
args = '<None>'
help = 'hacking - only use if you are Nico'
def add_arguments(self, parser):
parser.add_argument('command', type=str, help='Command')
def handle(self, *args, **options):
getattr(self, options['command'])(**options)
@classmethod
def classtest(cls, **_):
clsmembers = inspect.getmembers(sys.modules['uncloud_api.models'], inspect.isclass)
for name, c in clsmembers:
if re.match(r'.+Product$', name):
print("{} -> {}".format(name, c))

View file

@ -0,0 +1,29 @@
import time
from django.conf import settings
from django.core.management.base import BaseCommand
from uncloud_api import models
class Command(BaseCommand):
args = '<None>'
help = 'VM Snapshot support'
def add_arguments(self, parser):
parser.add_argument('command', type=str, help='Command')
def handle(self, *args, **options):
print("Snapshotting")
#getattr(self, options['command'])(**options)
@classmethod
def monitor(cls, **_):
while True:
try:
tweets = models.Reply.get_target_tweets()
responses = models.Reply.objects.values_list('tweet_id', flat=True)
new_tweets = [x for x in tweets if x.id not in responses]
models.Reply.send(new_tweets)
except TweepError as e:
print(e)
time.sleep(60)

View file

@ -0,0 +1,31 @@
# Generated by Django 3.0.3 on 2020-02-23 10:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='VMSnapshotProduct',
fields=[
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('status', models.CharField(choices=[('pending', 'Pending'), ('being_created', 'Being created'), ('created_active', 'Created'), ('deleted', 'Deleted')], default='pending', max_length=256)),
('gb_ssd', models.FloatField()),
('gb_hdd', models.FloatField()),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]

View file

@ -0,0 +1,46 @@
# Generated by Django 3.0.3 on 2020-02-22 07:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('uncloud_api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='VMSnapshotOrder',
fields=[
('order_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='uncloud_api.Order')),
],
bases=('uncloud_api.order',),
),
migrations.CreateModel(
name='VMSnapshotProduct',
fields=[
('product_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='uncloud_api.Product')),
('gb_ssd', models.FloatField()),
('gb_hdd', models.FloatField()),
],
bases=('uncloud_api.product',),
),
migrations.DeleteModel(
name='OrderReference',
),
migrations.RemoveField(
model_name='product',
name='name',
),
migrations.RemoveField(
model_name='product',
name='recurring_period',
),
migrations.AddField(
model_name='product',
name='status',
field=models.CharField(choices=[('pending', 'Pending'), ('being_created', 'Being created'), ('created_active', 'Created'), ('deleted', 'Deleted')], default='pending', max_length=256),
),
]

View file

@ -0,0 +1,132 @@
import uuid
from django.db import models
from django.contrib.auth import get_user_model
# Product in DB vs. product in code
# DB:
# - need to define params (+param types) in db -> messy?
# - get /products/ is easy / automatic
#
# code
# - can have serializer/verification of fields easily in DRF
# - can have per product side effects / extra code running
# - might (??) make features easier??
# - how to setup / query the recurring period (?)
# - could get products list via getattr() + re ...Product() classes
# -> this could include the url for ordering => /order/vm_snapshot (params)
# ---> this would work with urlpatterns
# Combination: create specific product in DB (?)
# - a table per product (?) with 1 entry?
# Orders
# define state in DB
# select a price from a product => product might change, order stays
# params:
# - the product uuid or name (?) => productuuid
# - the product parameters => for each feature
#
# logs
# Should have a log = ... => 1:n field for most models!
class Product(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(get_user_model(),
on_delete=models.CASCADE)
# override these fields by default
description = ""
recurring_period = "not_recurring"
status = models.CharField(max_length=256,
choices = (
('pending', 'Pending'),
('being_created', 'Being created'),
('created_active', 'Created'),
('deleted', 'Deleted')
),
default='pending'
)
class Meta:
abstract = True
def __str__(self):
return "{}".format(self.name)
class VMSnapshotProduct(Product):
price_per_gb_ssd = 0.35
price_per_gb_hdd = 1.5/100
sample_ssd = 10
sample_hdd = 100
def recurring_price(self):
return 0
def one_time_price(self):
return 0
@classmethod
def sample_price(cls):
return cls.sample_ssd * cls.price_per_gb_ssd + cls.sample_hdd * cls.price_per_gb_hdd
description = "Create snapshot of a VM"
recurring_period = "monthly"
@classmethod
def pricing_model(cls):
return """
Pricing is on monthly basis and storage prices are equivalent to the storage
price in the VM.
Price per GB SSD is: {}
Price per GB HDD is: {}
Sample price for a VM with {} GB SSD and {} GB HDD VM is: {}.
""".format(cls.price_per_gb_ssd, cls.price_per_gb_hdd,
cls.sample_ssd, cls.sample_hdd, cls.sample_price())
gb_ssd = models.FloatField()
gb_hdd = models.FloatField()
class Feature(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=256)
recurring_price = models.FloatField(default=0)
one_time_price = models.FloatField()
product = models.ForeignKey(Product, on_delete=models.CASCADE)
# params for "cpu": cpu_count -> int
# each feature can only have one parameters
# could call this "value" and set whether it is user usable
# has_value = True/False
# value = string -> int (?)
# value_int
# value_str
# value_float
class Meta:
abstract = True
def __str__(self):
return "'{}' - '{}'".format(self.product, self.name)
# class Order(models.Model):
# uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# owner = models.ForeignKey(get_user_model(),
# on_delete=models.CASCADE)
# product = models.ForeignKey(Product,
# on_delete=models.CASCADE)

View file

@ -0,0 +1,19 @@
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = get_user_model()
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
class VMSnapshotSerializer(serializers.Serializer):
pass

View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View file

@ -0,0 +1,83 @@
from django.shortcuts import render
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from rest_framework import viewsets, permissions, generics
from .serializers import UserSerializer, GroupSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
class CreditCardViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows credit cards to be listed
"""
queryset = get_user_model().objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = get_user_model().objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [permissions.IsAuthenticated]
# POST /vm/snapshot/ vmuuid=... => create snapshot, returns snapshot uuid
# GET /vm/snapshot => list
# DEL /vm/snapshot/<uuid:uuid> => delete
# create-list -> get, post => ListCreateAPIView
# del on other!
class VMSnapshotView(generics.ListCreateAPIView):
#lookup_field = 'uuid'
permission_classes = [permissions.IsAuthenticated]
import inspect
import sys
import re
# Next: create /order/<productname> urls
# Next: strip off "Product" at the end
class ProductsView(APIView):
def get(self, request, format=None):
clsmembers = inspect.getmembers(sys.modules['uncloud_api.models'], inspect.isclass)
products = []
for name, c in clsmembers:
# Include everything that ends in Product, but not Product itself
m = re.match(r'(?P<pname>.+)Product$', name)
if m:
products.append({
'name': m.group('pname'),
'description': c.description,
'recurring_period': c.recurring_period,
'pricing_model': c.pricing_model()
}
)
return Response(products)

View file

View file

@ -0,0 +1,5 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)

View file

@ -0,0 +1,4 @@
from django.apps import AppConfig
class AuthConfig(AppConfig):
name = 'uncloud_auth'

View file

@ -0,0 +1,44 @@
# Generated by Django 3.0.3 on 2020-02-23 10:02
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View file

@ -0,0 +1,5 @@
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass

View file

View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class UncloudVmConfig(AppConfig):
name = 'uncloud_vm'

View file

@ -0,0 +1,12 @@
from django.db import models
class VM(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
cores = models.IntegerField()
ram = models.FloatField()
class VMDisk(models.Model):

View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View file

@ -0,0 +1,24 @@
from django.shortcuts import render
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from myapps.serializers import UserSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from opennebula.models import VM as OpenNebulaVM
class VMViewSet(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
permission_classes = [permissions.IsAuthenticated]