Django应用程序在项目级别进行用户身份验证

时间:2016-10-23 09:45:18

标签: python django authentication

在项目级别处理用户身份验证时,如何处理应用内的用户身份验证?

我正在构建一个应用程序,我在创建数据库条目时需要一个经过身份验证的用户对象,但我不想处理应用程序内部的整个注册/登录逻辑,而应该在项目级别进行交换

该应用程序需要用户登录,但在开发时我无法确定将其放在何处。我可以在settings.py中为项目“伪造”经过身份验证的用户吗?

更新

我意识到我必须做的就是在将@login_required添加到我的所有视图后登录/ admin。然后我使用request.user获取我需要的数据并将models.ForeignKey(User)添加到需要它的模型中

2 个答案:

答案 0 :(得分:3)

没有默认方法来伪造用户,但您可以自己轻松实现。

您只需创建一个以硬编码用户身份登录的视图。

def force_login(request):
    # this check is not really required, but probably a good idea
    if not settings.DEBUG:
        raise ImproperlyConfigured("Don't use the force_login view in production")
    user, created = User.objects.get_or_create(
        username='user',
        defaults={...})  # set whatever defaults you need
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    login(request, user)
    return HttpResponse('logged in')

现在您只需将此视图添加到urls.py即可。另一种方法是将其写为中间件。

class ForceAuthenticationMiddleware(object):
    """
    Ensures that the request has a logged in user.

    If there is no user, it logs in a default user and return a
    redirect.
    """

    def process_request(self, request):
        if request.user.is_authenticated:
            return
        user, created = User.objects.get_or_create(
            username='user',
            defaults={...})  # set whatever defaults you need
        user.backend = settings.AUTHENTICATION_BACKENDS[0]
        login(request, user)
        return HttpResponseRedirect(request.get_full_path())

settings.MIDDLEWARE_CLASSES

之后的'django.contrib.auth.middleware.AuthenticationMiddleware',中插入该中间件

更新:我将此答案转换为blog post并在PyPI上发布了中间件。

答案 1 :(得分:0)

根据Django auth系统documentation

如果您正在寻找限制对已登录用户的访问的方法 使用/************* UDP CLIENT CODE *******************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> #include <ctype.h> #include <stdlib.h> #include <fcntl.h> #include <netdb.h> /* getprotobyname */ #include <sys/stat.h> #include <unistd.h> #include <string.h> int main(){ int clientSocket, portNum, nBytes; struct sockaddr_in serverAddr; socklen_t addr_size; char *file_path = "input.tmp"; int filefd; ssize_t read_return; char buffer[BUFSIZ]; char *user_input = NULL; char *server_reply = NULL; /*Create UDP socket*/ clientSocket = socket(PF_INET, SOCK_DGRAM, 0); /*Configure settings in address struct*/ serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7891); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*Initialize size variable to be used later on*/ addr_size = sizeof serverAddr; while (1) { filefd = open(file_path, O_WRONLY | O_APPEND); if (filefd == -1) { perror("open"); exit(EXIT_FAILURE); } else { printf("Type a sentence to send to server/file:\n"); fgets(buffer,BUFSIZ,stdin); write (filefd,buffer,BUFSIZ); printf("You typed: %s",buffer); } read_return = read(filefd, buffer, BUFSIZ); nBytes = strlen(buffer) + 1; if (read_return == 0)//indicated end of file break; if (read_return == -1) { perror("read"); exit(EXIT_FAILURE); } /*Send message to server*/ sendto(clientSocket,buffer,nBytes,0,(struct sockaddr *)&serverAddr,addr_size); /*if (write(clientSocket, buffer, read_return) == -1) { perror("write"); exit(EXIT_FAILURE); }else{printf("input file read successfully into the buffer\n");}*/ } free(user_input); free(server_reply); close(filefd); exit(EXIT_SUCCESS); } 装饰者:

login_required()

默认情况下,用户在成功进行身份验证时应重定向到的路径存储在名为“next”的查询字符串参数中,在此示例中为from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def my_view(request): #your code ,最后用户登录用户对象挂钩到{{1 }}