this post was submitted on 21 Oct 2024
84 points (86.2% liked)

Programming

17254 readers
69 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities [email protected]



founded 1 year ago
MODERATORS
top 50 comments
sorted by: hot top controversial new old
[–] [email protected] 1 points 1 day ago* (last edited 1 day ago)

Code before:

async function createUser(user) {
    if (!validateUserInput(user)) {
        throw new Error('u105');
    }

    const rules = [/[a-z]{1,}/, /[A-Z]{1,}/, /[0-9]{1,}/, /\W{1,}/];
    if (user.password.length >= 8 && rules.every((rule) => rule.test(user.password))) {
        if (await userService.getUserByEmail(user.email)) {
            throw new Error('u212');
        }
    } else {
        throw new Error('u201');
    }

    user.password = await hashPassword(user.password);
    return userService.create(user);
}

Here's how I would refac it for my personal readability. I would certainly introduce class types for some concern structuring and not dangling functions, but that'd be the next step and I'm also not too familiar with TypeScript differences to JavaScript.

const passwordRules = [/[a-z]{1,}/, /[A-Z]{1,}/, /[0-9]{1,}/, /\W{1,}/]
function validatePassword(plainPassword) => plainPassword.length >= 8 && passwordRules.every((rule) => rule.test(plainPassword))
async function userExists(email) => await userService.getUserByEmail(user.email)

async function createUser(user) {
    // What is validateUserInput? Why does it not validate the password?
    if (!validateUserInput(user)) throw new Error('u105')
    // Why do we check for password before email? I would expect the other way around.
    if (!validatePassword(user.password)) throw new Error('u201')
    if (!userExists(user.email)) throw new Error('u212')

    const hashedPassword = await hashPassword(user.password)
    return userService.create({ email: user.email, hashedPassword: hashedPassword });
}

Noteworthy:

  • Contrary to most JS code, [for independent/new code] I use the non-semicolon-ending style following JavaScript Standard Style - see their no semicolons rule with reasoning; I don't actually know whether that's even valid TypeScript, I just fell back into JS
  • I use oneliners for simple check-error-early-returns
  • I commented what was confusing to me
  • I do things like this to fully understand code even if in the end I revert it and whether I implement a fix or not. Committing refacs is also a big part of what I do, but it's not always feasible.
  • I made the different interface to userService.create (a different kind of user object) explicit
  • I named the parameter in validatePassword plainPasswort to make the expectation clear, and in the createUser function more clearly and obviously differentiate between "the passwords"/what password is. (In C# I would use a param label on call validatePassword(plainPassword: user.password) which would make the interface expectation and label transformation from interface to logic clear.

Structurally, it's not that different from the post suggestion. But it doesn't truth-able value interpretation, and it goes a bit further.

[–] [email protected] 21 points 3 days ago* (last edited 3 days ago) (1 children)

In addition to the excellent points made by steventhedev and koper:

user.password = await hashPassword(user.password);

Just this one line of code alone is wrong.

  1. It's unclear, but quite likely that the type has changed here. Even in a duck typed language this is hard to manage and often leads to bugs.
  2. Even without a type change, you shouldn't reuse an object member like this. Dramatically better to have password and hashed_password so that they never get mixed up. If you don't want the raw password available after this point, zero it out or delete it.
  3. All of these style considerations apply 4x as strongly when it's a piece of code that's important to the security of your service, which obviously hashing passwords is.
[–] [email protected] -5 points 2 days ago (3 children)

I appreciate the security concerns, but I wouldn't consider overriding the password property with the hashed password to be wrong. Raw passwords are typically only needed in three places: user creation, login, and password reset. I'd argue that having both password and hashedPassword properties in the user object may actually lead to confusion, since user objects are normally used in hundreds of places throughout the codebase. I think, when applicable, we should consider balancing security with code maintainability by avoiding redundancy and potential confusion.

[–] [email protected] 9 points 2 days ago (1 children)

When is the hashed password needed other than user creation, login or password resets? Once you have verified the user you should not need it at all. If anything storing it on the user at all is likely a bad idea. Really you have two states here - the unauthed user which has their login details, and an authed user which has required info about the user but not their password, hashed or not.

Personally I would construct the user object from the request after doing auth - that way you know that any user object is already authed and it never needs to store the password or hash at all.

[–] [email protected] -1 points 2 days ago (1 children)

Perhaps I was unclear. What I meant to say is that, whenever possible, we shouldn't have multiple versions of a field, especially when there is no corresponding plaintext password field in the database, as is the case here.

[–] [email protected] 4 points 2 days ago

And they were arguing the same - just renaming the property rather than reusing it. You should only have one not both but naming them differently can make it clear which one you have.

But here I am arguing to not have either on the user object at all. They are only needed at the start of a request and should never be needed after that point. So no point in attaching them to a user object - just verify the username and password and pass around user object after that without either the password or hash. Not everything needs to be added to a object.

[–] [email protected] 6 points 2 days ago

I absolutely agree. An even better structure wouldn't have a raw password field on the user object at all.

[–] [email protected] 4 points 2 days ago

I agree. The field shouldn't have been called 'password' in the first place, but rather 'plaintextPassword' or similar. That makes the code much more readable, if at a glance I know if I'm dealing with the hash or the plaintext version.

[–] [email protected] 7 points 3 days ago

A quick glance and this seemed nothing to do with self documenting code and everything to do with the flaws when code isn't strictly typed.

load more comments
view more: next ›