Login Procedure

To authenticate the request, call express-sweet.services.Authentication.authenticate() method.
This method returns true if the authentication succeeds and false if it fails.
If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

The post-authentication logic depends on whether the login request is received asynchronously or synchronously, so an example of both logics is shown here.
  1. Create a user table to authenticate.
    CREATE TABLE `user` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `name` varchar(30) NOT NULL,
      `email` varchar(255) NOT NULL,
      `password` varchar(100) NOT NULL,
      `icon` varchar(768) NOT NULL DEFAULT MD5(RAND()),
      `created` datetime NOT NULL DEFAULT current_timestamp(),
      `modified` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
      PRIMARY KEY (`id`),
      UNIQUE KEY `ukUserEmail` (`email`),
      UNIQUE KEY `ukUserIcon`(`icon`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  2. Set the email address and password columns of the user table to be used for authentication in the config file config/authentication.js.
    /**
     * Authentication user ID field name, defaults to `username`.
     * @type {string}
     */
    username: 'email',
    
    /**
     * Authentication password field name, defaults to `password`.
     * @type {string}
     */
    password: 'password'
  3. For asynchronous requests.
    Returns the authentication result and executes subsequent processing on the front end.

    When the form submits, it sends a login request (/api/users/login), and the routes/api/user.js router receives the request, authenticates it based on the username and password, and returns the result.
    After that, the front end checks the authentication result returned from the router and redirects to / if the authentication result is successful (true).
    If you redirect to /, the page will automatically switch to the URL specified in success_redirect of config/authentication.js.
    import {Router} from 'express';
    import * as sweet from 'express-sweet';
    const router = Router();
    const Authentication = sweet.services.Authentication;
    
    router.post('/login', async (req, res, next) => {
      const isAuth = await Authentication.authenticate(req, res, next);
      res.json(isAuth);
    });
    export default router;
    const express = require('express');
    const router = express.Router();
    const Authentication = require('express-sweet').services.Authentication;
    
    router.post('/login', async (req, res, next) => {
      const isAuth = await Authentication.authenticate(req, res, next);
      res.json(isAuth);
    });
    module.exports = router;
    <form id="form">
      <label>Email</label><input type="email" name="email" required autofocus>
      <label class="form-label">Password</label><input type="password" name="password" required>
      <button type="submit">Login</button>
    </form>
    
    <script>
    const form = document.querySelector('#form');
    form.addEventListener('submit', async event => {
      event.preventDefault();
    
      // Send an authentication request.
      const res = await fetch('/api/users/login', {method: 'POST', body: new FormData(form)});
      const isAuth = await res.json();
    
      // If login fails.
      if (!isAuth)
        return void alert('The user name or password is incorrect.');
    
      // After logging in successfully, you will be taken to the top page.
      location.href = '/';
    });
    </script>
  4. For sync request.
    If the authentication is successful, redirect to the page with the URL specified by success_redirect in config/authentication.js.
    If it fails, redirect to the page with the URL specified by failure_redirect in config/authentication.js.
    import {Router} from 'express';
    import * as sweet from 'express-sweet';
    const router = Router();
    const Authentication = sweet.services.Authentication;
    
    router.post('/login', async (req, res, next) => {
      const isAuth = await Authentication.authenticate(req, res, next);
      if (isAuth) 
        Authentication.successRedirect(res);
      else
        Authentication.failureRedirect(req, res);
    });
    export default router;
    const express = require('express');
    const router = express.Router();
    const Authentication = require('express-sweet').services.Authentication;
    
    router.post('/login', async (req, res, next) => {
      const isAuth = await Authentication.authenticate(req, res, next);
      if (isAuth) 
        Authentication.successRedirect(res);
      else
        Authentication.failureRedirect(req, res);
    });
    module.exports = router;
    <form method="post" action="/api/users/login">
      <label>Email</label><input type="email" name="email" required autofocus>
      <label class="form-label">Password</label><input type="password" name="password" required>
      <button type="submit">Login</button>
    </form>