diff --git a/.gitignore b/.gitignore index 304c492..786a584 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ __pycache__/ pay.conf -log.txt \ No newline at end of file +log.txt +test.py +STRIPE +venv/ diff --git a/README-penguinpay.md b/README-penguinpay.md new file mode 100644 index 0000000..3229bc5 --- /dev/null +++ b/README-penguinpay.md @@ -0,0 +1,42 @@ +## How to place a order with penguin pay + +### Requirements + +* An ungleich account - can be registered for free on + https://account.ungleich.ch +* httpie installed (provides the http command) + +## Get a membership + + +## Registering a payment method + +To be able to pay for the membership, you will need to register a +credit card or apply for payment on bill (TO BE IMPLEMENTED). + +### Register credit card + +``` +http POST https://api.ungleich.ch/membership \ + username=nico password=yourpassword \ + cc_number=.. \ + cc_ + +``` + + + +### Request payment via bill + + + + +## Create the membership + + +``` +http POST https://api.ungleich.ch/membership username=nico password=yourpassword + +``` + +## List available products diff --git a/hack-a-vpn.py b/hack-a-vpn.py new file mode 100644 index 0000000..e6bfb43 --- /dev/null +++ b/hack-a-vpn.py @@ -0,0 +1,213 @@ +from flask import Flask, request +from flask_restful import Resource, Api +import etcd3 +import json +import logging +from functools import wraps + +from ldaptest import is_valid_ldap_user + +def authenticate(func): + @wraps(func) + def wrapper(*args, **kwargs): + if not getattr(func, 'authenticated', True): + return func(*args, **kwargs) + + # pass in username/password ! + acct = basic_authentication() # custom account lookup function + + if acct: + return func(*args, **kwargs) + + flask_restful.abort(401) + return wrapper + +def readable_errors(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except etcd3.exceptions.ConnectionFailedError as e: + raise UncloudException('Cannot connect to etcd: is etcd running and reachable? {}'.format(e)) + except etcd3.exceptions.ConnectionTimeoutError as e: + raise UncloudException('etcd connection timeout. {}'.format(e)) + + return wrapper + + +class DB(object): + def __init__(self, config, prefix="/"): + self.config = config + + # Root for everything + self.base_prefix= '/nicohack' + + # Can be set from outside + self.prefix = prefix + + self.connect() + + @readable_errors + def connect(self): + self._db_clients = [] + for endpoint in self.config.etcd_hosts: + client = etcd3.client(host=endpoint, **self.config.etcd_args) + self._db_clients.append(client) + + def realkey(self, key): + return "{}{}/{}".format(self.base_prefix, + self.prefix, + key) + + @readable_errors + def get(self, key, as_json=False, **kwargs): + value, _ = self._db_clients[0].get(self.realkey(key), **kwargs) + + if as_json: + value = json.loads(value) + + return value + + + @readable_errors + def set(self, key, value, as_json=False, **kwargs): + if as_json: + value = json.dumps(value) + + # FIXME: iterate over clients in case of failure ? + return self._db_clients[0].put(self.realkey(key), value, **kwargs) + + +class Membership(Resource): + def __init__(self, config): + self.config = config + + def get(self): + data = request.get_json(silent=True) or {} + print("{} {}".format(data, config)) + return {'message': 'Order successful' }, 200 + + def post(self): + data = request.get_json(silent=True) or {} + print("{} {}".format(data, config)) + return {'message': 'Order 2x successful' }, 200 + + +class Order(Resource): + def __init__(self, config): + self.config = config + + @staticmethod + def post(): + data = request.get_json(silent=True) or {} + print("{} {}".format(data, config)) + + +class Product(Resource): + def __init__(self, config): + self.config = config + + self.products = [] + self.products.append( + { "name": "membership-free", + "description": """ +This membership gives you access to the API and includes a VPN +with 1 IPv6 address. +See https://redmine.ungleich.ch/issues/7747? +""", + "uuid": "a3883466-0012-4d01-80ff-cbf7469957af", + "recurring": True, + "recurring_time_frame": "per_year", + "features": [ + { "name": "membership", + "price_one_time": 0, + "price_recurring": 0 + } + ] + } + ) + self.products.append( + { "name": "membership-standard", + "description": """ +This membership gives you access to the API and includes an IPv6-VPN with +one IPv6 address ("Road warrior") +See https://redmine.ungleich.ch/issues/7747? +""", + "uuid": "1d85296b-0863-4dd6-a543-a6d5a4fbe4a6", + "recurring": True, + "recurring_time_frame": "per_month", + "features": [ + { "name": "membership", + "price_one_time": 0, + "price_recurring": 5 + } + + ] + } + ) + self.products.append( + { "name": "membership-premium", + "description": """ +This membership gives you access to the API and includes an +IPv6-VPN with a /48 IPv6 network. +See https://redmine.ungleich.ch/issues/7747? +""", + "uuid": "bfd63fd2-d227-436f-a8b8-600de74dd6ce", + "recurring": True, + "recurring_time_frame": "per_month", + "features": [ + { "name": "membership", + "price_one_time": 0, + "price_recurring": 5 + } + + ] + } + ) + self.products.append( + { "name": "ipv6-vpn-with-/48", + "description": """ +An IPv6 VPN with a /48 network included. +""", + "uuid": "fe5753f8-6fe1-4dc4-9b73-7b803de4c597", + "recurring": True, + "recurring_time_frame": "per_year", + "features": [ + { "name": "vpn", + "price_one_time": 0, + "price_recurring": 120 + } + ] + } + ) + + + @staticmethod + def post(): + data = request.get_json(silent=True) or {} + print("{} {}".format(data, config)) + + def get(self): + data = request.get_json(silent=True) or {} + print("{} {}".format(data, config)) + + return self.products + + + + + +if __name__ == '__main__': + app = Flask(__name__) + + config = {} + + config['etcd_url']="https://etcd1.ungleich.ch" + config['ldap_url']="ldaps://ldap1.ungleich.ch" + + api = Api(app) + api.add_resource(Order, '/orders', resource_class_args=( config, )) + api.add_resource(Product, '/products', resource_class_args=( config, )) + api.add_resource(Membership, '/membership', resource_class_args=( config, )) + + app.run(host='::', port=5000, debug=True) diff --git a/ldaptest.py b/ldaptest.py new file mode 100644 index 0000000..eb5a5be --- /dev/null +++ b/ldaptest.py @@ -0,0 +1,27 @@ +import ldap3 +from ldap3 import Server, Connection, ObjectDef, Reader, ALL +import os +import sys + +def is_valid_ldap_user(username, password): + server = Server("ldaps://ldap1.ungleich.ch") + is_valid = False + + try: + conn = Connection(server, 'cn={},ou=users,dc=ungleich,dc=ch'.format(username), password, auto_bind=True) + is_valid = True + except Exception as e: + print("user: {}".format(e)) + + try: + conn = Connection(server, 'uid={},ou=customer,dc=ungleich,dc=ch'.format(username), password, auto_bind=True) + is_valid = True + except Exception as e: + print("customer: {}".format(e)) + + + return is_valid + + +if __name__ == '__main__': + print(is_valid_ldap_user(sys.argv[1], sys.argv[2])) diff --git a/nicohack202002/uncloud/.gitignore b/nicohack202002/uncloud/.gitignore new file mode 100644 index 0000000..49ef255 --- /dev/null +++ b/nicohack202002/uncloud/.gitignore @@ -0,0 +1 @@ +db.sqlite3 diff --git a/nicohack202002/uncloud/manage.py b/nicohack202002/uncloud/manage.py new file mode 100755 index 0000000..b050590 --- /dev/null +++ b/nicohack202002/uncloud/manage.py @@ -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() diff --git a/nicohack202002/uncloud/uncloud/.gitignore b/nicohack202002/uncloud/uncloud/.gitignore new file mode 100644 index 0000000..ef418f5 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/.gitignore @@ -0,0 +1 @@ +secrets.py diff --git a/nicohack202002/uncloud/uncloud/__init__.py b/nicohack202002/uncloud/uncloud/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/uncloud/asgi.py b/nicohack202002/uncloud/uncloud/asgi.py new file mode 100644 index 0000000..2b5a7a3 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/asgi.py @@ -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() diff --git a/nicohack202002/uncloud/uncloud/settings.py b/nicohack202002/uncloud/uncloud/settings.py new file mode 100644 index 0000000..be38f8f --- /dev/null +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -0,0 +1,165 @@ +""" +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 + +# 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' +] + +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' + + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# 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 + +import ldap +from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion + + +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_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.BasicAuthentication', + '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/' + + +# Uncommitted file +import uncloud.secrets + +import stripe +stripe.api_key = uncloud.secrets.STRIPE_KEY diff --git a/nicohack202002/uncloud/uncloud/stripe.py b/nicohack202002/uncloud/uncloud/stripe.py new file mode 100644 index 0000000..ce35fd9 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/stripe.py @@ -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 diff --git a/nicohack202002/uncloud/uncloud/urls.py b/nicohack202002/uncloud/uncloud/urls.py new file mode 100644 index 0000000..cb50432 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/urls.py @@ -0,0 +1,37 @@ +"""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 + +router = routers.DefaultRouter() +router.register(r'users', views.UserViewSet) +router.register(r'groups', views.GroupViewSet) + +# 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('api-auth/', include('rest_framework.urls', namespace='rest_framework')) +] + +#urlpatterns = [ +# path('admin/', admin.site.urls), +# path('api/', include('api.urls')), +#] diff --git a/nicohack202002/uncloud/uncloud/wsgi.py b/nicohack202002/uncloud/uncloud/wsgi.py new file mode 100644 index 0000000..c4a07b8 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/wsgi.py @@ -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() diff --git a/nicohack202002/uncloud/uncloud_api/__init__.py b/nicohack202002/uncloud/uncloud_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/uncloud_api/admin.py b/nicohack202002/uncloud/uncloud_api/admin.py new file mode 100644 index 0000000..f9f5589 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/admin.py @@ -0,0 +1,6 @@ +from django.contrib import admin + +from .models import Product, Feature + +admin.site.register(Product) +admin.site.register(Feature) diff --git a/nicohack202002/uncloud/uncloud_api/apps.py b/nicohack202002/uncloud/uncloud_api/apps.py new file mode 100644 index 0000000..6830fa2 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + name = 'uncloud_api' diff --git a/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py b/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py new file mode 100644 index 0000000..33be28d --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py @@ -0,0 +1,50 @@ +# Generated by Django 3.0.3 on 2020-02-21 10:42 + +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='OrderReference', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ], + ), + migrations.CreateModel( + name='Product', + fields=[ + ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('name', models.CharField(max_length=256)), + ('recurring_period', models.CharField(choices=[('per_year', 'Per Year'), ('per_month', 'Per Month'), ('per_week', 'Per Week'), ('per_day', 'Per Day'), ('per_hour', 'Per Hour'), ('not_recurring', 'Not recurring')], default='not_recurring', max_length=256)), + ], + ), + migrations.CreateModel( + name='Order', + fields=[ + ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uncloud_api.Product')), + ], + ), + migrations.CreateModel( + name='Feature', + fields=[ + ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('name', models.CharField(max_length=256)), + ('recurring_price', models.FloatField(default=0)), + ('one_time_price', models.FloatField()), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='uncloud_api.Product')), + ], + ), + ] diff --git a/nicohack202002/uncloud/uncloud_api/migrations/__init__.py b/nicohack202002/uncloud/uncloud_api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/uncloud_api/models.py b/nicohack202002/uncloud/uncloud_api/models.py new file mode 100644 index 0000000..9d4291a --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/models.py @@ -0,0 +1,58 @@ +import uuid + +from django.db import models +from django.contrib.auth import get_user_model + + + +class Product(models.Model): + uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + name = models.CharField(max_length=256) + + recurring_period = models.CharField(max_length=256, + choices = ( + ("per_year", "Per Year"), + ("per_month", "Per Month"), + ("per_week", "Per Week"), + ("per_day", "Per Day"), + ("per_hour", "Per Hour"), + ("not_recurring", "Not recurring") + ), + default="not_recurring" + ) + + def __str__(self): + return "{}".format(self.name) + + + +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) + + 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) + + +class OrderReference(models.Model): + """ + An order can references another product / relate to it. + This model is used for the relation + """ + + pass diff --git a/nicohack202002/uncloud/uncloud_api/serializers.py b/nicohack202002/uncloud/uncloud_api/serializers.py new file mode 100644 index 0000000..57532f2 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/serializers.py @@ -0,0 +1,16 @@ +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'] diff --git a/nicohack202002/uncloud/uncloud_api/tests.py b/nicohack202002/uncloud/uncloud_api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/nicohack202002/uncloud/uncloud_api/views.py b/nicohack202002/uncloud/uncloud_api/views.py new file mode 100644 index 0000000..88e0543 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/views.py @@ -0,0 +1,37 @@ +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 + +from .serializers import UserSerializer, GroupSerializer + +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] diff --git a/nicohack202002/uncloud/uncloud_auth/__init__.py b/nicohack202002/uncloud/uncloud_auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/uncloud_auth/admin.py b/nicohack202002/uncloud/uncloud_auth/admin.py new file mode 100644 index 0000000..f91be8f --- /dev/null +++ b/nicohack202002/uncloud/uncloud_auth/admin.py @@ -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) diff --git a/nicohack202002/uncloud/uncloud_auth/apps.py b/nicohack202002/uncloud/uncloud_auth/apps.py new file mode 100644 index 0000000..c16bd7a --- /dev/null +++ b/nicohack202002/uncloud/uncloud_auth/apps.py @@ -0,0 +1,4 @@ +from django.apps import AppConfig + +class AuthConfig(AppConfig): + name = 'uncloud_auth' diff --git a/nicohack202002/uncloud/uncloud_auth/migrations/0001_initial.py b/nicohack202002/uncloud/uncloud_auth/migrations/0001_initial.py new file mode 100644 index 0000000..267adf2 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_auth/migrations/0001_initial.py @@ -0,0 +1,44 @@ +# Generated by Django 3.0.3 on 2020-02-21 10:41 + +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()), + ], + ), + ] diff --git a/nicohack202002/uncloud/uncloud_auth/migrations/__init__.py b/nicohack202002/uncloud/uncloud_auth/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/uncloud_auth/models.py b/nicohack202002/uncloud/uncloud_auth/models.py new file mode 100644 index 0000000..4c9c171 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_auth/models.py @@ -0,0 +1,4 @@ +from django.contrib.auth.models import AbstractUser + +class User(AbstractUser): + pass diff --git a/notes-nico.org b/notes-nico.org new file mode 100644 index 0000000..21102f9 --- /dev/null +++ b/notes-nico.org @@ -0,0 +1,42 @@ +* snapshot feature +** product: vm-snapshot +* steps +** DONE authenticate via ldap + CLOSED: [2020-02-20 Thu 19:05] +** DONE Make classes / views require authentication + CLOSED: [2020-02-20 Thu 19:05] +** TODO register credit card +*** TODO find out what saving with us +*** Info +**** should not be fully saved in the DB +**** model needs to be a bit different +* Decide where to save sensitive data +** stripe access key, etc. +* python requirements (nicohack202002) + django djangorestframework django-auth-ldap stripe +* os package requirements (alpine) + openldap-dev +* VPN case +** put on /orders with uuid +** register cc +* CC +** TODO check whether we can register or not at stripe +* membership +** required for "smaller" / "shorter" products + +* TODO Membership missing +* Flows to be implemented - see https://redmine.ungleich.ch/issues/7609 +** Membership +*** 5 CHF +** Django Hosting +*** One time payment 35 CHF +*** Monthly payment depends on VM size +*** Parameters: same as IPv6 only VM +** IPv6 VPN +*** Parameters: none +*** Is for free if the customer has an active VM +** IPv6 only VM +*** Parameters: cores, ram, os_disk_size, OS +* Django rest framework +** viewset: .list and .create +** view: .get .post diff --git a/notes.org b/notes.org new file mode 100644 index 0000000..72e8ffc --- /dev/null +++ b/notes.org @@ -0,0 +1 @@ +* diff --git a/requirements.txt b/requirements.txt index 0f5d0d2..29c21b4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,4 +5,4 @@ Flask-RESTful git+https://code.ungleich.ch/ahmedbilal/ungleich-common/#egg=ungleich-common-etcd&subdirectory=etcd git+https://code.ungleich.ch/ahmedbilal/ungleich-common/#egg=ungleich-common-ldap&subdirectory=ldap git+https://code.ungleich.ch/ahmedbilal/ungleich-common/#egg=ungleich-common-std&subdirectory=std -git+https://code.ungleich.ch/ahmedbilal/ungleich-common/#egg=ungleich-common-schemas&subdirectory=schemas \ No newline at end of file +git+https://code.ungleich.ch/ahmedbilal/ungleich-common/#egg=ungleich-common-schemas&subdirectory=schemas diff --git a/stripe_hack.py b/stripe_hack.py new file mode 100644 index 0000000..f436c62 --- /dev/null +++ b/stripe_hack.py @@ -0,0 +1,7 @@ +import stripe_utils +import os + + +if __name__ == '__main__': + s = stripe_utils.StripeUtils(os.environ['STRIPE_PRIVATE_KEY']) + print(s.get_stripe_customer_from_email('coder.purple+2002@gmail.com')) diff --git a/stripe_utils.py b/stripe_utils.py index a125474..6a2cd29 100644 --- a/stripe_utils.py +++ b/stripe_utils.py @@ -72,8 +72,9 @@ class StripeUtils(object): PLAN_EXISTS_ERROR_MSG = 'Plan {} exists already.\nCreating a local StripePlan now.' PLAN_DOES_NOT_EXIST_ERROR_MSG = 'Plan {} does not exist.' - def __init__(self): + def __init__(self, private_key): self.stripe = stripe + stripe.api_key = private_key @handle_stripe_error def card_exists(self, customer, cc_number, exp_month, exp_year, cvc): diff --git a/ucloud_pay.py b/ucloud_pay.py index fc45951..dbc0d2c 100644 --- a/ucloud_pay.py +++ b/ucloud_pay.py @@ -33,7 +33,6 @@ class ListProducts(Resource): logger.debug('Products = {}'.format(prod_dict)) return prod_dict, 200 - class AddProduct(Resource): @staticmethod def post(): @@ -68,6 +67,9 @@ class AddProduct(Resource): else: return make_return_message('Product updated.') +################################################################################ +# Nico-ok-marker + class UserRegisterPayment(Resource): @staticmethod