Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - how can I limit the access in Flask

I create a project to simulate login my company's website.And put it in my server to let others to use.

But the company website has a limit with single ip can only open 2 sessions.

So when more than 2 my colleagues login my project ,the third one can't login.

Is there a way to limit the access , So when there's 2 users are using ,the third one can't login.

Should I use a global variable to store a number of current users?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can save the ip address, user id or login and last time of logging in to your app into database and check against it when some user logs in.

If user logs in, you store his/her ip address, id/login and last time of logging in to the app into table. If an attempt is made to login third time from the same ip address you reject it.

When user logs out you remove the record from the database.

You need to be careful with situations when user session expires automatically but the record is in the database.

In order to avoid that you can set permanent session to True (session will not be destroyed even if the browser gets closed) and set its duration to a fixed amount of time - let's say 48 hours. Then you can create a procedure which will run periodically in your db and check the last time of logging in and the duration of the session. If the difference is more than 48 hours, it deletes the record from the database.

You should also take into account whether your ip addresses are static or dynamic. With static ip addresses it should be much easier. With dynamic - it depends on how often they change, but definitely it will be more complicated.

Before a user logs in you can get his/her ip address this way:

from flask import request

@app.route('/login', methods=['GET', 'POST']):
def login():
    ip_address = request.remote_addr
    # Check the ip_address and how many sessions are bound to it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...