from django.shortcuts import redirect


def in_groups(u, group_names):
    if u.is_authenticated():
        if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
            return True
        return False


class LoginRequiredMixin(object):
    require_group = None

    def dispatch(self, *args, **kwargs):
        # if the view does not specify a group, being logged in is sufficient
        # which is pretty much the same as the lower most access level (Lab guy)
        # or the user is a sa, which is allowed to do everything anyway

        nextLoc = "?next=" + self.request.path
        redir_obj = redirect(to='login_page')
        redir_obj['Location'] += nextLoc

        if (self.request.user.is_authenticated() and self.require_group is None) \
                or self.request.user.is_superuser:
            return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
        elif not self.request.user.is_authenticated():
            return redir_obj

        user_group = self.request.user.user_group

        # user belongs to either no group or an insufficient one, redirect to login
        if not user_group or user_group < self.require_group:
            return redir_obj
        else:
            # allow access
            return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
