Ocultar nome completo se não estiver logado

Olá,

Minha configuração atual é que o Discourse seja legível mesmo se você não estiver logado. Também ativei “habilitar nomes” para ver o nome completo logo ao lado do apelido.

Mas o que eu NÃO quero é que usuários não logados vejam o nome completo. Existe alguma maneira de desativar isso? Não encontrei.

Obrigado antecipadamente pela ajuda!

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:

Isso já foi integrado?

Gostaríamos que nossos fóruns fossem publicamente legíveis e indexados por mecanismos de busca, mas gostaríamos de não mostrar nomes reais, a menos que o usuário esteja logado (para que os nomes reais das pessoas não sejam expostos a não membros e mecanismos de busca).

Isso é possível? Tentei o código acima, mas não consegui fazê-lo funcionar.

O código acima precisa de uma atualização, @tshenry?

Acabei de verificar e o código ainda funciona. Todas as observações que mencionei continuam válidas.


Tentei rastrear todas as áreas em que o nome completo do usuário era usado como atributo title do avatar dele. O código a seguir deve cobrir todas as áreas, desde que você tenha hide_user_profiles_from_public e prioritize_username_in_ux habilitados. Infelizmente, ele depende da sobrescrita de alguns modelos, mas eles não mudam com frequência. Incluí links para os arquivos no GitHub caso você queira verificar se precisa atualizar algum código. A única modificação que fiz foi adicionar ou alterar o namePath para que use o nome de usuário em vez do nome completo.

<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>

Isso não deve ser considerado um método 100% seguro, mas manterá as informações fora do alcance de qualquer pessoa que não esteja se esforçando bastante para encontrá-las.

Em algum momento, seria bom ter essa funcionalidade como comportamento padrão sempre que prioritize_username_in_ux estiver habilitado.

@DavidO, você leu Beginner's guide to using Discourse Themes? Se você criou um componente de tema e adicionou o código à seção comum <head>, certifique-se de adicionar o componente ao seu tema principal.

Ok, obrigado. Vou trabalhar mais nisso.

Concordo que seria bom ter a opção de ocultar o nome real de pessoas que não estão logadas (incluindo mecanismos de busca).

Agradeço a ajuda, pessoal.

Estou pensando em tornar parte da minha comunidade pública. Para proteger os membros que contribuíram para aquela categoria específica, gostaria de usar algo como esse script de anonimização. No entanto, não gostaria de ativar o prioritize_username_in_ux. Por outro lado, não me importaria em ofuscar todos os nomes — tanto nomes de usuário quanto nomes reais, e talvez até mesmo os avatares. Existe uma maneira de conseguir isso com uma modificação do script?