Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • infrastruktur/warpinfra
  • dray/warpinfra
  • HoelShare/warpinfra
3 results
Show changes
Showing with 322 additions and 59 deletions
......@@ -6,33 +6,63 @@ from warpauth.models import LdapUser
class ProductCategory(models.Model):
name = models.CharField(max_length=100, unique=True)
position = models.FloatField(null=True, blank=True, default=0)
def __str__(self):
return self.name
class ProductCategorySerializer(serializers.ModelSerializer):
class Meta:
model = ProductCategory
fields = ['id', 'name','position']
class Product(models.Model):
name = models.CharField(max_length=100, null=True)
price = models.FloatField()
price_ek = models.FloatField()
price_vk = models.FloatField()
category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True)
count = models.IntegerField()
stock_count = models.IntegerField(null=True, blank=True, default=0)
barcode = models.CharField(max_length=100, null=True, blank=True)
position = models.FloatField(null=True, blank=True, default=0)
def __str__(self):
return self.name
class ProductSerializer(serializers.ModelSerializer):
category = serializers.StringRelatedField()
class Meta:
model = Product
fields = ['id', 'name', 'price', 'category', 'count']
fields = ['id', 'name', 'price_vk', 'category', 'barcode','stock_count','position']
class Transaction(models.Model):
date = models.DateTimeField(auto_now_add=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
type = models.IntegerField() # 1: aufladen; 2:kaufen
amount = models.FloatField()
cash_paid = models.BooleanField(default=False)
def __str__(self):
return str(self.amount) #self.product.name+" - "+self.amount
class TransactionLog(models.Model):
uid = models.CharField(max_length=100)
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, null=True)
class UserCredit(models.Model):
uid = models.CharField(max_length=100,unique=True)
card_id = models.CharField(max_length=10, unique=True)
card_id = models.CharField(max_length=255, null=True, blank=True) # Unique only with django 1.11
credit = models.FloatField()
pinCode = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.uid
class UserCreditSerializer(serializers.ModelSerializer):
class Meta:
model = UserCredit
fields = ['uid', 'card_id', 'credit']
fields = ['uid', 'card_id', 'credit', 'pinCode']
......@@ -14,7 +14,7 @@
{{ news.message }}
</div>
<div class="panel-footer">
{% trans "Created by" %} {{ news.user }} {{ news.created | naturaltime }}
{% trans "created by" %} {{ news.user }} {{ news.created | naturaltime }}
</div>
</div>
{% endfor %}
......
......@@ -6,6 +6,9 @@ urlpatterns = [
url(r'^api/users/$', views.user_list),
url(r'^api/users/(?P<user_id>\w+)/$', views.user_list),
url(r'^api/products/$', views.product_list),
url(r'^api/gen_token/$', views.gen_token),
url(r'^api/categories/$', views.category_list),
# url(r'^api/gen_token/$', views.gen_token),
url(r'^api/transactions/(?P<user_id>\w+)/$', views.multiple_transaction),
url(r'^api/products/(?P<prod_id>\w+)/barcode/$', views.addBarcode),
]
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from warpauth.models import LdapUser
from warppay.models import UserCredit, UserCreditSerializer, Product, ProductSerializer
from warppay.models import UserCredit, UserCreditSerializer, Product, ProductSerializer, ProductCategory, ProductCategorySerializer, Transaction
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
......@@ -12,18 +13,46 @@ from rest_framework import status
# logging.getLogger('main').info(token.key)
@api_view(['GET'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def category_list(request):
if request.method == 'GET':
products = ProductCategory.objects.all()
serializer = ProductCategorySerializer(products, context={'request': request}, many=True)
return Response(serializer.data)
return Response()
@api_view(['GET', 'PUT'])
#@authentication_classes((TokenAuthentication,))
#@permission_classes((IsAuthenticated,))
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def product_list(request):
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products,context={'request': request}, many=True)
serializer = ProductSerializer(products, context={'request': request}, many=True)
return Response(serializer.data)
elif request.method == 'PUT':
return Response()
return Response()
@api_view(['PUT'])
def addBarcode(request, prod_id=0):
if request.method == 'PUT':
try:
product = Product.objects.get(id=prod_id)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if not product.barcode:
product.barcode = request.data['barcode']
product.save()
return Response()
else:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
@api_view(['GET'])
def gen_token(request):
......@@ -32,9 +61,9 @@ def gen_token(request):
return Response(token)
return Response()
@api_view(['GET', 'PUT', 'POST'])
#@authentication_classes((TokenAuthentication,))
#@permission_classes((IsAuthenticated,))
@api_view(['GET', 'PUT'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def user_list(request, user_id = 0):
if request.method == 'GET':
sync_users()
......@@ -48,15 +77,21 @@ def user_list(request, user_id = 0):
elif request.method == 'PUT':
if not user_id:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
sync_users()
try:
print(request.data)
user = UserCredit.objects.get(uid=user_id)
if "credit" in request.data:
user.credit = request.data['credit']
if "card_id" in request.data:
user.card_id = request.data['card_id']
user.save();
try:
ldap_user = LdapUser.objects.get(uid=str(request.data['uid']))
if not ldap_user.card_id:
ldap_user.card_id = request.data['card_id']
ldap_user.save()
else:
return Response(status=status.HTTP_403_FORBIDDEN)
except:
pass
sync_users()
return Response(UserCreditSerializer(user).data)
except UserCredit.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
......@@ -79,14 +114,80 @@ def user_list(request, user_id = 0):
serializer = UserCreditSerializer(u)
return Response(serializer.data, status=state)
return Response()
@api_view(['PUT'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def multiple_transaction(request, user_id=None):
if request.method == 'PUT':
if not user_id:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
try:
u = UserCredit.objects.get(uid=str(user_id))
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
transactions = []
products = []
for transact in request.data:
if 'trans_type' not in transact:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
t = Transaction()
t.type = int(transact['trans_type'])
if t.type == 1:
if 'amount' not in transact or ('amount' in transact and float(transact['amount'] < 0)):
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
if 'cash_paid' in transact:
t.cash_paid = bool(transact['cash_paid'])
else:
t.cash_paid = True
t.amount = float(transact['amount'])
u.credit += t.amount
elif t.type == 2:
try:
product = Product.objects.get(id=transact['product']['id'])
t.product = product
if 'cash_paid' in transact:
t.cash_paid = bool(transact['cash_paid'])
t.amount = product.price_vk
if not t.cash_paid:
u.credit -= t.amount
product.stock_count -= 1
products.append(product)
except:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
else:
return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
transactions.append(t)
for t in transactions:
t.save()
print(t)
for p in products:
p.save()
print(p)
u.save()
print(u)
return Response()
def sync_users():
for user in LdapUser.objects.all():
for ldapuser in LdapUser.objects.all():
try:
u = UserCredit(uid=user.uid, card_id=user.card_id, credit=0.0)
u = UserCredit.objects.get(uid=ldapuser.uid)
if ldapuser.card_id:
u.card_id = ldapuser.card_id
u.save()
if ldapuser.pinCode:
u.pinCode = ldapuser.pinCode
u.save()
except ObjectDoesNotExist:
u = UserCredit(uid=ldapuser.uid, card_id=ldapuser.card_id, pinCode="", credit=0.0)
u.save()
except IntegrityError:
pass
except:
pass
from django.contrib import admin
from django.apps import AppConfig
class WarpmainConfig(AppConfig):
name = 'warpservice'
from django.db import models
from django.conf.urls import url, include
from warpservice import views
urlpatterns = [
url(r'^api/services/3dprinter$', views.printer_3d),
]
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from warpauth.models import LdapUser
@api_view(['GET'])
def printer_3d(request):
ret= {"admin":{}, "user":{}}
users = LdapUser.objects.filter(memberof__contains="cn=3dprint-user,ou=infrastructure,dc=warpzone,dc=ms").filter(memberof__contains="cn=active,ou=groups,dc=warpzone,dc=ms")
for user in users:
if user.card_id:
ret["user"][user.card_id] = user.uid
return Response(ret)
No preview for this file type
......@@ -2,7 +2,8 @@ import os
import ldap
import logging
import configparser
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType
from django_auth_ldap.config import LDAPSearch, GroupOfUniqueNamesType, GroupOfNamesType, PosixGroupType
from django.core.urlresolvers import reverse_lazy
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
......@@ -11,6 +12,15 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config = configparser.RawConfigParser()
config.read('/etc/warpinfra/config.ini')
# COMMON
APPS = [app.strip() for app in config.get('common','APPS').split(",")]
# MYSQL
MYSQL_HOST = config.get('mysql','MYSQL_HOST')
MYSQL_PORT = config.get('mysql','MYSQL_PORT')
MYSQL_USER = config.get('mysql','MYSQL_USER')
MYSQL_PASS = config.get('mysql','MYSQL_PASS')
MYSQL_NAME = config.get('mysql','MYSQL_NAME')
# LDAP
LDAP_HOST = "ldap://"+config.get('ldap','LDAP_HOST')
......@@ -38,16 +48,26 @@ EMAIL_SUBJECT_PREFIX = config.get('email','SUBJECT_PREFIX')
PW_RESET_TOKEN_LIFETIME = config.get('security','PW_RESET_TOKEN_LIFETIME')
SECRET_KEY = config.get('security','SECRET_KEY')
# MATTERMOST
API_KEY = config.get('mattermost','API_KEY')
# DEBUG
DEBUG = config.getboolean('debug','DEBUG')
DEBUG = config.getboolean('debug', 'DEBUG')
# MISC
LOG_PATH = config.get('misc', 'LOG_PATH')
INSTANCE_NAME = config.get('common', 'INSTANCE_NAME')
ALLOWED_HOSTS = [config.get('security','ALLOWED_HOSTS')]
LOGIN_URL = 'two_factor:login'
LOGOUT_URL = 'logout'
LOGIN_REDIRECT_URL = '/'
MEDIA_ROOT = 'templates/media/'
MEDIA_URL = '/media/'
ALLOWED_HOSTS = []
INSTALLED_APPS = (
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
......@@ -55,15 +75,17 @@ INSTALLED_APPS = (
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django_mysql',
'bootstrapform',
'warpmain',
'warpauth',
'warpfood',
# WARPPAY
'bootstrap3_datetime',
'rest_framework',
'rest_framework.authtoken',
'warppay'
)
'django_otp',
'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp',
'two_factor'
]
INSTALLED_APPS.extend(APPS)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
......@@ -71,6 +93,7 @@ MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
......@@ -104,10 +127,24 @@ LOCALE_PATHS = (
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'warpzone.db'
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_NAME,
'USER': MYSQL_USER,
'PASSWORD': MYSQL_PASS,
'HOST': MYSQL_HOST,
'PORT': MYSQL_PORT,
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1",
'charset': 'utf8mb4',
},
},
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': '/opt/database/warpzone.db'
# },
'ldap': {
'ENGINE': 'ldapdb.backends.ldap',
'NAME': LDAP_HOST,
......@@ -119,7 +156,13 @@ DATABASE_ROUTERS = ['ldapdb.router.Router']
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'de'
LANGUAGES = (
('de', 'German'),
('en', 'English'),
)
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
......@@ -153,10 +196,10 @@ AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"}
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(LDAP_GROUP_SEARCH_PATH,
ldap.SCOPE_SUBTREE, "(objectClass=posixGroup)"
ldap.SCOPE_SUBTREE, "(objectClass=groupOfUniqueNames)"
)
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType()
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
......@@ -169,13 +212,30 @@ AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_GROUPS = True
AUTH_LDAP_GROUP_CACHE_TIMEOUT = 10
logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
hdlr = logging.FileHandler('/tmp/ldap.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': LOG_PATH+'/error.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
'django_auth_ldap': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
......@@ -189,4 +249,10 @@ REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
if not DEBUG:
REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = [
'rest_framework.renderers.JSONRenderer'
]
......@@ -5,9 +5,24 @@ from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, }),
url(r'^', include('warpmain.urls')),
url(r'^', include('warpauth.urls')),
url(r'^', include('warpfood.urls')),
# url(r'^', include('warppay.urls')),
url(r'^media/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.MEDIA_ROOT, }),
]
if "warpmain" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warpmain.urls')))
if "warpauth" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warpauth.urls')))
if "warpfood" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warpfood.urls')))
if "warpapi" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warpapi.urls')))
if "warppay" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warppay.urls')))
if "warpservice" in settings.INSTALLED_APPS:
urlpatterns.append(url(r'^', include('warpservice.urls')))
from django.core.mail import send_mail
from django.conf import settings
from django.utils.translation import ugettext as _
from matterhook import Webhook
import logging
page_context = {'pages': [
{"link": "pizza", "name": _("pizza_sheet")},
{"link": "about", "name": _("about")},
], 'debug': settings.DEBUG}
def send_to_mattermost(username, channel, message):
try:
if settings.API_KEY:
hook = Webhook("https://mattermost.warpzone.ms", settings.API_KEY)
if settings.DEBUG:
username = "["+channel+"] "+username
channel = "warpinfradebug"
hook.send(message, channel=channel, username=username)
except Exception as e:
logging.getLogger("django").error(e)
def send_email(to_address, subject, content):
try:
......@@ -15,5 +36,3 @@ def send_email(to_address, subject, content):
print(e)
return False