Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaiste/f0b9c3f353ee4f2c69c159bac665e09f to your computer and use it in GitHub Desktop.
Save zaiste/f0b9c3f353ee4f2c69c159bac665e09f to your computer and use it in GitHub Desktop.
Node.js, PostgreSQL Authentication & Session Management

Node.js, PostgreSQL Authentication & Session Management

The following flow is implemented in Huncwot - Macro framework for monolithic JavaScript applications, with batteries included.

Setup

Register/Signup

login/signin corresponds to a create method (a HTTP POST action) for Person entity.

const create = async ({ params }) => {
  const user = params.user
  
  const hashedPassword = await bcrypt.hash(password, 10);
  
  const [{ id: person_id }] = await db`person`
    .insert({
      name,
      email,
      password: hashed_password,
      role,
      project_id,
      site_id
    })
    .return('id');

  
  const token = Session.create(person_id);
}

Login/Signin

login/signin corresponds to a create method (a HTTP POST action) for Session entity.

const create = async ({ params }) {
  const { email, password } = params;

  const [person] = await db`person`
    .where({ email })
    .return('id', 'name', 'email', 'password');

  if (person) {
    const { id: person_id, password: actual_password, name, email } = person;
    const match = await bcrypt.compare(password, actual_password);

    if (match) {
      const token = await Session.create(person_id);
      return created({ id: person_id, token, name, email });
    } else {
      return unauthorized();
    }
  } else {
    return unauthorized();
  }
}

Business Logic

  1. A person sends username/password to register.
  2. bcrypt takes plain text password as input and produces hashed version to be stored securely in the database.
  3. At each login, a person sends the password in plain text for bcrypt to hash it again and compare with the version stored in the database.
  4. If the passwords match, crypto generates a random string to use as an authentication token for subsequent requests to use.
  5. The token is stored in a separate table called Session
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment