Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Flask REST API API Protection Password hashing

Not sure what is wrong with my code here. Any help?

Bummer: Didn't get back a properly hashed password; User.hash_password should be a static method

import datetime

from peewee import *

from argon2 import PasswordHasher

DATABASE = SqliteDatabase('recipes.db')

HASHER = PasswordHasher()

class User(Model): 
    username = CharField(unique=True) 
    password = CharField()

class Meta:
    database = DATABASE

def create_user(cls, username, password):
    except cls.DoesNotExist:
        user = cls(username=username)
        user.password = cls.hash_password(password) #Here the class instance is calling the static method we just made
        return user
        raise Exception("User already exists")  

def hash_password(password):   #function takes in user password and hashes it
    return HASHER.hash(password)

class Recipe(Model):
    name = CharField()
    created_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = DATABASE

class Ingredient(Model):
    name = CharField()
    description = CharField()
    quantity = DecimalField()
    measurement_type = CharField()
    recipe = ForeignKeyField(Recipe)

class Meta:
    database = DATABASE

def initialize():
    DATABASE.create_tables([User, Recipe, Ingredient], safe=True)

1 Answer

Josh Keenan
Josh Keenan
19,528 Points

You are close:

user = cls(username=username, password=password)
user.password = user.hash_password(password)

Here's my solution, passing the password into the instance creation in the first line and then taking the password from that and hashing it. If you have any questions feel free to ask