Hide full name if not logged in

Hi,

my current configuration is, that discourse is readable if you are not logged in. Also I set “enable names” to see the full name right near the nick name.

But what I DONT want is, that not logged in users can see the full name. Is there any way to disable this? I didnt found it.

Thx in advance for your help!

Is this possible with CSS @tshenry? I think we have the anon classes to do it?

I was going to respond to this earlier with some CSS, but remembered the case where username and display name match, resulting in the username being hidden.

In that situation it would present an avatar, with no name whatsoever.

But still better than get crawled by any bots :slight_smile: other forum software (plug-ins) hiding the full name and also anonymze the nick in e.g. to “user 34726”. Would be really perfect if I could hide at least the real name :slight_smile:

I’m going to look into this when I get a chance. It should be doable with a small theme component. I’ve got a decent amount on my plate, so it maybe be a little bit before I get back to you with anything.

Alright, the script for removing the full name for anons is fairly simple. Just create a new theme component and add the following to the Common </head> section:

<script type="text/discourse-plugin" version="0.8">
  api.reopenWidget("poster-name", {
    html(attrs) {
      let contents = this._super(attrs);
      if(contents.length == 2 && !api.getCurrentUser()) {
        return contents.shift();
      }
      return contents;
    }
  });
</script>

Some things to note:

  • To better avoid full names getting out, it would be best to set the site setting hide_user_profiles_from_public
  • This code assumes you have prioritize_username_in_ux enabled
  • A user’s full name will be used as the title attribute for a user avatar, so it will be displayed whenever someone hovers over an avatar. I haven’t found a solution for this yet, but I’ll come back if one is found.

Hope that helps :slightly_smiling_face:

Это когда-либо было интегрировано?

Мы хотим, чтобы наши форумы были общедоступны для чтения и индексировались поисковыми системами, но при этом не отображать настоящие имена, если пользователь не авторизован (чтобы настоящие имена людей не были доступны неучастникам и поисковым системам).

Возможно ли это? Я попробовал использовать код выше, но не смог заставить его работать.

Требуется ли обновление для кода выше, @tshenry?

Я только что проверил, и код всё ещё работает. Все упомянутые мной замечания по-прежнему актуальны.


Я попытался найти все места, где полное имя пользователя использовалось в качестве атрибута title для его аватара. Приведённый ниже код должен охватить все такие случаи, при условии, что у вас включены параметры hide_user_profiles_from_public и prioritize_username_in_ux. К сожалению, это решение требует переопределения нескольких шаблонов, хотя они меняются нечасто. Я включил ссылки на файлы на GitHub, если вам когда-нибудь понадобится проверить, нужно ли обновлять код. Единственное изменение, которое я внёс, — это добавление или изменение namePath, чтобы он использовал имя пользователя вместо полного имени.

<script type="text/discourse-plugin" version="0.8">
  api.reopenWidget("poster-name", {
    html(attrs) {
      let contents = this._super(attrs);
      if(contents.length == 2 && api.getCurrentUser()) {
        return contents.shift();
      }
      return contents;
    }
  });
  
  api.reopenWidget("post-avatar", {
    html(attrs) {
      attrs.name = "";
      return  this._super(attrs);
    }
  });
  
  api.reopenWidget("topic-map-summary", {
    html(attrs, state) {
      attrs.createdByName = "";
      attrs.lastPostName = "";
      return  this._super(attrs, state);
    }
  });
  
  api.reopenWidget("topic-participant", {
    html(attrs, state) {
      attrs.name = "";
      return  this._super(attrs, state);
    }
  });

</script>


<!-- https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/templates/components/user-info.hbs -->
<script type="text/x-handlebars" data-template-name="components/user-info">
  <div class="user-image">
    <div class="user-image-inner">
      <a href="{{unbound userPath}}" data-user-card="{{unbound user.username}}">{{avatar user namePath="user.username" imageSize="large"}}</a>
      {{#if user.primary_group_name}}
        {{avatar-flair
          flairURL=user.primary_group_flair_url
          flairBgColor=user.primary_group_flair_bg_color
          flairColor=user.primary_group_flair_color
          groupName=user.primary_group_name}}
      {{/if}}
    </div>
  </div>

  <div class="user-detail">
    <div class='name-line'>
      <span class="username"><a href="{{unbound userPath}}" data-user-card="{{unbound user.username}}">{{format-username user.username}}</a></span>
      <span class="name">{{unbound name}}</span>
    </div>
    <div class="title">{{unbound user.title}}</div>

    {{#if hasBlock}}
      <div class='details'>
        {{yield}}
      </div>
    {{/if}}

  </div>
</script>

<!-- https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/templates/list/posters-column.raw.hbs -->
<script type="text/x-handlebars" data-template-name="list/posters-column.raw">
  <td class='posters'>
  {{#each posters as |poster|}}
  <a href="{{poster.user.path}}" data-user-card="{{poster.user.username}}" class="{{poster.extraClasses}}">{{avatar poster avatarTemplatePath="user.avatar_template" usernamePath="user.username" namePath="user.username" imageSize="small"}}</a>
  {{/each}}
  </td>
</script>

<!-- https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/templates/components/latest-topic-list-item.hbs -->
<script type="text/x-handlebars" data-template-name="components/latest-topic-list-item">
  <div class='topic-poster'>
    {{#user-link user=topic.lastPoster}}
      {{avatar topic.lastPoster namePath="topic.lastPoster" imageSize="large"}}
    {{/user-link}}
  </div>
  <div class='main-link'>
    <div class='top-row'>
      {{raw "topic-status" topic=topic}}
      {{topic-link topic}}
      {{#if topic.featured_link}}
        {{topic-featured-link topic}}
      {{/if}}
      {{topic-post-badges newPosts=topic.totalUnread unseen=topic.unseen url=topic.lastUnreadUrl}}
    </div>
    <div class='bottom-row'>
      {{category-link topic.category}}
      {{discourse-tags topic mode="list"}}
    </div>
  </div>
  <div class='topic-stats'>
    {{raw "list/posts-count-column" topic=topic tagName="div"}}
    <div class="topic-last-activity">
      <a href="{{topic.lastPostUrl}}" title="{{topic.bumpedAtTitle}}">{{format-date topic.bumpedAt format="tiny" noTitle="true"}}</a>
    </div>
  </div>
</script>

Этот метод не следует считать на 100% безопасным, но он скроет информацию от всех, кто не прилагает особых усилий для её поиска.

В будущем было бы здорово, чтобы эта функциональность стала частью базового поведения при включении параметра prioritize_username_in_ux.

@DavidO, вы читали Beginner's guide to using Discourse Themes? Если вы создали компонент темы и добавили код в общий раздел <head>, обязательно добавьте этот компонент в вашу основную тему.

Окей, спасибо. Буду работать над этим дальше.

Согласен, было бы здорово сделать это опцией, чтобы скрывать настоящее имя от тех, кто не вошел в систему (включая поисковые системы).

Оцениваю это, ребята.

Я думаю о том, чтобы сделать часть моего сообщества публичной. Чтобы защитить участников, внесших вклад в эту конкретную категорию, я хотел бы использовать что-то вроде этого скрипта для анонимизации. Однако я не хотел бы включать параметр prioritize_username_in_ux. С другой стороны, мне не противно было бы скрыть все имена — как имена пользователей, так и реальные имена, и, возможно, даже аватары. Есть ли способ добиться этого с помощью модификации этого скрипта?