DzITC
DzITC

Reputation: 879

Flask: 'str' object has no attribute 'is_active'

I'm using PostgreSQL as my database. It's my first-day using flask, but after many attempts to create a working login system I started to get many errors, but now only one left. I don't really know the reason, I tried researching, but I still don't understand where I'm making a mistake. I easily check if the user exists with the - user_management check_login function

class user_management:

    def __init__(self):
        pass


    def check_login(self, username, password):
        try:

            self.username = username
            self.password = password

            # psycopg2 stuff
            self.connection = psycopg2.connect(host='127.0.0.1', port=5432, password='ssss412', database='postgres', user='postgres')
            self.cursor = self.connection.cursor()
            self.query = f"select * from users where username=('{self.username}') and password=('{self.password}')"
            self.cursor.execute(self.query)
            self.connection.commit()
            self.result = self.cursor.fetchone()

        except KeyError:
            pass

        except Exception as error:
            print('error', error)

        finally:
            self.result = self.result or None

            if self.result:
                return True
            elif not self.result:
                return False
            else:
                return False


User = user_management()

@login_manager.user_loader
def load_user(user_id):
    print('idddd', user_id)
    return 2

class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
    remember = BooleanField('remember me')

class RegisterForm(FlaskForm):
    email = StringField('email', validators=[InputRequired(), Email(message='Invalid email address'), Length(max=50)])
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=15)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

@app.route('/') # Home
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        print(form.username.data, form.password.data)
        login_check = User.check_login(form.username.data, form.password.data)
        if login_check is True: # Logged in
            verification_check = User.check_verification(form.username.data, form.password.data)
            if verification_check is False:
                logout_user()
                return render_template('verification.html')
            elif verification_check is True:
                print('Verified')
                login_user(form.username.data, remember=form.remember.data)
                return redirect(url_for('dashboard'))
            elif verification_check == 'noacc':
                return render_template('index.html')
            elif verification_check == 'error':
                return render_template('index.html')
            return redirect(url_for('dashboard'))

        elif login_check is False: # Wrong cred
            return render_template('index.html')

    return render_template('login.html',form=form)

Edit: posting the whole error...

Traceback (most recent call last):
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\interkodas\Desktop\login -ex\app.py", line 170, in login
    login_user(form.username.data, remember=form.remember.data)
  File "C:\Users\interkodas\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_login\utils.py", line 158, in login_user
    if not force and not user.is_active:
AttributeError: 'str' object has no attribute 'is_active'

Upvotes: 1

Views: 2873

Answers (1)

jarmod
jarmod

Reputation: 78663

The Flask-Login login_user(user, remember, duration, force, fresh) method takes a user object as the first parameter, not a string representing the user.

One common way to get a user object is as follows (where User is the user model in your application, derived from db.Model):

user = User.query.get(form.username.data)

Some additional help can be found here.

Upvotes: 2

Related Questions