Skip to content

auth.login

Samuel S. Donovan edited this page Dec 10, 2022 · 7 revisions

auth.login utilizes auth.users and auth.sessions to create a cookie and a session token, which together are used to manage session.

auth.login(req, res, username, password) provides a function to log a user in and create a session token.

auth.login.endpoint provides a function with the signature function(req, res) that can be used to easily create a login endpoint.

Method

auth.login(req, res, username, password)

NOTE: As this method sets a cookie, it is imperative that it be called before any body is sent otherwise an error will be encountered statingError: Can't render headers after they are sent to the client..

Return Values

undefined User not found
false Password mismatch
true Login successful

NOTE: req.session/.user/.groups is updated upon successful login.

Endpoint

auth.login.endpoint provides an optional ready-to-use endpoint for logging users in.

auth.login.endpoint requires that req.body be defined with req.body.username and req.body.password as strings. This can be accomplished using express.json(). Various response codes are given depending on if the login was successful or not.

Example

const express = require('express');
const app = express();

const cookieParser = require('cookie-parser');
app.use(cookieParser("secret"));

const auth = require('express-cookie-session-auth');
app.use(auth);

app.post("/login", auth.login.endpoint);

Expected Body

{
    "username": "string",
    "password": "string
}

Response codes

200 Login successful
401 Login failed

Clone this wiki locally