Beispiel #1
0
def register():
    if request.method == 'POST':
        username = request.from['username']
        password = request.from['password']
        db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User is already registered.'

        if error is None:
            db.execute(
                'INSERT INTO user(username, password) VALUES (?, ?)',
                (username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Beispiel #2
0
def register():
    if request.method == 'POST': # user submitted the form, request.method will be 'POST'. start validating the input.
        username = request.form(['username']) # request.form is a special type of dict mapping submitted form keys and values
        password = request.form(['password'])
        db = get_db()
        error = None

        if not username: # Validate that username and password are not empty.
            error = 'Username is required'
        elif not password:
            error = 'Password is required'
        elif not db.execute('SELECT if FROM user WHERE username = ?', (username,)).fetchone() is not None: 
        # Validate that username is not already registered by querying the database and checking if a result is returned. 
        # db.execute takes a SQL query with ? placeholders for any user input, and a tuple of values to replace the placeholders with
        # fetchone() returns one row from the query.
            error = 'User {} is already registered'.format(username)

        if error is None: # If validation succeeds, insert the new user data into the database.
            db.execute('INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)))
            db.commit() # Since this query modifies data, db.commit() needs to be called afterwards to save the changes.
            return redirect(url_for('auth.login')) # After storing the user, they are redirected to the login page. url_for() generates the URL for the login view based on its name. redirect() generates a redirect response to the generated URL.

        flash(error) # If validation fails, the error is shown to the user. flash() stores messages that can be retrieved when rendering the template.

    return render_template('auth/register.html') # When the user initially navigates to auth/register, or there was a validation error, an HTML page with the registration form should be shown. render_template() will render a template containing the HTML
Beispiel #3
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Beispiel #4
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password'
        if error is None:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))
        flash(error)
    return render_template('auth/login.html')
Beispiel #5
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?', (username,)).fetchone() # The user is queried first and stored in a variable for later use.

        if user is None:
            error = 'Incorrect username'
        elif not check_password_hash(user['password'], password): # hashes the submitted password in the same way as the stored hash and securely compares them
            error = 'Incorrect password'

        if error is None:
            # session is a dict that stores data across requests. When validation succeeds, the user’s id is stored in a new session.
            # The data is stored in a cookie that is sent to the browser, and the browser then sends it back with subsequent requests. 
            # Flask securely signs the data so that it can’t be tampered with.
            session.clear() 
            session['user_id'] = user['id'] # key 'user_id' in session dict. 
            return redirect(url_for('index')) 

        flash(error)

        return render_template('auth/login.html')