This commit is contained in:
iriska-gri committed 2023-10-30 10:48:31 +03:00
1 parent 6ae52dc583
commit 26e5b08e2e
1043 files changed
+1671

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
from django.contrib import admin
from .models import *
# Register your models here.
class UserAdmin(admin.ModelAdmin):
list_display=('username','fio', 'created_at', 'updated_at', 'is_active', 'is_staff')
search_fields = ('username',)
admin.site.register(User, UserAdmin)
+7
View File
@@ -0,0 +1,7 @@
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'accounts'
verbose_name='Аккаунты'
+69
View File
@@ -0,0 +1,69 @@
import jwt
import requests
import json
from django.conf import settings
from django.forms.models import model_to_dict
from rest_framework import authentication, exceptions
from datetime import datetime
from .models import User
from userauth.models import *
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from django.contrib.auth import get_user_model
User = get_user_model()
myDEBUG=True
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user.userinfo)
# TODO В зависимости от базы Алексея, добавить поля или нет - надо подумать
token['user']=model_to_dict(user.userinfo)
token['user']['is_active']=user.is_active
token['user']['is_staff']=user.is_staff
# !ТУТ СДЕЛАТь ФОТО НАВЕРНОЕ
# token['user']['last_login']= user.last_login
return token
from django.contrib.auth.backends import ModelBackend
# from django.contrib.auth.models import User
from django.utils import timezone
class CustomAuth(ModelBackend):
def authenticate(self, request, **kwargs):
username = kwargs['username']
password = kwargs['password']
status_code=0
# !ТУт стучим в AD, потом к Алексею
if myDEBUG!=True:
resp= requests.post('http://10.252.44.13:8005/getAD', json.dumps({'user': username, 'password':password, 'usercheck': username}))
# if True:
status_code=resp.status_code
else:
status_code=200
if status_code==200:
try:
user = DictEmployee.objects.using('user_directory').get(login=username)
if user.deleted!=1:
homeuser, created = User.objects.get_or_create(username=username)
homeuser.last_login= timezone.now()
user.is_active=homeuser.is_active
user.is_staff=homeuser.is_staff
user.last_login=homeuser.last_login.strftime('%Y-%d-%m %H:%M:%S')
homeuser.save()
homeuser.last_login=user.last_login
user.id=homeuser.id
homeuser.userinfo = user
return homeuser
except User.DoesNotExist:
pass
+34
View File
@@ -0,0 +1,34 @@
# Generated by Django 4.2.3 on 2023-10-25 13:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('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')),
('password', models.CharField(blank=True, max_length=128, null=True)),
('username', models.CharField(db_index=True, max_length=255, unique=True)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('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={
'abstract': False,
},
),
]
@@ -0,0 +1,23 @@
# Generated by Django 4.2.3 on 2023-10-25 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='username2',
field=models.CharField(db_index=True, max_length=255, null=True, unique=True),
),
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(blank=True, max_length=128),
),
]
@@ -0,0 +1,22 @@
# Generated by Django 4.2.3 on 2023-10-25 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_user_username2_alter_user_password'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='username2',
),
migrations.AlterField(
model_name='user',
name='password',
field=models.CharField(blank=True, max_length=128, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 4.2.3 on 2023-10-25 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_remove_user_username2_alter_user_password'),
]
operations = [
migrations.AlterField(
model_name='user',
name='last_login',
field=models.DateTimeField(auto_now=True, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 4.2.3 on 2023-10-25 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_alter_user_last_login'),
]
operations = [
migrations.AlterField(
model_name='user',
name='last_login',
field=models.DateTimeField(blank=True, null=True, verbose_name='last login'),
),
]
View File
Whitespace-only changes.
+70
View File
@@ -0,0 +1,70 @@
from datetime import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import (AbstractBaseUser, BaseUserManager)
import jwt
from django.contrib.auth.models import PermissionsMixin
from django.conf import settings
# from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.serializers import ValidationError
# from orgmanagment.models import *
from datetime import datetime, timedelta
import requests
from django.contrib.auth import authenticate
import json
from django.forms.models import model_to_dict
from userauth.models import DictEmployee
# all_fk: dict = {
# "otdel": Otdel,
# "department": Department,
# "organization":Organization,
# "position": Position,
# "rank": Rank
# }
# class Position(models.Model):
# name= models.CharField(verbose_name='Название', max_length=150, blank=True)
# class Meta:
# verbose_name = "Должность"
# verbose_name_plural = "Должности"
# def __str__(self):
# return str(self.name)
class UserManager(BaseUserManager):
def create_superuser(self, username, password):
""" Создает и возввращет пользователя с привилегиями суперадмина. """
if password is None:
raise TypeError('Superusers must have a password.')
user = self.create_user(username, password)
user.is_superuser = True
user.is_staff = True
user.set_password(password)
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
password = models.CharField(max_length=128, null=True,blank=True)
username = models.CharField(db_index=True, max_length=255, unique=True)
# username2 = models.CharField(db_index=True, null=True, max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# last_login = models.DateTimeField(auto_now=True, null=True)
# external=models.ForeignKey(DictEmployee,db_constraint=False, null=True, on_delete=models.PROTECT)
objects = UserManager()
USERNAME_FIELD = 'username'
# REQUIRED_FIELDS = ['username']
def __str__(self):
return str(self.username)
def fio(self):
return DictEmployee.objects.using('user_directory').get(login=self.username).fio
+23
View File
@@ -0,0 +1,23 @@
import json
from rest_framework.renderers import JSONRenderer
class UserJSONRenderer(JSONRenderer):
charset = 'utf-8'
def render(self, data, media_type=None, renderer_context=None):
# Если мы получим ключ token как часть ответа, это будет байтовый
# объект. Байтовые объекты плохо сериализуются, поэтому нам нужно
# декодировать их перед рендерингом объекта User.
token = data.get('token', None)
if token is not None and isinstance(token, bytes):
# Как говорится выше, декодирует token если он имеет тип bytes.
data['token'] = token.decode('utf-8')
# print(data)
# Наконец, мы можем отобразить наши данные в простанстве имен 'user'.
return json.dumps({
'user': data,
})
+4
View File
@@ -0,0 +1,4 @@
from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+18
View File
@@ -0,0 +1,18 @@
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import *
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,TokenVerifyView
)
urlpatterns = [
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('token/verify/', TokenVerifyView.as_view(), name='token_access'),
path('getuser/', getuserAPIView.as_view(), name='getuserAPIView'),
]
+50
View File
@@ -0,0 +1,50 @@
from rest_framework import status
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from .renderers import UserJSONRenderer
from userauth.models import *
from .models import *
# from .serializers import RegistrationSerializer
# class RegistrationAPIView(APIView):
# """
# Разрешить всем пользователям (аутентифицированным и нет) доступ к данному эндпоинту.
# """
# permission_classes = (AllowAny,)
# serializer_class = RegistrationSerializer
# renderer_classes = (UserJSONRenderer,)
# def post(self, request):
# user = request.data.get("user",{})
# # Паттерн создания сериализатора, валидации и сохранения - довольно
# # стандартный, и его можно часто увидеть в реальных проектах.
# serializer = self.serializer_class(data=user)
# serializer.is_valid(raise_exception=True)
# serializer.save()
# return Response(serializer.data, status=status.HTTP_201_CREATED)
class UserAPIView(APIView):
permission_classes = (IsAuthenticated,)
# serializer_class = RegistrationSerializer
def get(self, request):
# serializer = self.serializer_class(data=request.user)
# serializer.is_valid(raise_exception=True)
return Response('user')
class getuserAPIView(APIView):
permission_classes = (AllowAny,)
def get(self, request):
userlogin = request.query_params.get('userlogin')
queryset = model_to_dict(DictEmployee.objects.using('user_directory').get(login=userlogin))
# queryset['responsible'] = [model_to_dict(x) for x in OrderResponsibilityEmployee.objects.using('user_directory').raw("SELECT * FROM order_responsibility_employee")]
return Response(queryset)