Added all the functionality of app and admin
This commit is contained in:
@@ -3,6 +3,7 @@ from rest_framework import serializers
|
||||
from module_iam.models import IAmPrincipal
|
||||
from module_project import constants
|
||||
from django.contrib.auth import authenticate
|
||||
from rest_framework.validators import UniqueValidator
|
||||
|
||||
# class BasePasswordSerializer(serializers.Serializer):
|
||||
# confirm_password = serializers.CharField(write_only=True, required=True)
|
||||
@@ -22,6 +23,10 @@ from django.contrib.auth import authenticate
|
||||
# return instance
|
||||
|
||||
class RegistrationSerializer(serializers.ModelSerializer):
|
||||
email = serializers.EmailField(
|
||||
required=True,
|
||||
validators=[UniqueValidator(queryset=IAmPrincipal.objects.all(), message="This email address is already in use.")]
|
||||
)
|
||||
password = serializers.CharField(write_only=True, required=True)
|
||||
confirm_password = serializers.CharField(write_only=True, required=True)
|
||||
|
||||
|
||||
@@ -12,5 +12,11 @@ urlpatterns = [
|
||||
path("verify-otp/", views.OTPVerificationView.as_view()),
|
||||
path("forget-password/", views.ForgetPasswordView.as_view()),
|
||||
|
||||
# path("profile/", views.Profile)
|
||||
path("account/deactivate/", views.AccountDeactivateView.as_view()),
|
||||
|
||||
path('google-signin/', views.GoogleSignin.as_view(), name='google_signin'),
|
||||
path('apple-signin/', views.AppleSignin.as_view(), name='apple_signin'),
|
||||
|
||||
path('version-check/', views.VersionCheck.as_view(), name='version_check'),
|
||||
|
||||
]
|
||||
|
||||
@@ -4,6 +4,7 @@ from module_project.utils import ApiResponse
|
||||
from module_iam.models import IAmPrincipal, IAmPrincipalOtp
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
from django.core.exceptions import ValidationError
|
||||
import requests
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -23,12 +24,21 @@ def generate_token_and_user_data(principal):
|
||||
data = {
|
||||
"access": str(refresh.access_token),
|
||||
"refresh": str(refresh),
|
||||
"first_name": principal.first_name,
|
||||
"phone_no": str(principal.phone_no),
|
||||
"complete": principal.register_complete,
|
||||
}
|
||||
return data
|
||||
|
||||
class GoogleAuthService():
|
||||
@staticmethod
|
||||
def get_user_info(access_token):
|
||||
headers = {'Authorization': f'Bearer {access_token}'}
|
||||
response = requests.get(
|
||||
'https://www.googleapis.com/oauth2/v3/userinfo',
|
||||
headers=headers,
|
||||
)
|
||||
user_info = response.json()
|
||||
return user_info
|
||||
|
||||
class AuthService:
|
||||
"""
|
||||
Provides authentication services for IAmPrincipal users.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import datetime
|
||||
from datetime import datetime
|
||||
from rest_framework import status
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
@@ -6,14 +6,23 @@ from rest_framework_simplejwt.authentication import JWTAuthentication
|
||||
from module_project import constants
|
||||
from module_project.service import SMSService, EmailService
|
||||
from module_project.utils import ApiResponse
|
||||
from .utils import AuthService
|
||||
from module_iam.models import IAmPrincipal, IAmPrincipalOtp
|
||||
from .serializers import RegistrationSerializer, LoginSerializer, OtpVerificationSerializer, PasswordResetSerializer
|
||||
from .utils import AuthService, GoogleAuthService
|
||||
from django.contrib.auth import authenticate
|
||||
import requests
|
||||
from module_iam.models import AppVersion, IAmPrincipal, IAmPrincipalOtp, IAmPrincipalType, IAmPrincipalSource
|
||||
from .serializers import (
|
||||
RegistrationSerializer,
|
||||
LoginSerializer,
|
||||
OtpVerificationSerializer,
|
||||
PasswordResetSerializer,
|
||||
)
|
||||
from django.conf import settings
|
||||
from rest_framework.response import Response
|
||||
|
||||
from .utils import (
|
||||
generate_token_and_user_data, get_principal_by_email, authticate_with_otp_and_passsword
|
||||
generate_token_and_user_data,
|
||||
get_principal_by_email,
|
||||
authticate_with_otp_and_passsword,
|
||||
)
|
||||
|
||||
|
||||
@@ -36,14 +45,19 @@ class RegistrationView(APIView):
|
||||
|
||||
try:
|
||||
instance = serializer.save()
|
||||
principal = instance
|
||||
token_data = generate_token_and_user_data(principal)
|
||||
instance.last_login = datetime.now()
|
||||
instance.principal_type = IAmPrincipalType.get_principal_user()
|
||||
instance.principal_source = IAmPrincipalSource.get_principal_app()
|
||||
instance.save()
|
||||
token_data = generate_token_and_user_data(instance)
|
||||
except Exception as e:
|
||||
return ApiResponse.error(
|
||||
status=status.HTTP_403_FORBIDDEN, message=str(e), errors=str(e)
|
||||
)
|
||||
|
||||
return ApiResponse.success(message=constants.REGISTRATION_SUCCESS, data=token_data)
|
||||
return ApiResponse.success(
|
||||
message=constants.REGISTRATION_SUCCESS, data=token_data
|
||||
)
|
||||
|
||||
|
||||
class LoginView(APIView):
|
||||
@@ -81,32 +95,9 @@ class LoginView(APIView):
|
||||
print("Errror reponse")
|
||||
return validation_result # Return the error response if validation fails
|
||||
|
||||
|
||||
# auth_service = AuthService(principal_model=IAmPrincipal)
|
||||
|
||||
# try:
|
||||
# principal = self.model.objects.get(email=email)
|
||||
# except Exception as e:
|
||||
# error_response = {
|
||||
# "status": status.HTTP_403_FORBIDDEN,
|
||||
# "message": constants.INVALID_EMAIL_PASSWORD,
|
||||
# "errors": constants.INVALID_EMAIL_PASSWORD,
|
||||
# }
|
||||
# return ApiResponse.error(**error_response)
|
||||
|
||||
# try:
|
||||
# auth_service.authenticate(principal_id=principal.id, password=password)
|
||||
# except Exception as e:
|
||||
# error_response = {
|
||||
# "status": status.HTTP_403_FORBIDDEN,
|
||||
# "message": e,
|
||||
# "errors": e,
|
||||
# }
|
||||
# return ApiResponse.error(**error_response)
|
||||
|
||||
try:
|
||||
principal.player_id = player_id
|
||||
principal.last_login = datetime.datetime.now()
|
||||
principal.last_login = datetime.now()
|
||||
principal.save()
|
||||
except Exception as e:
|
||||
error_response = {
|
||||
@@ -126,7 +117,9 @@ class OtpRequestView(APIView):
|
||||
|
||||
def post(self, request):
|
||||
if "email" not in request.data:
|
||||
return ApiResponse.error(message=constants.EMAIL_REQUIRED, errors=constants.EMAIL_REQUIRED)
|
||||
return ApiResponse.error(
|
||||
message=constants.EMAIL_REQUIRED, errors=constants.EMAIL_REQUIRED
|
||||
)
|
||||
print(f"email auth username: {settings.EMAIL_HOST_USER}")
|
||||
email = request.data.get("email")
|
||||
|
||||
@@ -139,7 +132,9 @@ class OtpRequestView(APIView):
|
||||
# auth_service = AuthService(IAmPrincipal)
|
||||
# principal = auth_service.get_principal_by_email(request.data.get("email"))
|
||||
|
||||
otp_code = SMSService().create_otp(principal=principal, otp_purpose="Forget password")
|
||||
otp_code = SMSService().create_otp(
|
||||
principal=principal, otp_purpose="Forget password"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=str(e), errors=str(e))
|
||||
@@ -147,18 +142,23 @@ class OtpRequestView(APIView):
|
||||
email_service = EmailService(
|
||||
subject="Forget Password",
|
||||
to=principal.email,
|
||||
from_email=settings.EMAIL_HOST_USER
|
||||
from_email=settings.EMAIL_HOST_USER,
|
||||
)
|
||||
|
||||
# Send the email
|
||||
try:
|
||||
email_service.load_template("module_auth/email_template.html", context={"code": otp_code} )
|
||||
email_service.load_template(
|
||||
"module_auth/email_template.html", context={"code": otp_code, "name": principal.first_name}
|
||||
)
|
||||
email_service.send()
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=f"Error sending email: {str(e)}", errors=str(e))
|
||||
return ApiResponse.error(
|
||||
message=f"Error sending email: {str(e)}", errors=str(e)
|
||||
)
|
||||
|
||||
return ApiResponse.success(message=constants.SUCCESS)
|
||||
|
||||
|
||||
class OTPVerificationView(APIView):
|
||||
authentication_classes = []
|
||||
permission_classes = []
|
||||
@@ -173,7 +173,7 @@ class OTPVerificationView(APIView):
|
||||
"errors": serializer.errors,
|
||||
}
|
||||
return ApiResponse.error(**error_response)
|
||||
|
||||
|
||||
email = serializer.validated_data.get("email")
|
||||
otp = serializer.validated_data.get("otp")
|
||||
|
||||
@@ -181,18 +181,16 @@ class OTPVerificationView(APIView):
|
||||
|
||||
if isinstance(principal, Response):
|
||||
return principal
|
||||
|
||||
validation_result = authticate_with_otp_and_passsword(
|
||||
principal, otp=otp
|
||||
)
|
||||
|
||||
validation_result = authticate_with_otp_and_passsword(principal, otp=otp)
|
||||
print("pasword instance ", validation_result)
|
||||
|
||||
if isinstance(validation_result, Response):
|
||||
print("Errror reponse")
|
||||
return validation_result # Return the error response if validation fails
|
||||
|
||||
token_data = generate_token_and_user_data(principal)
|
||||
return ApiResponse.success(message=constants.SUCCESS, data=token_data)
|
||||
return ApiResponse.success(message=constants.SUCCESS)
|
||||
|
||||
|
||||
class ForgetPasswordView(APIView):
|
||||
authentication_classes = [JWTAuthentication]
|
||||
@@ -200,6 +198,18 @@ class ForgetPasswordView(APIView):
|
||||
serializer_class = PasswordResetSerializer
|
||||
|
||||
def post(self, request):
|
||||
email = request.data.get("email")
|
||||
|
||||
principal = get_principal_by_email(email=email)
|
||||
|
||||
otp_instance = IAmPrincipalOtp.objects.filter(principal=principal).last()
|
||||
|
||||
if not otp_instance:
|
||||
return ApiResponse.error(message=constants.SESSION_EXPIRED)
|
||||
|
||||
if otp_instance.is_expired():
|
||||
return ApiResponse.error(message=constants.SESSION_EXPIRED)
|
||||
|
||||
serializer = self.serializer_class(request.user, data=request.data)
|
||||
if not serializer.is_valid():
|
||||
error_response = {
|
||||
@@ -214,4 +224,142 @@ class ForgetPasswordView(APIView):
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=str(e), errors=str(e))
|
||||
|
||||
return ApiResponse.success(message=constants.SUCCESS)
|
||||
return ApiResponse.success(message=constants.SUCCESS)
|
||||
|
||||
|
||||
class AccountDeactivateView(APIView):
|
||||
authentication_classes = [JWTAuthentication]
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def delete(self, request):
|
||||
try:
|
||||
user = IAmPrincipal.objects.get(id=request.user.id)
|
||||
user.is_active = False
|
||||
user.deleted = True
|
||||
user.save()
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=constants.INTERNAL_SERVER_ERROR, errors=str(e))
|
||||
|
||||
return ApiResponse.success(message=constants.ACCOUNT_DEACTIVATED)
|
||||
|
||||
|
||||
class GoogleSignin(APIView):
|
||||
authentication_classes = []
|
||||
permission_classes = []
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
access_token = request.data["access_token"]
|
||||
user_info = GoogleAuthService.get_user_info(access_token)
|
||||
|
||||
print(f"User Info : {user_info}")
|
||||
|
||||
# Authenticate user with the email provided by Google
|
||||
user = IAmPrincipal.objects.filter(email=user_info['email']).first(
|
||||
) or authenticate(email=user_info['email'], password=None)
|
||||
|
||||
if user is None:
|
||||
# Create a new user if not found
|
||||
user = IAmPrincipal.objects.create_user(
|
||||
username=user_info['email'],
|
||||
email=user_info['email'],
|
||||
first_name=f"{user_info['given_name']} {user_info['family_name']}",
|
||||
last_login=datetime.now(),
|
||||
principal_type=IAmPrincipalType.get_principal_user(),
|
||||
principal_source=IAmPrincipalSource.get_principal_google()
|
||||
)
|
||||
user.save()
|
||||
|
||||
token_data = generate_token_and_user_data(user)
|
||||
|
||||
# return Response({"token": token.key}, status=status.HTTP_200_OK)
|
||||
return ApiResponse.success(
|
||||
message=constants.SUCCESS, data=token_data
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=constants.FAILURE, errors=str(e))
|
||||
|
||||
|
||||
import jwt
|
||||
class AppleSignin(APIView):
|
||||
authentication_classes = []
|
||||
permission_classes = []
|
||||
|
||||
def post(self, request):
|
||||
try:
|
||||
authorization_code = request.data['authorization_code']
|
||||
headers = {
|
||||
'Authorization': f"Bearer {settings.SOCIAL_AUTH_APPLE_CLIENT_SECRET}"
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
'https://appleid.apple.com/auth/token',
|
||||
data={
|
||||
'client_id': settings.SOCIAL_AUTH_APPLE_CLIENT_ID,
|
||||
'code': authorization_code,
|
||||
'grant_type': 'authorization_code',
|
||||
'redirect_uri': False,
|
||||
},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
response_data = response.json()
|
||||
id_token = response_data.get('id_token')
|
||||
|
||||
decoded = jwt.decode(
|
||||
id_token,
|
||||
'',
|
||||
algorithms=['ES256'],
|
||||
options={
|
||||
'verify_aud': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
},
|
||||
)
|
||||
email = decoded.get('email')
|
||||
full_name = f"{decoded.get('given_name')} {decoded.get('family_name')}"
|
||||
if IAmPrincipal.objects.filter(email=email).exists():
|
||||
user = IAmPrincipal.objects.get(email=email)
|
||||
else:
|
||||
user = IAmPrincipal.objects.create_user(
|
||||
username=email,
|
||||
email=email,
|
||||
first_name=full_name,
|
||||
)
|
||||
user.save()
|
||||
|
||||
token_data = generate_token_and_user_data(user)
|
||||
|
||||
return ApiResponse.success(
|
||||
message=constants.SUCCESS, data=token_data
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return ApiResponse.error(message=constants.FAILURE, errors=str(e))
|
||||
|
||||
|
||||
class VersionCheck(APIView):
|
||||
authentication_classes = []
|
||||
permission_classes = []
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
app_version = request.GET.get('appVersion')
|
||||
|
||||
# Query the database to retrieve the upgrade flags based on the app version
|
||||
try:
|
||||
version = AppVersion.objects.get(version=app_version)
|
||||
except AppVersion.DoesNotExist:
|
||||
version = None
|
||||
|
||||
if version:
|
||||
upgrade_flags = {
|
||||
'forceUpgrade': version.force_upgrade,
|
||||
'recommendUpgrade': version.recommend_upgrade,
|
||||
}
|
||||
else:
|
||||
upgrade_flags = {
|
||||
'forceUpgrade': False,
|
||||
'recommendUpgrade': False,
|
||||
}
|
||||
return ApiResponse.success(message=constants.SUCCESS, data=upgrade_flags)
|
||||
@@ -1,6 +1,7 @@
|
||||
from django import forms
|
||||
from django.core import validators
|
||||
from module_project import constants
|
||||
from module_iam.models import IAmPrincipal
|
||||
|
||||
class LoginForm(forms.Form):
|
||||
email = forms.EmailField(
|
||||
@@ -12,4 +13,57 @@ class LoginForm(forms.Form):
|
||||
label="Password",
|
||||
strip=False,
|
||||
widget=forms.PasswordInput()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
|
||||
class UserForm(forms.ModelForm):
|
||||
password = forms.CharField(
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "off"}),
|
||||
validators=[
|
||||
validators.MinLengthValidator(
|
||||
limit_value=6, message="Password must be at least 6 characters long. "
|
||||
)
|
||||
],
|
||||
)
|
||||
confirm_password = forms.CharField(
|
||||
widget=forms.PasswordInput(attrs={"autocomplete": "off"})
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = IAmPrincipal
|
||||
fields = [
|
||||
"first_name",
|
||||
"email",
|
||||
"password",
|
||||
"confirm_password",
|
||||
]
|
||||
labels = {
|
||||
"first_name": "Name",
|
||||
}
|
||||
|
||||
def clean_email(self):
|
||||
email = self.cleaned_data.get('email')
|
||||
if IAmPrincipal.objects.filter(email=email).exists():
|
||||
raise forms.ValidationError("This email address is already in use.")
|
||||
return email
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super().clean()
|
||||
password = cleaned_data.get("password")
|
||||
confirm_password = cleaned_data.get("confirm_password")
|
||||
|
||||
if password and confirm_password and password != confirm_password:
|
||||
self.add_error("confirm_password", "Passwords do not match.")
|
||||
return cleaned_data
|
||||
|
||||
def save(self, commit=True):
|
||||
instance = super().save(commit=False)
|
||||
# Check if it's a new object (create action) or an existing one (update action)
|
||||
if not instance.pk: # pk is None for new objects
|
||||
instance.username = self.cleaned_data["email"]
|
||||
instance.set_password(self.cleaned_data["password"])
|
||||
if commit:
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
app_name = "module_auth"
|
||||
|
||||
@@ -11,7 +12,12 @@ urlpatterns = [
|
||||
path('password-reset-confirm/<uidb64>/<token>/', views.CustomPasswordResetConfirmView.as_view(), name='password_reset_confirm'),
|
||||
path('password-reset-complete/', views.CustomPasswordResetCompleteView.as_view(), name='password_reset_complete'),
|
||||
path('users/', views.UserDashView.as_view(), name='users'),
|
||||
path('users/add/', views.UserCreateOrUpdateView.as_view(), name='user_add'),
|
||||
path('users/edit/<int:pk>/', views.UserCreateOrUpdateView.as_view(), name='user_edit'),
|
||||
path('users/list/', views.UserListJson.as_view(), name='users_list'),
|
||||
path('users/action/', views.UserActionView.as_view(), name='users_action'),
|
||||
path('user/view/<int:id>/', views.UserRecordView.as_view(), name='user_view'),
|
||||
path('user/archive/list/', views.UserArchiveList.as_view(), name='user_archive'),
|
||||
path('user/count/', views.UsersCountView.as_view(), name="user_count")
|
||||
|
||||
]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import logging
|
||||
|
||||
from datetime import datetime
|
||||
from django.db.models import Q, Prefetch
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import authenticate, login, logout
|
||||
@@ -16,10 +17,13 @@ from django.contrib.auth.views import (
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.urls import reverse_lazy
|
||||
from django.views import generic
|
||||
from .forms import LoginForm
|
||||
from module_iam.models import IAmPrincipal
|
||||
from .forms import LoginForm, UserForm
|
||||
from module_iam.models import IAmPrincipal, IAmPrincipalType
|
||||
from module_iam import iam_constant
|
||||
from module_activity.models import PrincipalHealthData, Intolerance, Symptoms, PastTreatment, ChronicCondition
|
||||
from django_datatables_view.base_datatable_view import BaseDatatableView
|
||||
from module_project.mixins import ActionMixin
|
||||
from module_project.utils import JsonResponseUtil
|
||||
|
||||
from module_project import constants
|
||||
|
||||
@@ -74,7 +78,7 @@ class CustomPasswordResetDoneView(PasswordResetDoneView):
|
||||
|
||||
|
||||
class UserDashView(LoginRequiredMixin, generic.TemplateView):
|
||||
page_name = None
|
||||
page_name = iam_constant.RESOURCE_MANAGE_USER
|
||||
resource = None
|
||||
action = None
|
||||
template_name = "module_auth/users_list.html"
|
||||
@@ -86,20 +90,76 @@ class UserDashView(LoginRequiredMixin, generic.TemplateView):
|
||||
context["page_name"] = self.page_name
|
||||
return context
|
||||
|
||||
class UserCreateOrUpdateView(LoginRequiredMixin, generic.View):
|
||||
page_name = iam_constant.RESOURCE_MANAGE_USER
|
||||
model = IAmPrincipal
|
||||
form_class = UserForm
|
||||
template_name = "module_auth/user_add.html"
|
||||
success_url = reverse_lazy("module_auth:users")
|
||||
success_message = "Saved Successfully"
|
||||
error_message = "An error occurred while saving the data."
|
||||
|
||||
def get_object(self):
|
||||
pk = self.kwargs.get("pk")
|
||||
return get_object_or_404(self.model, pk=pk) if pk else None
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = {
|
||||
"page_name": self.page_name,
|
||||
"operation": "Edit" if self.object else "Add",
|
||||
}
|
||||
context.update(kwargs) # Include any additional context data passed to the view
|
||||
return context
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
form = self.form_class(instance=self.object)
|
||||
context = self.get_context_data(form=form)
|
||||
return render(request, self.template_name, context=context)
|
||||
|
||||
# @transaction.atomic
|
||||
def post(self, request, *args, **kwargs):
|
||||
print(request.POST)
|
||||
self.object = self.get_object()
|
||||
form = self.form_class(request.POST, instance=self.object)
|
||||
try:
|
||||
if form.is_valid():
|
||||
principal = form.save(commit=False)
|
||||
|
||||
# Check if it's a new object (create action) or an existing one (update action)
|
||||
if not principal.pk: # pk is None for new objects
|
||||
principal.created_by = request.user
|
||||
principal.principal_type = IAmPrincipalType.objects.filter(name=iam_constant.PRINCIPAL_TYPE_USER).first()
|
||||
principal.modified_by = request.user
|
||||
principal.modified_on = datetime.now()
|
||||
|
||||
# Save the object
|
||||
principal.save()
|
||||
|
||||
messages.success(request, "Form submitted successfully")
|
||||
return redirect(self.success_url)
|
||||
except Exception as e:
|
||||
self.error_message = constants.ERROR_OCCURR.format(str(e))
|
||||
print(self.error_message)
|
||||
messages.error(request, self.error_message)
|
||||
|
||||
context = self.get_context_data(form=form)
|
||||
return render(request, template_name=self.template_name, context=context)
|
||||
|
||||
|
||||
class UserListJson(BaseDatatableView):
|
||||
model = IAmPrincipal
|
||||
columns = ["id", "first_name", "email", "phone_no", "date_of_birth", "is_active"]
|
||||
order_columns = ["id", "first_name", "email", "phone_no", "date_of_birth", "is_active"]
|
||||
|
||||
def get_initial_queryset(self):
|
||||
deleted_flag = self.request.GET.get('deleted_flag', False)
|
||||
return self.model.objects.filter(principal_type=IAmPrincipalType.get_principal_user(), deleted=deleted_flag)
|
||||
|
||||
def filter_queryset(self, qs):
|
||||
print(f"request is {self.request.GET}")
|
||||
search_value = self.request.GET.get("search[value]", None)
|
||||
if search_value:
|
||||
# print(f"isdiget {search_value.isdigit()}")
|
||||
# if search_value.isdigit():
|
||||
# qs = qs.filter(Q(id=search_value))
|
||||
|
||||
qs = qs.filter(
|
||||
Q(id__icontains=search_value)
|
||||
| Q(first_name__icontains=search_value)
|
||||
@@ -115,9 +175,34 @@ class UserListJson(BaseDatatableView):
|
||||
|
||||
return qs
|
||||
|
||||
class UserActionView(ActionMixin):
|
||||
model = IAmPrincipal
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
|
||||
action = request.POST.get('action') # 'archive', 'active', or 'unarchive'
|
||||
ids = request.POST.getlist('ids[]') # List of IDs to perform action on
|
||||
active = request.POST.get('active')
|
||||
print(f"arhive action {action} and id is {ids} and active data is {active}")
|
||||
if action == 'archive':
|
||||
# Update 'deleted' field to True for the selected users
|
||||
self.model.objects.filter(id__in=ids).update(deleted=True, is_active=False)
|
||||
message = 'Record archived successfully.'
|
||||
elif action == 'active':
|
||||
# Update 'active' field to True for the selected users
|
||||
self.model.objects.filter(id__in=ids).update(is_active=active.capitalize())
|
||||
message = 'Record updated successfully.'
|
||||
elif action == 'unarchive':
|
||||
# Update 'deleted' field to False for the selected users
|
||||
self.model.objects.filter(id__in=ids).update(deleted=False)
|
||||
message = 'Record unarchived successfully.'
|
||||
else:
|
||||
return JsonResponseUtil.error(message="Invalid Action")
|
||||
|
||||
return JsonResponseUtil.success(message=message)
|
||||
|
||||
class UserRecordView(LoginRequiredMixin, generic.View):
|
||||
page_name = None
|
||||
page_name = iam_constant.RESOURCE_MANAGE_USER
|
||||
resource = None
|
||||
action = None
|
||||
model = IAmPrincipal
|
||||
@@ -160,39 +245,24 @@ class UserRecordView(LoginRequiredMixin, generic.View):
|
||||
chronic_prefetch
|
||||
).get(id=id)
|
||||
|
||||
print(f"prefetch datatas")
|
||||
for data in obj.chronic_data:
|
||||
print(f"data is {data.name, data.duration}")
|
||||
|
||||
# Render the template with the principal instance and related data
|
||||
return render(request, self.template_name, {'obj': obj})
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return render(request, self.template_name, {'obj': obj, 'page_name': self.page_name})
|
||||
|
||||
|
||||
class UserArchiveList(LoginRequiredMixin, generic.TemplateView):
|
||||
page_name = iam_constant.RESOURCE_MANAGE_USER
|
||||
resource = None
|
||||
action = None
|
||||
template_name = "module_auth/users_archive_list.html"
|
||||
model = IAmPrincipal
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["page_name"] = self.page_name
|
||||
return context
|
||||
|
||||
class CustomPasswordResetConfirmView(PasswordResetConfirmView):
|
||||
template_name = "module_auth/password_reset_confirm.html"
|
||||
@@ -201,3 +271,23 @@ class CustomPasswordResetConfirmView(PasswordResetConfirmView):
|
||||
|
||||
class CustomPasswordResetCompleteView(PasswordResetCompleteView):
|
||||
template_name = "module_auth/password_reset_complete.html"
|
||||
|
||||
|
||||
class UsersCountView(generic.View):
|
||||
|
||||
def get(self, request):
|
||||
current_year = int(self.request.GET.get("year"))
|
||||
user_counts = []
|
||||
|
||||
# Iterate over each month from January to December
|
||||
for month in range(1, 13):
|
||||
# Calculate the start and end dates for the current month
|
||||
start_date = datetime(current_year, month, 1)
|
||||
end_date = datetime(current_year, month + 1, 1) if month < 12 else datetime(current_year + 1, 1, 1)
|
||||
# Query the User model to count users created within the current month
|
||||
user_count = IAmPrincipal.objects.filter(date_joined__range=(start_date, end_date)).count()
|
||||
|
||||
# Append the count to the list
|
||||
user_counts.append(user_count)
|
||||
|
||||
return JsonResponseUtil.success(message=constants.SUCCESS, data=user_counts)
|
||||
Reference in New Issue
Block a user