From c1f384fb9ab222fe5d12067b82e595c1864ee097 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Sat, 15 Feb 2020 09:38:33 +0100 Subject: [PATCH 01/15] so many notes&hacks! --- README-penguinpay.md | 10 +++++ hack.py | 98 ++++++++++++++++++++++++++++++++++++++++++++ notes.org | 1 + requirements.txt | 3 ++ 4 files changed, 112 insertions(+) create mode 100644 README-penguinpay.md create mode 100644 hack.py create mode 100644 notes.org create mode 100644 requirements.txt diff --git a/README-penguinpay.md b/README-penguinpay.md new file mode 100644 index 0000000..769f183 --- /dev/null +++ b/README-penguinpay.md @@ -0,0 +1,10 @@ +## 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 + * diff --git a/hack.py b/hack.py new file mode 100644 index 0000000..c84f9f6 --- /dev/null +++ b/hack.py @@ -0,0 +1,98 @@ +from flask import Flask, request +from flask_restful import Resource, Api +import etcd3 +import json +import logging +from functools import wraps + +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 + + +class Order(Resource): + def __init__(self, config): + self.config = config + + @staticmethod + def post(): + print("{} {}".format(data, config)) + data = request.get_json(silent=True) or {} + + + + +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, '/order', resource_class_args=( config, )) + api.add_resource(Membership, '/membership', resource_class_args=( config, )) + + app.run(host='::', port=5000, debug=True) 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 new file mode 100644 index 0000000..668fb3f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +flask-restful +ldap3 +etcd3 From aa9548e753bddee41a30517114c79938a1e79873 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Sat, 15 Feb 2020 11:15:26 +0100 Subject: [PATCH 02/15] +gitignore Signed-off-by: Nico Schottelius --- .gitignore | 4 +++- README-penguinpay.md | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 77de841..786a584 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,6 @@ __pycache__/ pay.conf log.txt -test.py \ No newline at end of file +test.py +STRIPE +venv/ diff --git a/README-penguinpay.md b/README-penguinpay.md index 769f183..89f494a 100644 --- a/README-penguinpay.md +++ b/README-penguinpay.md @@ -7,4 +7,3 @@ * httpie installed (provides the http command) ### Get a membership - * From 074efffaa70ca594457e8dd61b041001ad06706d Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 09:44:30 +0100 Subject: [PATCH 03/15] ++ hack --- README-penguinpay.md | 35 ++++++++++++++++++++++++++++++++++- config.py | 5 ++++- hack.py | 5 +++++ requirements.txt | 1 + stripe_hack.py | 7 +++++++ stripe_utils.py | 9 +++++---- 6 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 stripe_hack.py diff --git a/README-penguinpay.md b/README-penguinpay.md index 89f494a..3229bc5 100644 --- a/README-penguinpay.md +++ b/README-penguinpay.md @@ -6,4 +6,37 @@ https://account.ungleich.ch * httpie installed (provides the http command) -### Get a membership +## 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/config.py b/config.py index b951830..c3bad9d 100644 --- a/config.py +++ b/config.py @@ -5,7 +5,10 @@ from ldap_manager import LdapManager config = configparser.ConfigParser() config.read('pay.conf') +# Note 2020-02-15: this stuff clearly does not belong here, +# if config.py is used everywhere. + etcd_client = EtcdWrapper(host=config['etcd']['host'], port=config['etcd']['port']) ldap_manager = LdapManager(server=config['ldap']['server'], admin_dn=config['ldap']['admin_dn'], - admin_password=config['ldap']['admin_password']) \ No newline at end of file + admin_password=config['ldap']['admin_password']) diff --git a/hack.py b/hack.py index c84f9f6..cbb9a07 100644 --- a/hack.py +++ b/hack.py @@ -70,6 +70,11 @@ class Membership(Resource): 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): diff --git a/requirements.txt b/requirements.txt index 668fb3f..1fc7b83 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ flask-restful ldap3 etcd3 +stripe 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 9474f74..3c68698 100644 --- a/stripe_utils.py +++ b/stripe_utils.py @@ -4,9 +4,9 @@ import stripe import stripe.error import logging -from config import etcd_client as client, config as config - -stripe.api_key = config['stripe']['private_key'] +# FIXME: way too many dependencies in this import +# Most of them are not needed for stripe +#from config import etcd_client as client, config as config def handle_stripe_error(f): @@ -73,8 +73,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): From 0a1ccadda2feb6b55a8d434da187d852739453b7 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 11:56:47 +0100 Subject: [PATCH 04/15] +ldaptest --- ldaptest.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 ldaptest.py diff --git a/ldaptest.py b/ldaptest.py new file mode 100644 index 0000000..f28fcf6 --- /dev/null +++ b/ldaptest.py @@ -0,0 +1,8 @@ +import ldap3 +from ldap3 import Server, Connection, ObjectDef, Reader, ALL +import os + +server = Server("ldaps://ldap1.ungleich.ch") +conn = Connection(server, 'cn=Nico Schottelius,ou=users,dc=ungleich,dc=ch', os.environ['PW'], auto_bind=True) + +print(conn) From 13292db39e6e28f6a957e42ea890b3fb46615d40 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 11:57:03 +0100 Subject: [PATCH 05/15] +old notes --- notes-nico.org | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 notes-nico.org diff --git a/notes-nico.org b/notes-nico.org new file mode 100644 index 0000000..9e88215 --- /dev/null +++ b/notes-nico.org @@ -0,0 +1,13 @@ +* 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 From 315aaded4148a08f9bf33069f5f7156aaee852fd Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 16:05:58 +0100 Subject: [PATCH 06/15] Focus on creating a VPN as a first test case --- README.md | 7 +++- hack.py => hack-a-vpn.py | 81 +++++++++++++++++++++++++++++++++++++++- ldaptest.py | 25 +++++++++++-- 3 files changed, 106 insertions(+), 7 deletions(-) rename hack.py => hack-a-vpn.py (53%) diff --git a/README.md b/README.md index 1b50cf3..72199ca 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,10 @@ The pay module for the uncloud - uses [Stripe](https://stripe.com/docs/api) as the payment gateway. - uses [ldap3](https://github.com/cannatag/ldap3) for ldap authentication. -## Getting started + +## Getting started as a user + + **TODO** @@ -40,4 +43,4 @@ http --json GET http://[::]:5000/order/list email=your_email_here password=your_ ```shell script http --json http://[::]:5000/user/register_payment card_number=4111111111111111 cvc=123 expiry_year=2020 expiry_month=8 card_holder_name="The test user" email=your_email_here password=your_password_here -``` \ No newline at end of file +``` diff --git a/hack.py b/hack-a-vpn.py similarity index 53% rename from hack.py rename to hack-a-vpn.py index cbb9a07..0956cd5 100644 --- a/hack.py +++ b/hack-a-vpn.py @@ -82,8 +82,84 @@ class Order(Resource): @staticmethod def post(): - print("{} {}".format(data, config)) 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 + } + + ] + } + ) + + + @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 + @@ -97,7 +173,8 @@ if __name__ == '__main__': config['ldap_url']="ldaps://ldap1.ungleich.ch" api = Api(app) - api.add_resource(Order, '/order', resource_class_args=( config, )) + 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 index f28fcf6..eb5a5be 100644 --- a/ldaptest.py +++ b/ldaptest.py @@ -1,8 +1,27 @@ import ldap3 from ldap3 import Server, Connection, ObjectDef, Reader, ALL import os +import sys -server = Server("ldaps://ldap1.ungleich.ch") -conn = Connection(server, 'cn=Nico Schottelius,ou=users,dc=ungleich,dc=ch', os.environ['PW'], auto_bind=True) +def is_valid_ldap_user(username, password): + server = Server("ldaps://ldap1.ungleich.ch") + is_valid = False -print(conn) + 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])) From e472d20ae007db5cb9de0a2718a642d5bd35f8d9 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 16:52:50 +0100 Subject: [PATCH 07/15] hacking uncloud v202002 Signed-off-by: Nico Schottelius --- nicohack202002/uncloud/api/__init__.py | 0 nicohack202002/uncloud/api/admin.py | 3 + nicohack202002/uncloud/api/apps.py | 5 + .../uncloud/api/migrations/__init__.py | 0 nicohack202002/uncloud/api/models.py | 3 + nicohack202002/uncloud/api/tests.py | 3 + nicohack202002/uncloud/api/views.py | 3 + nicohack202002/uncloud/manage.py | 21 +++ nicohack202002/uncloud/uncloud/__init__.py | 0 nicohack202002/uncloud/uncloud/asgi.py | 16 +++ nicohack202002/uncloud/uncloud/settings.py | 120 ++++++++++++++++++ nicohack202002/uncloud/uncloud/urls.py | 21 +++ nicohack202002/uncloud/uncloud/wsgi.py | 16 +++ 13 files changed, 211 insertions(+) create mode 100644 nicohack202002/uncloud/api/__init__.py create mode 100644 nicohack202002/uncloud/api/admin.py create mode 100644 nicohack202002/uncloud/api/apps.py create mode 100644 nicohack202002/uncloud/api/migrations/__init__.py create mode 100644 nicohack202002/uncloud/api/models.py create mode 100644 nicohack202002/uncloud/api/tests.py create mode 100644 nicohack202002/uncloud/api/views.py create mode 100755 nicohack202002/uncloud/manage.py create mode 100644 nicohack202002/uncloud/uncloud/__init__.py create mode 100644 nicohack202002/uncloud/uncloud/asgi.py create mode 100644 nicohack202002/uncloud/uncloud/settings.py create mode 100644 nicohack202002/uncloud/uncloud/urls.py create mode 100644 nicohack202002/uncloud/uncloud/wsgi.py diff --git a/nicohack202002/uncloud/api/__init__.py b/nicohack202002/uncloud/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/api/admin.py b/nicohack202002/uncloud/api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/nicohack202002/uncloud/api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/nicohack202002/uncloud/api/apps.py b/nicohack202002/uncloud/api/apps.py new file mode 100644 index 0000000..d87006d --- /dev/null +++ b/nicohack202002/uncloud/api/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + name = 'api' diff --git a/nicohack202002/uncloud/api/migrations/__init__.py b/nicohack202002/uncloud/api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nicohack202002/uncloud/api/models.py b/nicohack202002/uncloud/api/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/nicohack202002/uncloud/api/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/nicohack202002/uncloud/api/tests.py b/nicohack202002/uncloud/api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/nicohack202002/uncloud/api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/nicohack202002/uncloud/api/views.py b/nicohack202002/uncloud/api/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/nicohack202002/uncloud/api/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. 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/__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..97dcf1e --- /dev/null +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -0,0 +1,120 @@ +""" +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', +] + +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', + }, +] + + +# 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/' diff --git a/nicohack202002/uncloud/uncloud/urls.py b/nicohack202002/uncloud/uncloud/urls.py new file mode 100644 index 0000000..7b82bc9 --- /dev/null +++ b/nicohack202002/uncloud/uncloud/urls.py @@ -0,0 +1,21 @@ +"""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 + +urlpatterns = [ + path('admin/', admin.site.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() From 254429db55f50cd4621d21e9c64eb6694a5d6d91 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 16:55:01 +0100 Subject: [PATCH 08/15] .gitignore & more --- hack-a-vpn.py | 33 +++++++++++++++++++++++++++++++ hack.org | 0 nicohack202002/uncloud/.gitignore | 1 + notes-nico.org | 10 ++++++++++ ucloud_pay.py | 4 +++- 5 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 hack.org create mode 100644 nicohack202002/uncloud/.gitignore diff --git a/hack-a-vpn.py b/hack-a-vpn.py index 0956cd5..e6bfb43 100644 --- a/hack-a-vpn.py +++ b/hack-a-vpn.py @@ -5,6 +5,23 @@ 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): @@ -147,6 +164,22 @@ See https://redmine.ungleich.ch/issues/7747? ] } ) + 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 diff --git a/hack.org b/hack.org new file mode 100644 index 0000000..e69de29 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/notes-nico.org b/notes-nico.org index 9e88215..e2b8cac 100644 --- a/notes-nico.org +++ b/notes-nico.org @@ -1,3 +1,13 @@ +* python requirements (nicohack202002) + django djangorestframework +* 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 diff --git a/ucloud_pay.py b/ucloud_pay.py index 09c5813..f2c9e01 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 From 9fd445e9478ef2a30106905d6fabd47abaf9663a Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 18:58:07 +0100 Subject: [PATCH 09/15] add ldap support + tutorial example --- nicohack202002/uncloud/api/serializers.py | 14 +++++++++++++ nicohack202002/uncloud/api/views.py | 20 ++++++++++++++++++ nicohack202002/uncloud/uncloud/settings.py | 24 ++++++++++++++++++++++ nicohack202002/uncloud/uncloud/urls.py | 19 +++++++++++++++-- 4 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 nicohack202002/uncloud/api/serializers.py diff --git a/nicohack202002/uncloud/api/serializers.py b/nicohack202002/uncloud/api/serializers.py new file mode 100644 index 0000000..f5a5a92 --- /dev/null +++ b/nicohack202002/uncloud/api/serializers.py @@ -0,0 +1,14 @@ +from django.contrib.auth.models import User, Group +from rest_framework import serializers + + +class UserSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = User + fields = ['url', 'username', 'email', 'groups'] + + +class GroupSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Group + fields = ['url', 'name'] diff --git a/nicohack202002/uncloud/api/views.py b/nicohack202002/uncloud/api/views.py index 91ea44a..d7f3dae 100644 --- a/nicohack202002/uncloud/api/views.py +++ b/nicohack202002/uncloud/api/views.py @@ -1,3 +1,23 @@ from django.shortcuts import render # Create your views here. + +from django.contrib.auth.models import User, Group +from rest_framework import viewsets +from api.serializers import UserSerializer, GroupSerializer + + +class UserViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows users to be viewed or edited. + """ + queryset = User.objects.all().order_by('-date_joined') + serializer_class = UserSerializer + + +class GroupViewSet(viewsets.ModelViewSet): + """ + API endpoint that allows groups to be viewed or edited. + """ + queryset = Group.objects.all() + serializer_class = GroupSerializer diff --git a/nicohack202002/uncloud/uncloud/settings.py b/nicohack202002/uncloud/uncloud/settings.py index 97dcf1e..7def11a 100644 --- a/nicohack202002/uncloud/uncloud/settings.py +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -37,6 +37,7 @@ INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'rest_framework' ] MIDDLEWARE = [ @@ -99,6 +100,29 @@ AUTH_PASSWORD_VALIDATORS = [ }, ] +# LDAP +import ldap +from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion + +AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] +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/REST +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': [ + 'rest_framework.authentication.BasicAuthentication', + 'rest_framework.authentication.SessionAuthentication', + ] +} + + # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ diff --git a/nicohack202002/uncloud/uncloud/urls.py b/nicohack202002/uncloud/uncloud/urls.py index 7b82bc9..e52fd35 100644 --- a/nicohack202002/uncloud/uncloud/urls.py +++ b/nicohack202002/uncloud/uncloud/urls.py @@ -14,8 +14,23 @@ Including another URLconf 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin -from django.urls import path +from django.urls import path, include +from rest_framework import routers +from 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('admin/', admin.site.urls), + path('', include(router.urls)), + path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] + +#urlpatterns = [ +# path('admin/', admin.site.urls), +# path('api/', include('api.urls')), +#] From f8182e00e845b29ae92fbf3ae482a22e30f9f7d4 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 19:38:30 +0100 Subject: [PATCH 10/15] import secrets --- nicohack202002/uncloud/uncloud/.gitignore | 1 + nicohack202002/uncloud/uncloud/settings.py | 4 ++++ 2 files changed, 5 insertions(+) create mode 100644 nicohack202002/uncloud/uncloud/.gitignore 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/settings.py b/nicohack202002/uncloud/uncloud/settings.py index 7def11a..91bcf47 100644 --- a/nicohack202002/uncloud/uncloud/settings.py +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -142,3 +142,7 @@ USE_TZ = True # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' + + +# Uncommitted file +import uncloud.secrets From 118c66799c5629778bab6ce5c685a5d3acd3fe46 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Thu, 20 Feb 2020 19:38:43 +0100 Subject: [PATCH 11/15] ++views/permissions --- nicohack202002/uncloud/api/models.py | 3 +++ nicohack202002/uncloud/api/views.py | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/nicohack202002/uncloud/api/models.py b/nicohack202002/uncloud/api/models.py index 71a8362..7288ecf 100644 --- a/nicohack202002/uncloud/api/models.py +++ b/nicohack202002/uncloud/api/models.py @@ -1,3 +1,6 @@ from django.db import models # Create your models here. + +class CreditCard(models.Model): + pass diff --git a/nicohack202002/uncloud/api/views.py b/nicohack202002/uncloud/api/views.py index d7f3dae..c9b1e57 100644 --- a/nicohack202002/uncloud/api/views.py +++ b/nicohack202002/uncloud/api/views.py @@ -3,17 +3,30 @@ from django.shortcuts import render # Create your views here. from django.contrib.auth.models import User, Group -from rest_framework import viewsets +from rest_framework import viewsets, permissions + from api.serializers import UserSerializer, GroupSerializer +class CreditCardViewSet(viewsets.ModelViewSet): + + """ + API endpoint that allows credit cards to be listed + """ + queryset = User.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 = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer + permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ @@ -21,3 +34,5 @@ class GroupViewSet(viewsets.ModelViewSet): """ queryset = Group.objects.all() serializer_class = GroupSerializer + + permission_classes = [permissions.IsAuthenticated] From c45635505927da610deaba4e0b6a7de573502a48 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Fri, 21 Feb 2020 10:41:22 +0100 Subject: [PATCH 12/15] begin to introduce product Signed-off-by: Nico Schottelius --- hack.org | 0 nicohack202002/uncloud/api/models.py | 6 -- nicohack202002/uncloud/uncloud/settings.py | 6 +- nicohack202002/uncloud/uncloud/stripe.py | 55 +++++++++++++++++++ nicohack202002/uncloud/uncloud/urls.py | 2 +- .../uncloud/{api => uncloud_api}/__init__.py | 0 .../uncloud/{api => uncloud_api}/admin.py | 0 .../uncloud/{api => uncloud_api}/apps.py | 2 +- .../uncloud_api/migrations/0001_initial.py | 34 ++++++++++++ .../migrations/__init__.py | 0 nicohack202002/uncloud/uncloud_api/models.py | 30 ++++++++++ .../{api => uncloud_api}/serializers.py | 0 .../uncloud/{api => uncloud_api}/tests.py | 0 .../uncloud/{api => uncloud_api}/views.py | 2 +- notes-nico.org | 21 ++++++- 15 files changed, 147 insertions(+), 11 deletions(-) delete mode 100644 hack.org delete mode 100644 nicohack202002/uncloud/api/models.py create mode 100644 nicohack202002/uncloud/uncloud/stripe.py rename nicohack202002/uncloud/{api => uncloud_api}/__init__.py (100%) rename nicohack202002/uncloud/{api => uncloud_api}/admin.py (100%) rename nicohack202002/uncloud/{api => uncloud_api}/apps.py (71%) create mode 100644 nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py rename nicohack202002/uncloud/{api => uncloud_api}/migrations/__init__.py (100%) create mode 100644 nicohack202002/uncloud/uncloud_api/models.py rename nicohack202002/uncloud/{api => uncloud_api}/serializers.py (100%) rename nicohack202002/uncloud/{api => uncloud_api}/tests.py (100%) rename nicohack202002/uncloud/{api => uncloud_api}/views.py (94%) diff --git a/hack.org b/hack.org deleted file mode 100644 index e69de29..0000000 diff --git a/nicohack202002/uncloud/api/models.py b/nicohack202002/uncloud/api/models.py deleted file mode 100644 index 7288ecf..0000000 --- a/nicohack202002/uncloud/api/models.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.db import models - -# Create your models here. - -class CreditCard(models.Model): - pass diff --git a/nicohack202002/uncloud/uncloud/settings.py b/nicohack202002/uncloud/uncloud/settings.py index 91bcf47..d6cbb0e 100644 --- a/nicohack202002/uncloud/uncloud/settings.py +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -37,7 +37,8 @@ INSTALLED_APPS = [ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'rest_framework' + 'rest_framework', + 'uncloud_api' ] MIDDLEWARE = [ @@ -146,3 +147,6 @@ 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 index e52fd35..e0a0b61 100644 --- a/nicohack202002/uncloud/uncloud/urls.py +++ b/nicohack202002/uncloud/uncloud/urls.py @@ -17,7 +17,7 @@ from django.contrib import admin from django.urls import path, include from rest_framework import routers -from api import views +from uncloud_api import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) diff --git a/nicohack202002/uncloud/api/__init__.py b/nicohack202002/uncloud/uncloud_api/__init__.py similarity index 100% rename from nicohack202002/uncloud/api/__init__.py rename to nicohack202002/uncloud/uncloud_api/__init__.py diff --git a/nicohack202002/uncloud/api/admin.py b/nicohack202002/uncloud/uncloud_api/admin.py similarity index 100% rename from nicohack202002/uncloud/api/admin.py rename to nicohack202002/uncloud/uncloud_api/admin.py diff --git a/nicohack202002/uncloud/api/apps.py b/nicohack202002/uncloud/uncloud_api/apps.py similarity index 71% rename from nicohack202002/uncloud/api/apps.py rename to nicohack202002/uncloud/uncloud_api/apps.py index d87006d..6830fa2 100644 --- a/nicohack202002/uncloud/api/apps.py +++ b/nicohack202002/uncloud/uncloud_api/apps.py @@ -2,4 +2,4 @@ from django.apps import AppConfig class ApiConfig(AppConfig): - name = 'api' + 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..7248a66 --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py @@ -0,0 +1,34 @@ +# Generated by Django 3.0.3 on 2020-02-21 09:40 + +from django.db import migrations, models +import django.db.models.deletion +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + 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='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/api/migrations/__init__.py b/nicohack202002/uncloud/uncloud_api/migrations/__init__.py similarity index 100% rename from nicohack202002/uncloud/api/migrations/__init__.py rename to nicohack202002/uncloud/uncloud_api/migrations/__init__.py diff --git a/nicohack202002/uncloud/uncloud_api/models.py b/nicohack202002/uncloud/uncloud_api/models.py new file mode 100644 index 0000000..2dca8ea --- /dev/null +++ b/nicohack202002/uncloud/uncloud_api/models.py @@ -0,0 +1,30 @@ +from django.db import models +import uuid + +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" + ) + + + + +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) diff --git a/nicohack202002/uncloud/api/serializers.py b/nicohack202002/uncloud/uncloud_api/serializers.py similarity index 100% rename from nicohack202002/uncloud/api/serializers.py rename to nicohack202002/uncloud/uncloud_api/serializers.py diff --git a/nicohack202002/uncloud/api/tests.py b/nicohack202002/uncloud/uncloud_api/tests.py similarity index 100% rename from nicohack202002/uncloud/api/tests.py rename to nicohack202002/uncloud/uncloud_api/tests.py diff --git a/nicohack202002/uncloud/api/views.py b/nicohack202002/uncloud/uncloud_api/views.py similarity index 94% rename from nicohack202002/uncloud/api/views.py rename to nicohack202002/uncloud/uncloud_api/views.py index c9b1e57..9310d8b 100644 --- a/nicohack202002/uncloud/api/views.py +++ b/nicohack202002/uncloud/uncloud_api/views.py @@ -5,7 +5,7 @@ from django.shortcuts import render from django.contrib.auth.models import User, Group from rest_framework import viewsets, permissions -from api.serializers import UserSerializer, GroupSerializer +from .serializers import UserSerializer, GroupSerializer class CreditCardViewSet(viewsets.ModelViewSet): diff --git a/notes-nico.org b/notes-nico.org index e2b8cac..21102f9 100644 --- a/notes-nico.org +++ b/notes-nico.org @@ -1,5 +1,21 @@ +* 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 djangorestframework django-auth-ldap stripe +* os package requirements (alpine) + openldap-dev * VPN case ** put on /orders with uuid ** register cc @@ -21,3 +37,6 @@ *** 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 From 2cda4dd57b359ed1ae01eac267d1813997011620 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Fri, 21 Feb 2020 11:32:41 +0100 Subject: [PATCH 13/15] [auth] add customer user model Best practice See https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project --- nicohack202002/uncloud/uncloud/settings.py | 19 +++++++++-- nicohack202002/uncloud/uncloud/urls.py | 1 + nicohack202002/uncloud/uncloud_api/admin.py | 5 ++- .../uncloud_api/migrations/0001_initial.py | 34 ------------------- nicohack202002/uncloud/uncloud_api/models.py | 30 +++++++++++++++- nicohack202002/uncloud/uncloud_api/views.py | 9 +++-- .../migrations => uncloud_auth}/__init__.py | 0 nicohack202002/uncloud/uncloud_auth/admin.py | 5 +++ nicohack202002/uncloud/uncloud_auth/models.py | 4 +++ 9 files changed, 63 insertions(+), 44 deletions(-) delete mode 100644 nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py rename nicohack202002/uncloud/{uncloud_api/migrations => uncloud_auth}/__init__.py (100%) create mode 100644 nicohack202002/uncloud/uncloud_auth/admin.py create mode 100644 nicohack202002/uncloud/uncloud_auth/models.py diff --git a/nicohack202002/uncloud/uncloud/settings.py b/nicohack202002/uncloud/uncloud/settings.py index d6cbb0e..be38f8f 100644 --- a/nicohack202002/uncloud/uncloud/settings.py +++ b/nicohack202002/uncloud/uncloud/settings.py @@ -38,7 +38,8 @@ INSTALLED_APPS = [ 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', - 'uncloud_api' + 'uncloud_api', + 'uncloud_auth' ] MIDDLEWARE = [ @@ -101,11 +102,13 @@ AUTH_PASSWORD_VALIDATORS = [ }, ] -# LDAP +################################################################################ +# AUTH/LDAP + import ldap from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion -AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] + 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" @@ -114,6 +117,16 @@ 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 = { diff --git a/nicohack202002/uncloud/uncloud/urls.py b/nicohack202002/uncloud/uncloud/urls.py index e0a0b61..cb50432 100644 --- a/nicohack202002/uncloud/uncloud/urls.py +++ b/nicohack202002/uncloud/uncloud/urls.py @@ -27,6 +27,7 @@ router.register(r'groups', views.GroupViewSet) # 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')) ] diff --git a/nicohack202002/uncloud/uncloud_api/admin.py b/nicohack202002/uncloud/uncloud_api/admin.py index 8c38f3f..f9f5589 100644 --- a/nicohack202002/uncloud/uncloud_api/admin.py +++ b/nicohack202002/uncloud/uncloud_api/admin.py @@ -1,3 +1,6 @@ from django.contrib import admin -# Register your models here. +from .models import Product, Feature + +admin.site.register(Product) +admin.site.register(Feature) diff --git a/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py b/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py deleted file mode 100644 index 7248a66..0000000 --- a/nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py +++ /dev/null @@ -1,34 +0,0 @@ -# Generated by Django 3.0.3 on 2020-02-21 09:40 - -from django.db import migrations, models -import django.db.models.deletion -import uuid - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - 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='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/models.py b/nicohack202002/uncloud/uncloud_api/models.py index 2dca8ea..9d4291a 100644 --- a/nicohack202002/uncloud/uncloud_api/models.py +++ b/nicohack202002/uncloud/uncloud_api/models.py @@ -1,6 +1,10 @@ -from django.db import models 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) @@ -17,6 +21,8 @@ class Product(models.Model): default="not_recurring" ) + def __str__(self): + return "{}".format(self.name) @@ -28,3 +34,25 @@ class Feature(models.Model): 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/views.py b/nicohack202002/uncloud/uncloud_api/views.py index 9310d8b..88e0543 100644 --- a/nicohack202002/uncloud/uncloud_api/views.py +++ b/nicohack202002/uncloud/uncloud_api/views.py @@ -1,8 +1,7 @@ from django.shortcuts import render +from django.contrib.auth import get_user_model +from django.contrib.auth.models import Group -# Create your views here. - -from django.contrib.auth.models import User, Group from rest_framework import viewsets, permissions from .serializers import UserSerializer, GroupSerializer @@ -12,7 +11,7 @@ class CreditCardViewSet(viewsets.ModelViewSet): """ API endpoint that allows credit cards to be listed """ - queryset = User.objects.all().order_by('-date_joined') + queryset = get_user_model().objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] @@ -23,7 +22,7 @@ class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ - queryset = User.objects.all().order_by('-date_joined') + queryset = get_user_model().objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] diff --git a/nicohack202002/uncloud/uncloud_api/migrations/__init__.py b/nicohack202002/uncloud/uncloud_auth/__init__.py similarity index 100% rename from nicohack202002/uncloud/uncloud_api/migrations/__init__.py rename to nicohack202002/uncloud/uncloud_auth/__init__.py 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/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 From 6ba224638a1cbb24b4d1950d3b85008d5d3ca6a9 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Fri, 21 Feb 2020 11:42:54 +0100 Subject: [PATCH 14/15] fix migrations / custom user late introduce Signed-off-by: Nico Schottelius --- .../uncloud_api/migrations/0001_initial.py | 50 +++++++++++++++++++ .../uncloud_api/migrations/__init__.py | 0 .../uncloud_auth/migrations/0001_initial.py | 44 ++++++++++++++++ .../uncloud_auth/migrations/__init__.py | 0 4 files changed, 94 insertions(+) create mode 100644 nicohack202002/uncloud/uncloud_api/migrations/0001_initial.py create mode 100644 nicohack202002/uncloud/uncloud_api/migrations/__init__.py create mode 100644 nicohack202002/uncloud/uncloud_auth/migrations/0001_initial.py create mode 100644 nicohack202002/uncloud/uncloud_auth/migrations/__init__.py 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_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 From a5695ffa488c9666fb63496d5949a6e83fe4f9e5 Mon Sep 17 00:00:00 2001 From: Nico Schottelius Date: Fri, 21 Feb 2020 11:43:17 +0100 Subject: [PATCH 15/15] two more related user problems Signed-off-by: Nico Schottelius --- nicohack202002/uncloud/uncloud_api/serializers.py | 6 ++++-- nicohack202002/uncloud/uncloud_auth/apps.py | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 nicohack202002/uncloud/uncloud_auth/apps.py diff --git a/nicohack202002/uncloud/uncloud_api/serializers.py b/nicohack202002/uncloud/uncloud_api/serializers.py index f5a5a92..57532f2 100644 --- a/nicohack202002/uncloud/uncloud_api/serializers.py +++ b/nicohack202002/uncloud/uncloud_api/serializers.py @@ -1,10 +1,12 @@ -from django.contrib.auth.models import User, Group +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 = User + model = get_user_model() fields = ['url', 'username', 'email', 'groups'] 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'