python-Django, how can pass project id to specific user?

23 views Asked by At

Everyone I created a project model that enables the administrator to create separate projects and manage them, where each project has its own processes, as their structure is similar and differs in data. Therefore, I used Tenant and made it linked to one Domain, so that each project was separate with its data. Now I faced a problem with how to distribute these projects, as each project has One user and each user can have his own Domain. When logging in as a user, it checks to see if the user has a Domain. Here now the problem has appeared as he does not recognize the link between the project and the Domain.

  • Explain the process(admin create project and user after that associated between one user with one project then create tenant with domain and associated it with one user now i need when user try to login check if he fulfills the conditions redirect him to his project that can he access to his project by project/id

  • Foreign Key (project that can he access to his project by project/id) Domain have column tenant reference to Tenant Tenant have column user reference to User User have column project reference to Project )

I tried using the following code, as the first part of it is verified by verifying the type of user. If he is an administrator, he will be transferred to the index page, but when he logs in as a user here, he does not fulfill the conditions described in the code.

@login_required
def login_view(request):
    msg = None
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    if user.is_superuser:
                        auth_login(request, user)
                        return redirect('index')
                    elif user.is_staff:
                        # Check if the user is associated with a project
                        if hasattr(user, 'project'):
                            project = user.project

                            # Check if the project has a related tenant
                            if hasattr(tenant, 'user'):
                                tenant = tenant.user

                                # Check if the tenant has a related domain
                                if hasattr(domain, 'tenant'):
                                    domain = domain.tenant

                                    # Use schema_context to activate the tenant's schema and context
                                    with schema_context(domain.domain):
                                        # Construct Project-Based URL
                                        project_url = reverse('project', args=[str(project.id)])
                                        # Redirect the user to the constructed project URL
                                        return redirect(project_url)
                                else:
                                    return redirect('no_domain_page')  # Redirect to a page indicating no domain
                            else:
                                return redirect('no_tenant_page') # Redirect to a page indicating no tenant
                        else:
                            return redirect('no_project_page')  # Redirect to a page indicating no project
                    else:
                        msg = 'Unauthorized access.'
                else:
                    msg = 'This user is not active or does not exist.'
            else:
                msg = 'Invalid username or password.'
        else:
            msg = 'Error in the entered data!'
    else:
        form = LoginForm()

    return render(request, 'login.html', {'form': form, 'msg': msg})

1

There are 1 answers

0
EmadObaid On

I found the solution to the above problem:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login as auth_login
from django_tenants.models import Domain
from django_tenants.utils import schema_context
from django.urls import reverse
from django.core.exceptions import ObjectDoesNotExist  # Import the exception
@login_required
def login_view(request):
    msg = None
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            try:
                # Check if the user exists
                user = User.objects.get(username=username)
                # Authenticate the user
                user = authenticate(username=username, password=password)
                if user is not None and user.is_active:
                    # Check if the user is a superuser
                    if user.is_superuser:
                        auth_login(request, user)
                        return redirect('index')
                    elif user.is_staff:
                         # Assuming each user is associated with exactly one Tenant
                        tenant = user.tenant
                        domains = Domain.objects.filter(tenant=tenant)
                        found_domain = None
                        for d in domains:
                            print(f"  - {d}")
                            found_domain = d
                        if found_domain and hasattr(found_domain, 'tenant'):
                            tenant = found_domain.tenant
                            with schema_context(found_domain.domain):
                                project_url = reverse('project', args=[str(user.project.uuid)])
                                redirect_url = f'http://{found_domain.domain}:8080{project_url}'
                                auth_login(request, user)
                                return redirect(redirect_url)
                        else:
                            msg = 'No link associated with the user was found!'
                else:
                        msg = 'Username or password is incorrect!'
            except User.DoesNotExist:
                msg = 'User not found'
            except ObjectDoesNotExist as e:
                # Handle the exception, e.g., log it or set a default value for tenant
                print(f"ObjectDoesNotExist: {e}")
                msg = 'An error occurred during authentication, no link associated with the user was found!!'
        else:
            msg = 'Error in entered data!'
    else:
        form = LoginForm()

    return render(request, 'login.html', {'form': form, 'msg': msg})