Opencart客户端 强制登录

Opencart 默认客户端不需要登录,只有下单时才需登录,若想只有登录后才能访问系统,则可以参照文章
https://webocreation.com/check-admin-logged-front-page-opencart-2-3/

在catalog/controller/common/header.php中 添加下列代码

<?php
class ControllerCommonHeader extends Controller {
  public function index() {
    $skip = array(
      'account/login',
      'account/register',
      'account/forgotten'
    );
    if (!in_array($this->request->get['route'], $skip)) {
      if (!$this->customer->isLogged()) {
        $this->session->data['redirect'] = $this->url->link('common/home', '', true);
        $this->response->redirect($this->url->link('account/login', '', true));
      }
    }
    ////// other original codes
  }
}

该代码判断当前尚未登录,且访问页面不是“登录”、“注册”、“忘记密码”这三个页面,则强制重定向到登录页面

在“logout”页面,当前代码没有清除cookie。最好在catalog\controller\account\logout.php中利用如下代码删除相关cookie.

  unset($_COOKIE['OCSESSID']);
setcookie($this->config->get('session_name'), "", time(), 
    ini_get('session.cookie_path'), ini_get('session.cookie_domain'));


注: https://stackoverflow.com/questions/20357962/opencart-force-login 提供另外一种方案
The other possibility is to create a preAction - e.g. like maintenance mode. I have used this once and I think this is much cleaner solution than implementing it in the view template (so it follows the MVC pattern - logic is done in controller, view is only for presenting the data and gathering input from user).
但是该方案“$this->url” 为空,所以可能仅适用于某个版本

  1. Create a class catalog/controller/common/login.php
class ControllerCommonLogin extends Controller {
  public function index() {
    if($this->config->get('config_store_id') == 1) { // if desired store, continue checking
      if(!$this->customer->isLogged()) { // Check user isn't logged in
        if(empty($this->request->get['route']) || 
         $this->request->get['route'] != 'account/login') { // Redirect if route isn't account/login
          $this->redirect($this->url->link('account/login', '', 'SSL'));
        }
      }
    }
  }
}
  1. then open up index.php (frontend one) and find line:
/ Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));

and after add this:

// Login needed pre-action
$controller->addPreAction(new Action('common/login'));
posted @ 2024-07-06 12:47  cyj2024  阅读(5)  评论(0编辑  收藏  举报