Esempio n. 1
0
def able_to_self_log_in_to_area(user):
    # 'Self log in' must be enabled
    if not get_customization('self_log_in') == 'enabled':
        return False
    # Check if the user is already in an area. If so, the /change_project/ URL can be used to change their project.
    if user.in_area():
        return False
    # Check policy for entering an area
    try:
        check_policy_to_enter_any_area(user=user)
    except UserAccessError:
        return False

    accessible_areas = get_accessible_areas_for_user(user)

    # Check if the user normally has access to an area at the current time
    try:
        for accessible_area in accessible_areas:
            check_policy_to_enter_this_area(area=accessible_area.area,
                                            user=user)
            # Users may not access an area if it's not accessible at this time or if a required resource is unavailable,
            # so return true if there exists at least one area they are able to log in to.
            return True
    except (NoAccessiblePhysicalAccessUserError,
            UnavailableResourcesUserError):
        pass

    # No areas are accessible...
    return False
Esempio n. 2
0
def self_log_in(request, load_areas=True):
	user: User = request.user
	if not able_to_self_log_in_to_area(user):
		return redirect(reverse('landing'))

	dictionary = {
		'projects': user.active_projects(),
	}
	facility_name = get_customization('facility_name')
	try:
		check_policy_to_enter_any_area(user)
	except InactiveUserError:
		dictionary['error_message'] = f'Your account has been deactivated. Please visit the {facility_name} staff to resolve the problem.'
		return render(request, 'area_access/self_login.html', dictionary)
	except NoActiveProjectsForUserError:
		dictionary['error_message'] = f"You are not a member of any active projects. You won't be able to use any interlocked {facility_name} tools. Please visit the {facility_name} user office for more information."
		return render(request, 'area_access/self_login.html', dictionary)
	except PhysicalAccessExpiredUserError:
		dictionary['error_message'] = f"Your physical access to the {facility_name} has expired. Have you completed your safety training within the last year? Please visit the User Office to renew your access."
		return render(request, 'area_access/self_login.html', dictionary)
	except NoPhysicalAccessUserError:
		dictionary['error_message'] = f"You have not been granted physical access to any {facility_name} area. Please visit the User Office if you believe this is an error."
		return render(request, 'area_access/self_login.html', dictionary)

	if load_areas:
		dictionary['user_accessible_areas'], dictionary['areas'] = load_areas_for_use_in_template(user)
	else:
		dictionary['user_accessible_areas'] = []
		dictionary['areas'] = []

	if request.method == 'GET':
		return render(request, 'area_access/self_login.html', dictionary)
	if request.method == 'POST':
		try:
			a = Area.objects.get(id=request.POST['area'])
			p = Project.objects.get(id=request.POST['project'])
			check_policy_to_enter_this_area(a, request.user)
			if p in dictionary['projects']:
				AreaAccessRecord.objects.create(area=a, customer=request.user, project=p)
		except NoAccessiblePhysicalAccessUserError as error:
			dictionary['area_error_message'] = f"You do not have access to the {error.area.name} at this time. Please visit the User Office if you believe this is an error."
			return render(request, 'area_access/self_login.html', dictionary)
		except UnavailableResourcesUserError as error:
			dictionary['area_error_message'] = f'The {error.area.name} is inaccessible because a required resource is unavailable ({error.resources[0]}).'
			return render(request, 'area_access/self_login.html', dictionary)
		except ScheduledOutageInProgressError as error:
			dictionary['area_error_message'] = f'The {error.area.name} is inaccessible because a scheduled outage is in progress.'
			return render(request, 'area_access/self_login.html', dictionary)
		except MaximumCapacityReachedError as error:
			dictionary['area_error_message'] = f'The {error.area.name} is inaccessible because it has reached its maximum capacity. Wait for somebody to exit and try again.'
			return render(request, 'area_access/self_login.html', dictionary)
		except ReservationRequiredUserError as error:
			dictionary['area_error_message'] = f'You do not have a current reservation for the {error.area.name}. Please make a reservation before trying to access this area.'
			return render(request, 'area_access/self_login.html', dictionary)
		except Exception as error:
			area_access_logger.exception(error)
			dictionary['area_error_message'] = "unexpected error"
			return render(request, 'area_access/self_login.html', dictionary)
		return redirect(reverse('landing'))
Esempio n. 3
0
def check_policy_for_user(customer: User):
	error_message = None
	try:
		check_policy_to_enter_any_area(user=customer)
	except InactiveUserError:
		error_message = '{} is inactive'.format(customer)
	except NoActiveProjectsForUserError:
		error_message = '{} does not have any active projects to bill area access'.format(customer)
	except NoPhysicalAccessUserError:
		error_message = '{} does not have access to any billable areas'.format(customer)
	except PhysicalAccessExpiredUserError:
		error_message = '{} does not have access to any areas because the user\'s physical access expired on {}. You must update the user\'s physical access expiration date before creating a new area access record.'.format(customer, customer.access_expiration.strftime('%B %m, %Y'))
	return error_message
Esempio n. 4
0
def check_user_reply_error(buddy_request: BuddyRequest,
                           user: User) -> Optional[str]:
    error_message = None
    try:
        check_policy_to_enter_any_area(user)
    except InactiveUserError:
        error_message = "You cannot reply to this request because your account has been deactivated"
    except NoActiveProjectsForUserError:
        error_message = "You cannot reply to this request because you don't have any active projects"
    except PhysicalAccessExpiredUserError:
        error_message = "You cannot reply to this request because your facility access has expired"
    except NoPhysicalAccessUserError:
        error_message = "You cannot reply to this request because you do not have access to any areas"
    else:
        if buddy_request.area not in user.accessible_areas():
            error_message = (
                f"You cannot reply to this request because you do not have access to the {buddy_request.area.name}"
            )
    return error_message
Esempio n. 5
0
def login_to_area(request, door_id):
    door = get_object_or_404(Door, id=door_id)

    badge_number = request.POST.get("badge_number", "")
    bypass_interlock = request.POST.get("bypass", 'False') == 'True'
    if badge_number == "":
        return render(request, "area_access/badge_not_found.html")
    try:
        badge_number = int(badge_number)
        user = User.objects.get(badge_number=badge_number)
    except (User.DoesNotExist, ValueError):
        return render(request, "area_access/badge_not_found.html")

    log = PhysicalAccessLog()
    log.user = user
    log.door = door
    log.time = timezone.now()
    log.result = PhysicalAccessType.DENY  # Assume the user does not have access

    facility_name = get_customization("facility_name")

    # Check policy for entering an area
    try:
        check_policy_to_enter_any_area(user=user)
    except InactiveUserError:
        log.details = "This user is not active, preventing them from entering any access controlled areas."
        log.save()
        return render(request, "area_access/inactive.html")

    except NoActiveProjectsForUserError:
        log.details = "The user has no active projects, preventing them from entering an access controlled area."
        log.save()
        return render(request, "area_access/no_active_projects.html")

    except PhysicalAccessExpiredUserError:
        log.details = "This user was blocked from this physical access level because their physical access has expired."
        log.save()
        message = f"Your physical access to the {facility_name} has expired. Have you completed your safety training within the last year? Please visit the User Office to renew your access."
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    except NoPhysicalAccessUserError:
        log.details = "This user does not belong to ANY physical access levels."
        log.save()
        message = f"You have not been granted physical access to any {facility_name} area. Please visit the User Office if you believe this is an error."
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    max_capacity_reached = False
    reservation_requirement_failed = False
    scheduled_outage_in_progress = False
    # Check policy to enter this area
    try:
        check_policy_to_enter_this_area(area=door.area, user=user)
    except NoAccessiblePhysicalAccessUserError as error:
        if error.access_exception:
            log.details = (
                f"The user was blocked from entering this area because of an exception: {error.access_exception.name}."
            )
            message = f"You do not have access to this area of the {facility_name} due to the following exception: {error.access_exception}. The exception ends on {localize(error.access_exception.end_time.astimezone(timezone.get_current_timezone()))}"
        else:
            log.details = (
                "This user is not assigned to a physical access level that allows access to this door at this time."
            )
            message = f"You do not have access to this area of the {facility_name} at this time. Please visit the User Office if you believe this is an error."
        log.save()
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    except UnavailableResourcesUserError as error:
        log.details = f"The user was blocked from entering this area because a required resource was unavailable [{', '.join(str(resource) for resource in error.resources)}]."
        log.save()
        return render(request, "area_access/resource_unavailable.html",
                      {"unavailable_resources": error.resources})

    except MaximumCapacityReachedError as error:
        # deal with this error after checking if the user is already logged in
        max_capacity_reached = error

    except ScheduledOutageInProgressError as error:
        # deal with this error after checking if the user is already logged in
        scheduled_outage_in_progress = error

    except ReservationRequiredUserError:
        # deal with this error after checking if the user is already logged in
        reservation_requirement_failed = True

    current_area_access_record = user.area_access_record()
    if current_area_access_record and current_area_access_record.area == door.area:
        # No log entry necessary here because all validation checks passed.
        # The log entry is captured when the subsequent choice is made by the user.
        return render(
            request,
            "area_access/already_logged_in.html",
            {
                "area": door.area,
                "project": current_area_access_record.project,
                "badge_number": user.badge_number,
                "reservation_requirement_failed":
                reservation_requirement_failed,
                "max_capacity_reached": max_capacity_reached,
                "scheduled_outage_in_progress": scheduled_outage_in_progress,
            },
        )

    if scheduled_outage_in_progress:
        log.details = f"The user was blocked from entering this area because the {scheduled_outage_in_progress.area.name} has a scheduled outage in progress."
        log.save()
        message = (
            f"The {scheduled_outage_in_progress.area.name} is inaccessible because a scheduled outage is in progress."
        )
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    if max_capacity_reached:
        log.details = f"The user was blocked from entering this area because the {max_capacity_reached.area.name} has reached its maximum capacity of {max_capacity_reached.area.maximum_capacity} people at a time."
        log.save()
        message = f"The {max_capacity_reached.area.name} has reached its maximum capacity. Please wait for somebody to leave and try again."
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    if reservation_requirement_failed:
        log.details = f"The user was blocked from entering this area because the user does not have a current reservation for the {door.area}."
        log.save()
        message = "You do not have a current reservation for this area. Please make a reservation before trying to access this area."
        return render(request, "area_access/physical_access_denied.html",
                      {"message": message})

    if user.active_project_count() >= 1:
        if user.active_project_count() == 1:
            project = user.active_projects()[0]
        else:
            project_id = request.POST.get("project_id")
            if not project_id:
                # No log entry necessary here because all validation checks passed, and the user must indicate which project
                # the wish to login under. The log entry is captured when the subsequent choice is made by the user.
                return render(request, "area_access/choose_project.html", {
                    "area": door.area,
                    "user": user
                })
            else:
                project = get_object_or_404(Project, id=project_id)
                if project not in user.active_projects():
                    log.details = "The user attempted to bill the project named {}, but they are not a member of that project.".format(
                        project.name)
                    log.save()
                    message = "You are not authorized to bill this project."
                    return render(request,
                                  "area_access/physical_access_denied.html",
                                  {"message": message})

        log.result = PhysicalAccessType.ALLOW
        log.save()

        # Automatically log the user out of any previous area before logging them in to the new area.
        previous_area = None
        if user.in_area():
            previous_area = user.area_access_record().area
            log_out_user(user)

        # All policy checks passed so open the door for the user.
        if not door.interlock.unlock():
            if bypass_interlock and interlock_bypass_allowed(user):
                pass
            else:
                return interlock_error("Login", user)

        delay_lock_door(door.id)

        log_in_user_to_area(door.area, user, project)
        occupants = AreaAccessRecord.objects.filter(area__name=door.area,
                                                    end=None,
                                                    staff_charge=None).count()
        if door.area.buddy_required():
            if occupants == 1:
                return render(
                    request,
                    'area_access/buddy_login_warning.html',
                    {
                        'area': door.area,
                        'name': user.first_name,
                        'project': project,
                        'previous_area': previous_area
                    },
                )
            elif occupants <= 3:
                return render(
                    request,
                    'area_access/buddy_login_reminder.html',
                    {
                        'area': door.area,
                        'name': user.first_name,
                        'project': project,
                        'previous_area': previous_area,
                        'occupants': occupants
                    },
                )
        return render(
            request,
            'area_access/login_success.html',
            {
                'area': door.area,
                'name': user.first_name,
                'project': project,
                'previous_area': previous_area
            },
        )
Esempio n. 6
0
def login_to_area(request, door_id):
	door = get_object_or_404(Door, id=door_id)

	badge_number = request.POST.get('badge_number', '')
	if badge_number == '':
		return render(request, 'area_access/badge_not_found.html')
	try:
		badge_number = int(badge_number)
		user = User.objects.get(badge_number=badge_number)
	except (User.DoesNotExist, ValueError):
		return render(request, 'area_access/badge_not_found.html')

	log = PhysicalAccessLog()
	log.user = user
	log.door = door
	log.time = timezone.now()
	log.result = PhysicalAccessType.DENY  # Assume the user does not have access

	# Check policy for entering an area
	try:
		check_policy_to_enter_any_area(user=user)
	except InactiveUserError:
		log.details = "This user is not active, preventing them from entering any access controlled areas."
		log.save()
		return render(request, 'area_access/inactive.html')

	except NoActiveProjectsForUserError:
		log.details = "The user has no active projects, preventing them from entering an access controlled area."
		log.save()
		return render(request, 'area_access/no_active_projects.html')

	except PhysicalAccessExpiredUserError:
		log.details = "This user was blocked from this physical access level because their physical access has expired."
		log.save()
		message = "Your physical access to the NanoFab has expired. Have you completed your safety training within the last year? Please visit the User Office to renew your access."
		return render(request, 'area_access/physical_access_denied.html', {'message': message})

	except NoPhysicalAccessUserError:
		log.details = "This user does not belong to ANY physical access levels."
		log.save()
		message = "You have not been granted physical access to any NanoFab area. Please visit the User Office if you believe this is an error."
		return render(request, 'area_access/physical_access_denied.html', {'message': message})

	max_capacity_reached = False
	# Check policy to enter this area
	try:
		check_policy_to_enter_this_area(area=door.area, user=user)
	except NoAccessiblePhysicalAccessUserError:
		log.details = "This user is not assigned to a physical access level that allows access to this door at this time."
		log.save()
		message = "You do not have access to this area of the NanoFab at this time. Please visit the User Office if you believe this is an error."
		return render(request, 'area_access/physical_access_denied.html', {'message': message})

	except UnavailableResourcesUserError:
		unavailable_resources = door.area.required_resources.filter(available=False)
		if unavailable_resources and not user.is_staff:
			log.details = "The user was blocked from entering this area because a required resource was unavailable."
			log.save()
			return render(request, 'area_access/resource_unavailable.html', {'unavailable_resources': unavailable_resources})

	except MaximumCapacityReachedError:
		# deal with this error after checking if the user is already logged in
		max_capacity_reached = True

	current_area_access_record = user.area_access_record()
	if current_area_access_record and current_area_access_record.area == door.area:
		# No log entry necessary here because all validation checks passed.
		# The log entry is captured when the subsequent choice is made by the user.
		return render(request, 'area_access/already_logged_in.html', {'area': door.area, 'project': current_area_access_record.project, 'badge_number': user.badge_number})

	if max_capacity_reached:
		log.details = f"This area has reached its maximum capacity of {door.area} people at a time."
		log.save()
		message = "This area has reached its maximum capacity. Please wait for somebody to leave and try again."
		return render(request, 'area_access/physical_access_denied.html', {'message': message})

	previous_area = None
	if user.active_project_count() >= 1:
		if user.active_project_count() == 1:
			project = user.active_projects()[0]
		else:
			project_id = request.POST.get('project_id')
			if not project_id:
				# No log entry necessary here because all validation checks passed, and the user must indicate which project
				# the wish to login under. The log entry is captured when the subsequent choice is made by the user.
				return render(request, 'area_access/choose_project.html', {'area': door.area, 'user': user})
			else:
				project = get_object_or_404(Project, id=project_id)
				if project not in user.active_projects():
					log.details = "The user attempted to bill the project named {}, but they are not a member of that project.".format(
						project.name)
					log.save()
					message = "You are not authorized to bill this project."
					return render(request, 'area_access/physical_access_denied.html', {'message': message})

		log.result = PhysicalAccessType.ALLOW
		log.save()

		# Automatically log the user out of any previous area before logging them in to the new area.
		if user.in_area():
			previous_area_access_record = user.area_access_record()
			previous_area_access_record.end = timezone.now()
			previous_area_access_record.save()
			previous_area = previous_area_access_record.area

		record = AreaAccessRecord()
		record.area = door.area
		record.customer = user
		record.project = project
		record.save()
		unlock_door(door.id)
		return render(request, 'area_access/login_success.html', {'area': door.area, 'name': user.first_name, 'project': record.project, 'previous_area': previous_area})