How to restrict user to be logged only one time per session?

一笑奈何 提交于 2019-12-08 09:09:26

问题


I'm working a Symfony 1.4 apps, and I need to prevent a user beeing able to login more than once into the application, I mean if S/He is already logged in, it should not be able to logged in just opening a new browser.

  • user log in on Chrome.
  • Open Firefox, try to login and then can't login because a session is already active on Chrome

I want to avoid same user begins another session with a different browser in the same computer, or in another.


回答1:


The only solution I think about is to use session in MySQL (or your database) and then, check if a session is active for a given user so it can login or not.

It won't be an easy part. I did that one time but can't find the source code.. So I will describe what you will have to do.

  1. You need to activate sfPDOSessionStorage to store session in db (you can follow this blogpost)
  2. then create a custom storage that extend sfPDOSessionStorage to be able to add more field into the session table.

    You will have a new field (for example sess_user_id) inside your factories.yml, something like this :

    all:
      storage:
        class: myCustomPDOSessionStorage
        param:
          db_table:       session
          database:       propel
    
          db_id_col:      sess_id
          db_data_col:    sess_data
          db_time_col:    sess_time
          db_user_id_col: sess_user_id
    
  3. You will need to update method sessionRead & sessionWrite from your custom session storage to:

    • insert/update with the new field (the user_id)
    • check if a user_id already exist and session time is ok or not. If not, throw an exception. You will have to catch this exception when the user login, to display message about the problem.



回答2:


You can check whether user is logged in by calling:

sfContext::getInstance()->getUser()->isAuthenticated()

or inside action just:

$this->getUser()->isAuthenticated()

So I guess you want to have something like:

public function executeLogin($request)
{
    if ($this->getUser()->isAuthenticated()) {
        // redirect or whatever
        // $this->redirect(...);
    } else {
        // login user properly
    }
}


来源:https://stackoverflow.com/questions/14323648/how-to-restrict-user-to-be-logged-only-one-time-per-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!