develop #4

Merged
s460930 merged 29 commits from develop into master 2020-12-07 15:22:26 +01:00
47 changed files with 812 additions and 5 deletions

5
.gitignore vendored
View File

@ -1,3 +1,6 @@
.idea/ .idea/
.idea .idea/*
*.iml *.iml
.idea
*__pycache__/
__pycache__/

14
Jenkinsfile vendored
View File

@ -1,11 +1,17 @@
pipeline { pipeline {
agent any agent { docker { image 'python:3.7.2' } }
stages { stages {
stage('Test') { stage('Build and test') {
steps { steps {
echo 'Test pipeline' sh 'pwd'
sh 'ls'
dir("${env.WORKSPACE}/rest-app"){
sh 'pwd'
sh 'ls'
sh 'python3 -m venv venv && . venv/bin/activate && pip3 install -r requirements.txt && python3 manage.py migrate && python3 manage.py test'
}
} }
} }
} }
} }

128
client/app.py Normal file
View File

@ -0,0 +1,128 @@
import tkinter as tk
import requests
FONT= ("Verdana", 12)
FONT_LARGE= ("Verdana", 20)
URL = "http://localhost:8000/api/authenticate"
TOKEN = ""
class SmartPicasso(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
self.title('SmartPicasso')
self.geometry('610x460')
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (LoginPage, MainView, RegisterView):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(LoginPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class LoginPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="SmartPicasso", font=FONT_LARGE)
label.pack(pady=10,padx=10)
label1 = tk.Label(self, text='Login:', font=FONT)
label1.pack()
input1 = tk.Entry(self)
input1.pack()
label2 = tk.Label(self, text='Password:', font=FONT)
label2.pack()
input2 = tk.Entry(self)
input2.pack()
button = tk.Button(self, text="Login", font=FONT, command=lambda: self.login(controller, input1.get(), input2.get()))
button.pack()
button2 = tk.Button(self, text="Register", font=FONT, command=lambda: controller.show_frame(RegisterView))
button2.pack()
def login(self, controller, login, passw,):
print(login)
print(passw)
data = {
"email": str(login),
"password": str(passw)
}
resp = requests.post(URL, json=data)
print(resp)
if (resp.status_code==200):
response=resp.json()
TOKEN = response['token']
controller.show_frame(MainView)
else:
print("bad pass")
badPassLabel = tk.Label(self, text='Wrong login/password!', font=FONT)
badPassLabel.pack()
return()
class MainView(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="SmartPicasso", font=FONT_LARGE)
label.pack(pady=10,padx=10)
label_u = tk.Label(self, text="Main menu", font=FONT)
label_u.pack(pady=10,padx=10)
class RegisterView(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="SmartPicasso", font=FONT_LARGE)
label.pack(pady=10,padx=10)
label_u = tk.Label(self, text="Register", font=FONT)
label_u.pack(pady=10,padx=10)
label1 = tk.Label(self, text='Login:', font=FONT)
label1.pack()
input1 = tk.Entry(self)
input1.pack()
label2 = tk.Label(self, text='Password:', font=FONT)
label2.pack()
input2 = tk.Entry(self)
input2.pack()
label3 = tk.Label(self, text='Email:', font=FONT)
label3.pack()
input3 = tk.Entry(self)
input3.pack()
button = tk.Button(self, text="Register", font=FONT, command=lambda: controller.show_frame(RegisterView))
button.pack()
app = SmartPicasso()
app.mainloop()

BIN
rest-app/db.sqlite3 Normal file

Binary file not shown.

22
rest-app/manage.py Executable file
View File

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

View File

@ -0,0 +1,3 @@
django
djangorestframework
djangorestframework-jwt

View File

Binary file not shown.

Binary file not shown.

View File

View File

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

View File

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

View File

@ -0,0 +1,32 @@
# Generated by Django 3.1.3 on 2020-11-30 21:16
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
atomic = False
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('is_superuser', models.BooleanField(default=False)),
],
options={
'db_table': 'login',
},
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 3.1.3 on 2020-11-30 21:19
from django.db import migrations
class Migration(migrations.Migration):
atomic = False
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='user',
table='user',
),
]

View File

@ -0,0 +1,72 @@
"""
@author p.dolata
"""
import uuid
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class UserManager(BaseUserManager):
"""
Manager for custom user model
"""
def create_user(self, email, password=None):
"""
Create and return `User` with an email, username and password
:param email: email of user
:param password: password of user
:return: model of new user
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Create and return a `User` with superuser (admin) permissions
:param email: email of superuser
:param password: password of superuser
:return: model of new superuser
"""
if password is None:
raise TypeError('Superusers must have a password')
user = self.create_user(email, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(AbstractBaseUser):
"""
Model of user
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True
)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
class Meta:
"""
Class to set table name in database
"""
db_table = 'user'

View File

@ -0,0 +1,69 @@
"""
@author p.dolata
"""
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from smartpicasso.app.user.models import User
from smartpicasso.app.user_profile.models import UserProfile
JWT_PAYLOAD_HANDLER = api_settings.JWT_PAYLOAD_HANDLER
JWT_ENCODE_HANDLER = api_settings.JWT_ENCODE_HANDLER
class UserSerializer(serializers.ModelSerializer):
"""
Class to manage serializing UserProfile
"""
class Meta:
model = UserProfile
fields = ('first_name', 'last_name')
class UserRegistrationSerializer(serializers.ModelSerializer):
"""
Class to manage serializing user during registration
"""
profile = UserSerializer(required=False)
class Meta:
model = User
fields = ('email', 'password', 'profile')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
profile_data = validated_data.pop('profile')
user = User.objects.create_user(**validated_data)
UserProfile.objects.create(
user=user,
first_name=profile_data['first_name'],
last_name=profile_data['last_name']
)
return user
class UserLoginSerializer(serializers.Serializer):
"""
Class to manage serializing user during singing in
"""
email = serializers.CharField(max_length=255)
password = serializers.CharField(max_length=128, write_only=True)
token = serializers.CharField(max_length=255, read_only=True)
def validate(self, data):
email = data.get('email', None)
password = data.get('password', None)
user = authenticate(email=email, password=password)
if user is None:
raise serializers.ValidationError('An user with provided email and password is not found')
try:
payload = JWT_PAYLOAD_HANDLER(user)
jwt_token = JWT_ENCODE_HANDLER(payload)
update_last_login(None, user)
except User.DoesNotExist:
raise serializers.ValidationError('User with given email and password does not exist')
return {'email': user.email, 'token': jwt_token}

View File

@ -0,0 +1,87 @@
from django.test import TestCase
from django.urls import reverse
from rest_framework import serializers
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from smartpicasso.app.user.models import User, UserManager
from smartpicasso.app.user.serializers import UserLoginSerializer, UserRegistrationSerializer
class UserApiTest(APITestCase):
client = APIClient()
def test_login_when_user_non_exist(self):
url = reverse('authenticate')
response = self.client.post(url, {'email': 'non-exist', 'password': '123'}, format='json')
assert response.status_code == 400
def test_login_when_user_exist(self):
User.objects.create_user(email='test@test.com', password='test')
url = reverse('authenticate')
response = self.client.post(url, {'email': 'test@test.com', 'password': 'test'}, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['success'], 'True')
self.assertIn('token', response.data)
class UserTest(TestCase):
def test_user_str(self):
email = 'test@test.com'
user = User.objects.create_user(email=email, password='test')
self.assertEqual(str(user), email)
class UserLoginSerializerTest(TestCase):
serializer = UserLoginSerializer()
def test_validate_wrong_credentials(self):
data = {'email': 'test@test.com', 'password': '123'}
self.assertRaises(serializers.ValidationError, self.serializer.validate, data)
def test_validate_success(self):
User.objects.create_user(email='test@test.com', password='test')
data = {'email': 'test@test.com', 'password': 'test'}
result = self.serializer.validate(data)
self.assertEqual(result['email'], 'test@test.com')
self.assertIn('token', result)
class UserRegistrationSerializerTest(TestCase):
serializer = UserRegistrationSerializer()
def test_create(self):
profile = {"first_name": "test", "last_name": "test"}
user = self.serializer.create({"email": "test@test.com", "password": "test", "profile": profile})
self.assertNotEqual(user, None)
self.assertEqual(user.email, "test@test.com")
class UserManagerTest(TestCase):
manager = User.objects
def test_create_user_none_email(self):
email = None
self.assertRaises(ValueError, self.manager.create_user, email)
def test_create_user(self):
user = self.manager.create_user("test@test.pl", "test")
self.assertNotEqual(user, None)
self.assertEqual(user.email, "test@test.pl")
self.assertEqual(user.is_active, True)
self.assertEqual(user.is_superuser, False)
self.assertEqual(user.is_staff, False)
def test_create_superuser_none_password(self):
password = None
self.assertRaises(TypeError, self.manager.create_superuser, "super@test.pl", password)
def test_create_superuser(self):
user = self.manager.create_superuser("super@test.pl", "test")
self.assertNotEqual(user, None)
self.assertEqual(user.email, "super@test.pl")
self.assertEqual(user.is_active, True)
self.assertEqual(user.is_superuser, True)
self.assertEqual(user.is_staff, True)

View File

@ -0,0 +1,12 @@
"""
@author: p.dolata
"""
from django.conf.urls import url
from smartpicasso.app.user.views import UserLoginView, UserRegistrationView
urlpatterns = [
url(r'^authenticate', UserLoginView.as_view(), name='authenticate'),
url(r'^register', UserRegistrationView.as_view(), name='register')
]

View File

@ -0,0 +1,48 @@
from rest_framework import status
from rest_framework.generics import RetrieveAPIView, CreateAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from smartpicasso.app.user.serializers import UserLoginSerializer, UserRegistrationSerializer
class UserLoginView(RetrieveAPIView):
"""
View for user login
"""
permission_classes = (AllowAny,)
serializer_class = UserLoginSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
response = {
'success': 'True',
'status_code': status.HTTP_200_OK,
'message': 'User logged in successfully',
'token': serializer.data['token']
}
status_code = status.HTTP_200_OK
return Response(response, status=status_code)
class UserRegistrationView(CreateAPIView):
"""
View for user registration
"""
permission_classes = (AllowAny,)
serializer_class = UserRegistrationSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
status_code = status.HTTP_201_CREATED
response = {
'success': 'True',
'status_code': status_code,
'message': 'User registered successfully'
}
return Response(response, status=status_code)

View File

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

View File

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

View File

@ -0,0 +1,30 @@
# Generated by Django 3.1.3 on 2020-11-30 21:41
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('user', '0002_auto_20201130_2119'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('first_name', models.CharField(max_length=50)),
('last_name', models.CharField(max_length=50)),
('phone_number', models.CharField(blank=True, max_length=10, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to='user.user')),
],
options={
'db_table': 'user_profile',
},
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 3.1.3 on 2020-12-01 21:54
from django.db import migrations
class Migration(migrations.Migration):
atomic = False
dependencies = [
('user_profile', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='phone_number',
),
]

View File

@ -0,0 +1,23 @@
"""
@author p.dolata
"""
import uuid
from django.db import models
from smartpicasso.app.user.models import User
class UserProfile(models.Model):
"""
Model representing user's profile
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
first_name = models.CharField(max_length=50, unique=False)
last_name = models.CharField(max_length=50, unique=False)
class Meta:
"""
Meta to se table name in database
"""
db_table = 'user_profile'

View File

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

View File

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

View File

@ -0,0 +1,16 @@
"""
ASGI config for smartpicasso 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartpicasso.settings')
application = get_asgi_application()

View File

@ -0,0 +1,158 @@
"""
Django settings for smartpicasso project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from datetime import timedelta
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xj*l&*)en@2m!0z))!3@-cf!i=tsuvp@tpp&5m)dd@+4gu1crh'
# 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',
'smartpicasso.app.user',
'smartpicasso.app.user_profile'
]
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 = 'smartpicasso.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 = 'smartpicasso.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'user.User'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.IsAdminUser'
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication'
]
}
JWT_AUTH = {
'JWT_ENCODE_HANDLER':
'rest_framework_jwt.utils.jwt_encode_handler',
'JWT_DECODE_HANDLER':
'rest_framework_jwt.utils.jwt_decode_handler',
'JWT_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_payload_handler',
'JWT_PAYLOAD_GET_USER_ID_HANDLER':
'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
'JWT_SECRET_KEY': 'SECRET_KEY',
'JWT_GET_USER_SECRET_KEY': None,
'JWT_PUBLIC_KEY': None,
'JWT_PRIVATE_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_LEEWAY': 0,
'JWT_EXPIRATION_DELTA': timedelta(days=30),
'JWT_AUDIENCE': None,
'JWT_ISSUER': None,
'JWT_ALLOW_REFRESH': False,
'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=30),
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
'JWT_AUTH_COOKIE': None,
}

View File

@ -0,0 +1,22 @@
"""smartpicasso URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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
urlpatterns = [
path('api/', include('smartpicasso.app.user.urls')),
path('admin/', admin.site.urls),
]

View File

@ -0,0 +1,16 @@
"""
WSGI config for smartpicasso 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.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartpicasso.settings')
application = get_wsgi_application()