TYPO3 fe_user如何通过php代码登录用户?

时间:2017-05-19 12:06:44

标签: typo3

我有TYPO3 7.6.18和扩展femanager。

$(document).ready(function(){

  var folder = "img/people";

  $.ajax({
    url : folder,
    success: function (data) {
        console.log(data);
    }
  });

});
var showPhotos = function(photos){

    $('.image-container').empty().justifiedImages({
        images : photos,
        rowHeight: 500,
        maxRowHeight: $('.gallery').height(),
        thumbnailPath: function(photo, width, height){
            var purl = photo.url_s;
            if( photo.url_n && (width > photo.width_s * 1.2 || height > photo.height_s * 1.2) ) purl = photo.url_n;
            if( photo.url_m && (width > photo.width_n * 1.2 || height > photo.height_n * 1.2) ) purl = photo.url_m;
            if( photo.url_z && (width > photo.width_m * 1.2 || height > photo.height_m * 1.2) ) purl = photo.url_z;
            if( photo.url_l && (width > photo.width_z * 1.2 || height > photo.height_z * 1.2) ) purl = photo.url_l;
            return purl;
        },
        getSize: function(photo){
            return {width: photo.width_s, height: photo.height_s};
        },
        margin: 1
    });
}

这段代码不起作用。错误:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>listing directory /img/people/</title>
    <style>* {
  margin: 0;
  padding: 0;
  outline: 0;
}

body {
  padding: 80px 100px;
  font: 13px "Helvetica Neue", "Lucida Grande", "Arial";
  background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9));
  background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9);
  background-repeat: no-repeat;
  color: #555;
  -webkit-font-smoothing: antialiased;
}
h1, h2, h3 {
  font-size: 22px;
  color: #343434;
}
h1 em, h2 em {
  padding: 0 5px;
  font-weight: normal;
}
h1 {
  font-size: 60px;
}
h2 {
  margin-top: 10px;
}
h3 {
  margin: 5px 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
  font-size: 18px;
}
ul li {
  list-style: none;
}
ul li:hover {
  cursor: pointer;
  color: #2e2e2e;
}
ul li .path {
  padding-left: 5px;
  font-weight: bold;
}
ul li .line {
  padding-right: 5px;
  font-style: italic;
}
ul li:first-child .path {
  padding-left: 0;
}
p {
  line-height: 1.5;
}
a {
  color: #555;
  text-decoration: none;
}
a:hover {
  color: #303030;
}
#stacktrace {
  margin-top: 15px;
}
.directory h1 {
  margin-bottom: 15px;
  font-size: 18px;
}
ul#files {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
ul#files li {
  float: left;
  width: 30%;
  line-height: 25px;
  margin: 1px;
}
ul#files li a {
  display: block;
  height: 25px;
  border: 1px solid transparent;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  overflow: hidden;
  white-space: nowrap;
}
ul#files li a:focus,
ul#files li a:hover {
  background: rgba(255,255,255,0.65);
  border: 1px solid #ececec;
}
ul#files li a.highlight {
  -webkit-transition: background .4s ease-in-out;
  background: #ffff4f;
  border-color: #E9DC51;
}
#search {
  display: block;
  position: fixed;
  top: 20px;
  right: 20px;
  width: 90px;
  -webkit-transition: width ease 0.2s, opacity ease 0.4s;
  -moz-transition: width ease 0.2s, opacity ease 0.4s;
  -webkit-border-radius: 32px;
  -moz-border-radius: 32px;
  -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03);
  -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03);
  -webkit-font-smoothing: antialiased;
  text-align: left;
  font: 13px "Helvetica Neue", Arial, sans-serif;
  padding: 4px 10px;
  border: none;
  background: transparent;
  margin-bottom: 0;
  outline: none;
  opacity: 0.7;
  color: #888;
}
#search:focus {
  width: 120px;
  opacity: 1.0; 
}

/*views*/
#files span {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  text-indent: 10px;
}
#files .name {
  background-repeat: no-repeat;
}
#files .icon .name {
  text-indent: 28px;
}

/*tiles*/
.view-tiles .name {
  width: 100%;
  background-position: 8px 5px;
}
.view-tiles .size,
.view-tiles .date {
  display: none;
}

/*details*/
ul#files.view-details li {
  float: none;
  display: block;
  width: 90%;
}
ul#files.view-details li.header {
  height: 25px;
  background: #000;
  color: #fff;
  font-weight: bold;
}
.view-details .header {
  border-radius: 5px;
}
.view-details .name {
  width: 60%;
  background-position: 8px 5px;
}
.view-details .size {
  width: 10%;
}
.view-details .date {
  width: 30%;
}
.view-details .size,
.view-details .date {
  text-align: right;
  direction: rtl;
}

/*mobile*/
@media (max-width: 768px) {
  body {
    font-size: 13px;
    line-height: 16px;
    padding: 0;
  }
  #search {
    position: static;
    width: 100%;
    font-size: 2em;
    line-height: 1.8em;
    text-indent: 10px;
    border: 0;
    border-radius: 0;
    padding: 10px 0;
    margin: 0;
  }
  #search:focus {
    width: 100%;
    border: 0;
    opacity: 1;
  }
  .directory h1 {
    font-size: 2em;
    line-height: 1.5em;
    color: #fff;
    background: #000;
    padding: 15px 10px;
    margin: 0;
  }
  ul#files {
    border-top: 1px solid #cacaca;
  }
  ul#files li {
    float: none;
    width: auto !important;
    display: block;
    border-bottom: 1px solid #cacaca;
    font-size: 2em;
    line-height: 1.2em;
    text-indent: 0;
    margin: 0;
  }
  ul#files li:nth-child(odd) {
    background: #e0e0e0;
  }
  ul#files li a {
    height: auto;
    border: 0;
    border-radius: 0;
    padding: 15px 10px;
  }
  ul#files li a:focus,
  ul#files li a:hover {
    border: 0;
  }
  #files .header,
  #files .size,
  #files .date {
    display: none !important;
  }
  #files .name {
    float: none;
    display: inline-block;
    width: 100%;
    text-indent: 0;
    background-position: 0 50%;
  }
  #files .icon .name {
    text-indent: 41px;
  }
}
</style>
    <script>
      function $(id){
        var el = 'string' == typeof id
          ? document.getElementById(id)
          : id;

        el.on = function(event, fn){
          if ('content loaded' == event) {
            event = window.attachEvent ? "load" : "DOMContentLoaded";
          }
          el.addEventListener
            ? el.addEventListener(event, fn, false)
            : el.attachEvent("on" + event, fn);
        };

        el.all = function(selector){
          return $(el.querySelectorAll(selector));
        };

        el.each = function(fn){
          for (var i = 0, len = el.length; i < len; ++i) {
            fn($(el[i]), i);
          }
        };

        el.getClasses = function(){
          return this.getAttribute('class').split(/\s+/);
        };

        el.addClass = function(name){
          var classes = this.getAttribute('class');
          el.setAttribute('class', classes
            ? classes + ' ' + name
            : name);
        };

        el.removeClass = function(name){
          var classes = this.getClasses().filter(function(curr){
            return curr != name;
          });
          this.setAttribute('class', classes.join(' '));
        };

        return el;
      }

      function search() {
        var str = $('search').value
          , links = $('files').all('a');

        links.each(function(link){
          var text = link.textContent;

          if ('..' == text) return;
          if (str.length && ~text.indexOf(str)) {
            link.addClass('highlight');
          } else {
            link.removeClass('highlight');
          }
        });
      }

      $(window).on('content loaded', function(){
        $('search').on('keyup', search);
      });
    </script>
  </head>
  <body class="directory">
    <input id="search" type="text" placeholder="Search" autocomplete="off" />
    <div id="wrapper">
      <h1><a href="/">~</a> / <a href="/img">img</a> / <a href="/img/people">people</a> / </h1>
      <ul id="files" class="view-tiles"><li><a href="/img" class="" title=".."><span class="name">..</span><span class="size"></span><span class="date"></span></a></li>
<li><a href="/img/people/1.jpg" class="" title="1.jpg"><span class="name">1.jpg</span><span class="size">57195</span><span class="date">5/19/2017 2:02:18 PM</span></a></li>
<li><a href="/img/people/2.jpg" class="" title="2.jpg"><span class="name">2.jpg</span><span class="size">83345</span><span class="date">5/19/2017 2:02:18 PM</span></a></li>
<li><a href="/img/people/3.jpg" class="" title="3.jpg"><span class="name">3.jpg</span><span class="size">77362</span><span class="date">5/19/2017 2:02:18 PM</span></a></li>
<li><a href="/img/people/4.jpg" class="" title="4.jpg"><span class="name">4.jpg</span><span class="size">71906</span><span class="date">5/19/2017 2:02:18 PM</span></a></li>
<li><a href="/img/people/5.jpg" class="" title="5.jpg"><span class="name">5.jpg</span><span class="size">90691</span><span class="date">5/19/2017 2:02:18 PM</span></a></li></ul>
    </div>
  </body>
</html>

这是硬代码吗?可能存在更好的方式吗?

你知道如何通过php代码登录用户吗?

5 个答案:

答案 0 :(得分:3)

对于$loginData['uname']我使用电子邮件作为用户名,您只需使用自己的用户名更改它($user->getUsername());

Class StandardLogin:

<?php
namespace Ads\Adsmanager\Authentication\Login;

/**
 * Standard Login of users
 *
 * @author Andrei Todorut <todorutac@gmail.com>
 */
class StandardLogin extends \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication implements LoginInterface
{    
    /**
     * 
     * @param \Ads\Adsmanager\Domain\Model\User $user
     * @return boolean
     */
    public function login(\Ads\Adsmanager\Domain\Model\User $user)
    {
        $passwordProcessor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Saltedpasswords\\Salt\\PhpassSalt');

        $loginData = array(
            'uname' => $user->getEmail(), //usernmae
            'uident' => $user->getPassword(), //password
            'status' => 'login'
        );


        $this->checkPid = false;
        $info = $this->getAuthInfoArray();
        $info['db_user']['username_column'] = 'email';

        $user_db = $this->fetchUserRecord($info['db_user'], $loginData['uname']);
        if ($user_db && $passwordProcessor->checkPassword($user->getPassword(), $user_db['password'])) {

            $this->setSession($user_db);
            return true;
        }
        return false;
    }


    private function setSession($user_db) 
    {

        $GLOBALS['TSFE']->fe_user->createUserSession($user_db);
        $GLOBALS['TSFE']->fe_user->user = $user_db;
        $GLOBALS['TSFE']->fe_user->setKey('ses', 'fe_typo_user', $user_db);
    }
}

您的操作控制器:

<?php 
//...
//stuff
public function loginAction(\TYPO3\CMS\Extbase\Domain\Model\User $user)
{
    $login = new StandardLogin();
    $login->login($user);
}
//...

答案 1 :(得分:1)

  

使用用户名作为参数

进行调用
function loginUser($username)
{
    $GLOBALS['TSFE']->fe_user->checkPid = '';
    $info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
    $user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
    $loginData = array('uname' => $username, 'uident' => $user['password'], 'status' => 'login');

    $GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
    $GLOBALS['TSFE']->fe_user->createUserSession($user);

    $reflection = new \ReflectionClass($GLOBALS['TSFE']->fe_user);
    $setSessionCookieMethod = $reflection->getMethod('setSessionCookie');
    $setSessionCookieMethod->setAccessible(TRUE);
    $setSessionCookieMethod->invoke($GLOBALS['TSFE']->fe_user);

    $GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $session_data = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);

    setcookie('fe_typo_user', $session_data['ses_id'], time() + (86400 * 30), "/");
    setcookie('nc_staticfilecache', 'fe_typo_user_logged_in', time() + (86400 * 30), "/");
}

答案 2 :(得分:0)

也许您错过了$GLOBALS['TSFE']->fe_user->fetchGroupData();$GLOBALS["TSFE"]->fe_user->storeSessionData();来保存更改。

我只有一个旧的(TYPO3 4.5)示例,它起作用:

$user = $GLOBALS['TSFE']->fe_user->getRawUserByName($username);

$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS["TSFE"]->fe_user->user = $GLOBALS["TSFE"]->fe_user->fetchUserSession();
$GLOBALS['TSFE']->fe_user->fetchGroupData();
$GLOBALS["TSFE"]->fe_user->setKey("ses", "do_redirect", 0);
$GLOBALS["TSFE"]->fe_user->storeSessionData();

答案 3 :(得分:0)

Typo3最近更改了它的Cookie策略,以默认情况下不创建fe_typo_user(由于GDPR / DSGVO)。其他解决方案由于错过了“ start()”而不再起作用。

以下功能可以正常工作:

ng serve --project <application-name>

它缺乏认真的状态处理。如果我进一步改进它,可以在这里找到:https://gist.github.com/tserowski/8572c2314f7f909f31248a9ad0023509

答案 4 :(得分:0)

尝试此尺寸。 适用于TYPO3 V10。

/**
 * User sign in.
 *
 * @param string $suppliedPassword - The just-supplied password
 * @param string $storedPassword  - The stored user password
 * @param int $permanentLogin   - Whether to log the user permanently.
 *        - Requires setting $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] to 1
 *          in your ext_localconf file.
 *        - Optionally, set $GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] to how long
 *          you want the permanent session to last.
 * @param int $uid - The UID of the user you want to login.
 * @param null|mixed $userSessionData - User's data you want to persist.
 */
public function logon(string $suppliedPassword, string $storedPassword, int $permanentLogin, int $uid, $userSessionData = NULL): void {

    /**
     * Password.
     */
    if ($this->passwordIsAuthentic($suppliedPassword, $storedPassword)) {

        #Log in user
        $GLOBALS['TSFE']->fe_user->is_permanent = $permanentLogin;
        $GLOBALS['TSFE']->fe_user->createUserSession(['uid' => $uid]);

        if($userSessionData){

            /**
             * @tip You can change the key name '__USER__' to whatever you like.
             */
            $GLOBALS['TSFE']->fe_user->setAndSaveSessionData('__USER__', $userSessionData);
        }

        $GLOBALS['TSFE']->fe_user->loginSessionStarted = 1;
        $GLOBALS['TSFE']->fe_user->setSessionCookie();

        /**
         * @Note $GLOBALS['TSFE']->loginUser is deprecated in favor of 
         * $context->getPropertyFromAspect('frontend.user', 'isLoggedIn');
         */
    }
}

/**
 * Check password here
 *
 * @param string $suppliedPassword
 * @param string $storedPassword
 *
 * @return bool
 */
private function passwordIsAuthentic(string $suppliedPassword, string $storedPassword): bool {

    $saltFactory = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashFactory::class);
    $invalidPasswordHashException = NULL;

    try {
        $hashInstance = $saltFactory->get($storedPassword, TYPO3_MODE);
        if (($hashInstance instanceof \TYPO3\CMS\Core\Crypto\PasswordHashing\PasswordHashInterface) && $hashInstance->checkPassword($suppliedPassword, $storedPassword)) {
            return TRUE;
        }
    } catch (\TYPO3\CMS\Core\Crypto\PasswordHashing\InvalidPasswordHashException $invalidPasswordHashException) {

        // Get a hashed password instance for the hash stored in db of this user
        return FALSE;
    }

    return FALSE;
}