1
votes

Forgive me for my lack of knowledge. Am a complete newbie to flask and web technology concept. I am in the process to build the login part of an app. After searching, I found flask login to be an option to use. After going through SQLAlchemy,Flask-login homepage, some blogs,tutorials,and going through questions on stack-oflow, tried to build a basic login part-code given below. I used SQLAlchemy, and database is POSTGres. This is just a start involving the login through email-password and session handling will involve more functions later.

In the code, I authenticate the user-id and password, and then assign corresponding UUID(primary key in User DB) from the database as a session variable, in order to create a session. Am I right in doing so?. In some 'stack-of' answers, it is mentioned that session-id is to be randomly generated after user authentication, and stored in a separate sessions table in database. Got confused. I am passing UUID which is my primary key, as an 'id' for 'get_id' method. Is is right??

I tried implementing this code. However in chrome developement console, I see sessions, which dissappear after i logout.

    import flask
    from flask import Flask,render_template,request,url_for,redirect,session
    from flask_sqlalchemy import SQLAlchemy
    from flask_login import current_user, UserMixin, LoginManager, login_required, login_user, 
    logout_user

    app = Flask(__name__)
    db = SQLAlchemy(app)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:test@localhost/hw'
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'
    app.config['SECRET_KEY'] = 'thisissecret'

    class User(UserMixin,db.Model):
        __tablename__ = 'user'
        __table_args__ = {'schema': 'logging'}
        user_id = db.Column(db.VARCHAR,primary_key = True)
        first_name = db.Column(db.VARCHAR)
        last_name = db.Column(db.VARCHAR)
        email = db.Column(db.VARCHAR)
        contact_no = db.Column(db.VARCHAR)
        status = db.Column(db.BOOLEAN)
        loginpassword = db.Column(db.VARCHAR)

        def get_id(self):
            return str(self.user_id)

    @login_manager.user_loader
    def load_user(id):
        try:
            return User.query.get(id)
        except:
            return None


    @app.route('/logedin',methods=['POST'])
    def logedin():
        session.pop('id', None)
        em = request.form['email']
        pwd = request.form['password']
        usr = User.query.filter_by(email = em).first()
        if usr:
            if usr and usr.loginpassword == pwd:
                login_user(usr,remember = False)
                session['id'] = usr.user_id
                return ('you r logged in')
            else:
                return '<h1>user not found</h1>'
        else:
        #return render_template('testlogin.html')
            return '<h1>user not found</h1>'


    @app.before_request
    def check_logedin():
        if not 'id' in session:
            return render_template('testlogin.html')


    @app.route('/login')
    def login():
        if current_user is_authenticated():
            return redirect(url_for('home'))
        else:
            return render_template('testlogin.html')


    @app.route('/logout')
    @login_required
    def logout():
        logout_user()
        session.pop('id', None)
        return 'you are logged out'

    @app.route('/home')
    @login_required
    def home():
        return ('The current user is in.')

    if __name__ == '__main__':
        app.run(debug=True)

Apologies if some silly things. But I am unable to make out this session thing. Appreciate your help. Thanks in advance

1

1 Answers

1
votes

You say that you "assign corresponding [user id] as a session variable", but some say "that session-id is to be randomly generated after user authentication, and stored in a separate sessions table in database".

Those two things are not in conflict. A session ID is a value sent to the user. It identifies session data. What is important is that the session data is hidden from the user and that a valid session ID cannot be guessed by a user.

What you are doing with flask.session is fine. You are placing a variable into a session and flask is taking care of the rest (giving only a random session ID to the user).

All you need to do is save user id in the session:

session['id'] = usr.user_id

and later read user id from the session

user_id = session.get('id')

Note that the user_id read this way may be None, meaning the user is not logged in.

This does not keep session data in a database, at least by default, but that probably is not important in your case. A good reason to keep data in a data base would be for example if you have a distributed system in which several servers are serving the same website, so the user might log in in one server, but then access another server.