I am new to Django. I don't understand why we use login(request,user) to authenticate user to login
def login_user(request):
if request.method=="POST":
username=request.POST.get("username")
password=request.POST.get("password")
user= authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect("home")
return render(request,"login.html")
A login view typically takes a username and password, or some other credentials (one-time password, oauth tokens, etc.). It then validates it, and logs in the user.
By logging in, the user id is added to the session data of the HTTP session. This prevents sending credentials in each request, which is not very safe: yes, most HTTPS connections are encrypted, and is (likely) computationally very hard to "crack" the underlying HTTP message and thus reveal the credentials, but if that happens, then the credentials are known to the hacker, and then the hacker can for example log in themselves, or try the credentials on other sites. It would also be quite inconvenient that a user needs to enter credentials in each request, or that developers somehow have to store these in the browser's memory, and send the credentials each time.
Instead, a webserver usually has session storage. This means that the webserver somehow attaches data to a session, for example by using the webserver's memory, a file on the webserver, or the database.
In order to link a request to a session, the browser uses cookies. It has a cookie that contains the id of the session, and in each request, it sends the cookies for that domain including the one with the session id. A webserver like Django aims to make it (close) to impossible to guess session ids, such that one can not "hijack" someone else's session by just guessing different session ids until eventually there is a hit.
The
loginmethod exactly does that: it takes the id of the user, and saves that into the session variables for the session id submitted by the web-browser. If no session id was already given to the browser, in the response, it will add such cookie.The
login(…)function [Django-doc] thus does not check credentials, you can in fact attach any user you want. Often you of course want to check credentials, and in that case you useauthenticate(…)[Django-doc]. This will look for a user with the given username (or email, or some other identifier), check if the password is correct (or some other credential), and if that is the case, return the user. So a common flow is to just check if the credentials hold withauthenticate(…)and if that is the case, log in the user for which the credentials hold.But there are of course other views possible that work with one-time passwords (OTPs), OAuth tokens, etc.