diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 6186cefaf..000000000 --- a/.babelrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "sourceMaps": true, - "presets": [ - "es2015" - ], - "plugins": [ - "add-module-exports", - "transform-class-properties", - "transform-decorators-legacy", - "transform-object-assign", - "transform-object-rest-spread", - "transform-react-jsx" - ] -} diff --git a/client/.babelrc b/client/.babelrc index 1d4fe2508..63b1c53de 100644 --- a/client/.babelrc +++ b/client/.babelrc @@ -1,6 +1,14 @@ { - "extends": "../.babelrc", + "presets": [ + "es2015" + ], "plugins": [ - "transform-async-to-generator" + "add-module-exports", + "transform-class-properties", + "transform-decorators-legacy", + "transform-object-assign", + "transform-object-rest-spread", + "transform-async-to-generator", + "transform-react-jsx" ] } diff --git a/client/coral-admin/src/components/ui/Header.css b/client/coral-admin/src/components/ui/Header.css index e30cb46d7..eba94d892 100644 --- a/client/coral-admin/src/components/ui/Header.css +++ b/client/coral-admin/src/components/ui/Header.css @@ -74,8 +74,12 @@ background-color: transparent; transition: background-color 200ms; + &:hover { + background-color: #232323; + } + &.active { - background-color: #232323; + background-color: #232323; } } diff --git a/client/coral-admin/src/constants/comments.js b/client/coral-admin/src/constants/comments.js index 603a3ce00..98f2e039d 100644 --- a/client/coral-admin/src/constants/comments.js +++ b/client/coral-admin/src/constants/comments.js @@ -1,5 +1,7 @@ export const SHOW_BANUSER_DIALOG = 'SHOW_BANUSER_DIALOG'; export const HIDE_BANUSER_DIALOG = 'HIDE_BANUSER_DIALOG'; +export const SHOW_SUSPENDUSER_DIALOG = 'SHOW_SUSPENDUSER_DIALOG'; +export const HIDE_SUSPENDUSER_DIALOG = 'HIDE_SUSPENDUSER_DIALOG'; export const COMMENTS_MODERATION_QUEUE_FETCH_REQUEST = 'COMMENTS_MODERATION_QUEUE_FETCH_REQUEST'; export const COMMENTS_MODERATION_QUEUE_FETCH_SUCCESS = 'COMMENTS_MODERATION_QUEUE_FETCH_SUCCESS'; export const COMMENT_CREATE_SUCCESS = 'COMMENT_CREATE_SUCCESS'; diff --git a/client/coral-admin/src/containers/Community/Community.css b/client/coral-admin/src/containers/Community/Community.css index 958e41ccb..28551c8a0 100644 --- a/client/coral-admin/src/containers/Community/Community.css +++ b/client/coral-admin/src/containers/Community/Community.css @@ -185,6 +185,8 @@ justify-content: space-between; .author { + font-size: 16px; + font-weight: bold; min-width: 230px; display: flex; align-items: center; @@ -223,7 +225,6 @@ color: black; max-width: 500px; word-wrap: break-word; - font-weight: 300; } .flagged { @@ -301,7 +302,6 @@ } } - .actionButton { transform: scale(.8); margin: 0; @@ -315,12 +315,19 @@ .flaggedBy { display: inline; padding: 3px; + font-size: 16px; } .flaggedByLabel { font-weight: bold; + font-size: 14px; } .flaggedReasons { padding-top: 15px; + margin-left: 24px; +} + +.flaggedByReason { + font-size: 1tpx; } diff --git a/client/coral-admin/src/containers/Community/FlaggedAccounts.js b/client/coral-admin/src/containers/Community/FlaggedAccounts.js index 1a6d349c8..692cef70d 100644 --- a/client/coral-admin/src/containers/Community/FlaggedAccounts.js +++ b/client/coral-admin/src/containers/Community/FlaggedAccounts.js @@ -7,13 +7,15 @@ const lang = new I18n(translations); import styles from './Community.css'; import Loading from './Loading'; -import EmptyCard from '../../components/EmptyCard'; +import EmptyCard from 'coral-admin/src/components/EmptyCard'; import User from './components/User'; const FlaggedAccounts = ({...props}) => { const {commenters, isFetching} = props; const hasResults = !isFetching && commenters && !!commenters.length; +// if (commenter.status === 'PENDING' && commenter.actions.length > 0) { + return (
@@ -21,19 +23,16 @@ const FlaggedAccounts = ({...props}) => { { hasResults ? commenters.map((commenter, index) => { - if (commenter.status === 'PENDING' && commenter.actions.length > 0) { - return ; - } - return null; + return ; }) : {lang.t('community.no-flagged-accounts')} } diff --git a/client/coral-admin/src/containers/Community/components/SuspendUserDialog.js b/client/coral-admin/src/containers/Community/components/SuspendUserDialog.js index 44f38f796..20e221c48 100644 --- a/client/coral-admin/src/containers/Community/components/SuspendUserDialog.js +++ b/client/coral-admin/src/containers/Community/components/SuspendUserDialog.js @@ -49,7 +49,7 @@ class SuspendUserDialog extends Component { const {suspendUser, user} = this.props; const {stage} = this.state; - const cancel = this.props.onClose; + const cancel = this.props.handleClose; const next = () => this.setState({stage: stage + 1}); const suspend = () => { suspendUser({userId: user.user.id, message: this.state.email}) diff --git a/client/coral-admin/src/containers/Community/components/User.js b/client/coral-admin/src/containers/Community/components/User.js index 71598e352..20b599a7a 100644 --- a/client/coral-admin/src/containers/Community/components/User.js +++ b/client/coral-admin/src/containers/Community/components/User.js @@ -35,7 +35,7 @@ const User = props => {
- flagFlags({ user.actions.length }): + flag{lang.t('community.flags')}({ user.actions.length }): { user.action_summaries.map( (action, i ) => { return @@ -67,8 +67,8 @@ const User = props => { } )} +
-
{modActionButtons.map((action, i) => diff --git a/client/coral-admin/src/containers/Configure/StreamSettings.js b/client/coral-admin/src/containers/Configure/StreamSettings.js index 4725221ce..ab0ef6af6 100644 --- a/client/coral-admin/src/containers/Configure/StreamSettings.js +++ b/client/coral-admin/src/containers/Configure/StreamSettings.js @@ -37,6 +37,10 @@ const updateInfoBoxContent = (updateSettings) => (event) => { updateSettings({infoBoxContent}); }; +const updateAutoClose = (updateSettings, autoCloseStream) => () => { + updateSettings({autoCloseStream}); +}; + const updateClosedMessage = (updateSettings) => (event) => { const closedMessage = event.target.value; updateSettings({closedMessage}); @@ -131,6 +135,11 @@ const StreamSettings = ({updateSettings, settingsError, settings, errors}) => {
+
+ +
{lang.t('configure.close-after')}
diff --git a/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js b/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js index a6d3527c7..61352b921 100644 --- a/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js +++ b/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js @@ -163,6 +163,7 @@ class ModerationContainer extends Component { activeTab={activeTab} singleView={moderation.singleView} selectedIndex={this.state.selectedIndex} + bannedWords={settings.wordlist.banned} suspectWords={settings.wordlist.suspect} showBanUserDialog={props.showBanUserDialog} acceptComment={props.acceptComment} diff --git a/client/coral-admin/src/containers/ModerationQueue/ModerationQueue.js b/client/coral-admin/src/containers/ModerationQueue/ModerationQueue.js index b90b59f81..79b4ce7e4 100644 --- a/client/coral-admin/src/containers/ModerationQueue/ModerationQueue.js +++ b/client/coral-admin/src/containers/ModerationQueue/ModerationQueue.js @@ -24,6 +24,7 @@ const ModerationQueue = ({comments, selectedIndex, commentCount, singleView, loa commentType={activeTab} selected={i === selectedIndex} suspectWords={props.suspectWords} + bannedWords={props.bannedWords} actions={actionsMap[status]} showBanUserDialog={props.showBanUserDialog} acceptComment={props.acceptComment} @@ -47,6 +48,7 @@ const ModerationQueue = ({comments, selectedIndex, commentCount, singleView, loa }; ModerationQueue.propTypes = { + bannedWords: PropTypes.arrayOf(PropTypes.string).isRequired, suspectWords: PropTypes.arrayOf(PropTypes.string).isRequired, currentAsset: PropTypes.object, showBanUserDialog: PropTypes.func.isRequired, diff --git a/client/coral-admin/src/containers/ModerationQueue/components/Comment.js b/client/coral-admin/src/containers/ModerationQueue/components/Comment.js index f68bab2b7..a2bbbf092 100644 --- a/client/coral-admin/src/containers/ModerationQueue/components/Comment.js +++ b/client/coral-admin/src/containers/ModerationQueue/components/Comment.js @@ -19,6 +19,7 @@ const lang = new I18n(translations); const Comment = ({actions = [], ...props}) => { const links = linkify.getMatches(props.comment.body); + const linkText = links ? links.map(link => link.raw) : []; const actionSummaries = props.comment.action_summaries; return (
  • @@ -49,9 +50,9 @@ const Comment = ({actions = [], ...props}) => {
  • - - - +

    {links ? Contains Link : null} @@ -77,6 +78,7 @@ Comment.propTypes = { acceptComment: PropTypes.func.isRequired, rejectComment: PropTypes.func.isRequired, suspectWords: PropTypes.arrayOf(PropTypes.string).isRequired, + bannedWords: PropTypes.arrayOf(PropTypes.string).isRequired, currentAsset: PropTypes.object, comment: PropTypes.shape({ body: PropTypes.string.isRequired, @@ -92,9 +94,4 @@ Comment.propTypes = { }) }; -const linkStyles = { - backgroundColor: 'rgb(255, 219, 135)', - padding: '1px 2px' -}; - export default Comment; diff --git a/client/coral-admin/src/containers/ModerationQueue/components/ModerationMenu.js b/client/coral-admin/src/containers/ModerationQueue/components/ModerationMenu.js index b8160e21b..0606fdb81 100644 --- a/client/coral-admin/src/containers/ModerationQueue/components/ModerationMenu.js +++ b/client/coral-admin/src/containers/ModerationQueue/components/ModerationMenu.js @@ -8,28 +8,46 @@ import {Link} from 'react-router'; const lang = new I18n(translations); -const ModerationMenu = ({asset, premodCount, rejectedCount, flaggedCount, selectSort, sort}) => { - const premodPath = asset ? `/admin/moderate/premod/${asset.id}` : '/admin/moderate/premod'; - const rejectPath = asset ? `/admin/moderate/rejected/${asset.id}` : '/admin/moderate/rejected'; - const flagPath = asset ? `/admin/moderate/flagged/${asset.id}` : '/admin/moderate/flagged'; +const ModerationMenu = ( + {asset, premodCount, rejectedCount, flaggedCount, selectSort, sort} +) => { + const premodPath = asset + ? `/admin/moderate/premod/${asset.id}` + : '/admin/moderate/premod'; + const rejectPath = asset + ? `/admin/moderate/rejected/${asset.id}` + : '/admin/moderate/rejected'; + const flagPath = asset + ? `/admin/moderate/flagged/${asset.id}` + : '/admin/moderate/flagged'; + return ( -
    +
    -
    +
    - + {lang.t('modqueue.premod')} - - {lang.t('modqueue.rejected')} - - + {lang.t('modqueue.flagged')} + + {lang.t('modqueue.rejected')} +
    selectSort(sort)}> diff --git a/client/coral-admin/src/containers/ModerationQueue/components/styles.css b/client/coral-admin/src/containers/ModerationQueue/components/styles.css index 9576045de..51086dfd4 100644 --- a/client/coral-admin/src/containers/ModerationQueue/components/styles.css +++ b/client/coral-admin/src/containers/ModerationQueue/components/styles.css @@ -170,7 +170,7 @@ span { border-bottom: 1px solid #e0e0e0; font-size: 18px; width: 100%; - max-width: 660px; + max-width: 700px; min-width: 400px; margin: 0 auto; position: relative; @@ -192,7 +192,7 @@ span { } &.selected { - max-width: 670px; + max-width: 720px; max-height: 410px; } @@ -216,10 +216,12 @@ span { justify-content: space-between; .author { - font-weight: 600; + font-weight: 300; min-width: 230px; display: flex; align-items: center; + color: #262626; + font-size: 16px; } } @@ -242,10 +244,11 @@ span { } .created { - color: #666; - font-size: 13px; + color: #262626; + font-size: 14px; margin-left: 15px; line-height: 1px; + font-weight: 300; } .actionButton { @@ -260,6 +263,7 @@ span { max-width: 500px; word-wrap: break-word; font-weight: 300; + font-size: 16px; } .flagged { diff --git a/client/coral-admin/src/graphql/queries/index.js b/client/coral-admin/src/graphql/queries/index.js index 291ea6bc5..f0e8e5b70 100644 --- a/client/coral-admin/src/graphql/queries/index.js +++ b/client/coral-admin/src/graphql/queries/index.js @@ -67,7 +67,15 @@ export const loadMore = (fetchMore) => ({limit, cursor, sort, tab, asset_id}) => }); }; -export const modUserFlaggedQuery = graphql(MOD_USER_FLAGGED_QUERY); +export const modUserFlaggedQuery = graphql(MOD_USER_FLAGGED_QUERY, { + options: ({params: {action_type = 'FLAG'}}) => { + return { + variables: { + action_type: action_type + } + }; + } +}); export const modQueueResort = (id, fetchMore) => (sort) => { return fetchMore({ diff --git a/client/coral-admin/src/graphql/queries/modUserFlaggedQuery.graphql b/client/coral-admin/src/graphql/queries/modUserFlaggedQuery.graphql index 98f2191eb..c99d94583 100644 --- a/client/coral-admin/src/graphql/queries/modUserFlaggedQuery.graphql +++ b/client/coral-admin/src/graphql/queries/modUserFlaggedQuery.graphql @@ -1,5 +1,5 @@ -query Users ($n: ACTION_TYPE) { - users (query:{action_type: $n}){ +query Users ($action_type: ACTION_TYPE) { + users (query:{action_type: $action_type}){ id username status diff --git a/client/coral-admin/src/index.js b/client/coral-admin/src/index.js index 00190847a..9a532856e 100644 --- a/client/coral-admin/src/index.js +++ b/client/coral-admin/src/index.js @@ -7,7 +7,6 @@ import store from './services/store'; import App from './components/App'; -import 'react-mdl/extra/material.css'; import 'react-mdl/extra/material.js'; render( diff --git a/client/coral-admin/src/translations.json b/client/coral-admin/src/translations.json index f59499e50..1021978f1 100644 --- a/client/coral-admin/src/translations.json +++ b/client/coral-admin/src/translations.json @@ -18,6 +18,7 @@ "banned": "Banned", "banned-user": "Banned User", "loading": "Loading results", + "flags": "Flags", "flaggedaccounts": "Flagged Usernames", "people": "People", "no-flagged-accounts": "The Account Flags queue is currently empty.", @@ -161,22 +162,23 @@ "es": { "errors": { "NOT_AUTHORIZED": "Acción no autorizada.", - "LOGIN_MAXIMUM_EXCEEDED": "Ha realizado demasiados intentos fallidos de contraseña. Por favor espera." + "LOGIN_MAXIMUM_EXCEEDED": "Ha realizado demasiados intentos fallidos de colocar la contraseña. Por favor espere." }, "community": { "username_and_email": "Usuario y E-mail", "account_creation_date": "Fecha de creación de la cuenta", "newsroom_role": "Rol en la redacción", - "admin": "Administrador", - "moderator": "Moderador", + "admin": "Administradora", + "moderator": "Moderadora", "role": "Seleccionar rol...", - "no-results": "No se encontraron usuarios con ese nombre de usuario o correo electronico.", + "no-results": "No se encontraron usuarixs con ese nombre de usuario o e-mail.", "status": "Estado", "select-status": "Seleccionar estado...", "active": "Activa", "banned": "Suspendido", "banned-user": "Usuario Suspendido", "loading": "Cargando resultados", + "flags": "Reporte", "flaggedaccounts": "Nombres de Usuario Reportados", "people": "Gente", "no-flagged-accounts": "No hay ninguna cuenta reportada.", @@ -185,9 +187,9 @@ "This looks like an ad/marketing": "Spam/Propaganda", "This username is offensive": "Ofensivo", "Other": "Otros", - "ban_user": "Quieres suspender el Usuario?", + "ban_user": "Quieres suspender al Usuario?", "are_you_sure": "Estas segura que quieres suspender a {0}?", - "note": "Nota: Suspender a este usuario no le va a permitir borrar ni editar ni comentar.", + "note": "Nota: Suspender a este usuario no le va a permitir (al usuario) borrar ni editar ni comentar.", "cancel": "Cancelar", "yes_ban_user": "Si, Suspendan el usuario" }, @@ -203,7 +205,8 @@ "username": "nombre de usuario", "email_subject": "Su cuenta ha sido suspendida temporariamente", "email": "Otra persona de la comunidad recientemente marcó su nombre de usuario para ser revisado. Por su contenido, el nombre de usuario ha sido rechazado. Esto quiere decir que no puede comentar, gustar o marcar contenido hasta que modifique su nombre de usuario. Por favor, envienos un correo a moderator@newsorg.com si tiene alguna pregunta o preocupación", - "write_message": "Escribir un mensaje" + "write_message": "Escribir un mensaje", + "loading": "Cargando resultados" }, "modqueue": { "likes": "gustos", @@ -222,34 +225,34 @@ "banned_user": "Usuario Suspendido" }, "user": { - "user_bio": "", - "bio_flags": "", - "username_flags": "" + "user_bio": "marcas para este usuario", + "bio_flags": "marcas para esta biografia", + "username_flags": "marcas para este nombre de usuario" }, "configure": { - "closed-stream-settings": "Mensaje cuando los comentarios están cerrados en el artículo", + "closed-stream-settings": "Mensaje a enviar cuando los comentarios están cerrados en el artículo", "stream-settings": "Configuración de Comentarios", "moderation-settings": "Configuración de Moderación", - "tech-settings": "Configuración Technical", + "tech-settings": "Configuración Técnica", "custom-css-url": "URL CSS a medida", - "custom-css-url-desc": "URL de una hoja de estilo que va a sobrescribir los estilos por defecto de Embed Stream. Puede ser interna o externa.", + "custom-css-url-desc": "URL de una hoja de estilo que va a sobrescribir los estilos por defecto del hilo de comentarios. Puede ser interna o externa.", "dashboard": "Panel", "enable-pre-moderation": "Habilitar pre-moderación", "enable-pre-moderation-text": "Los moderadores deben aprobar cada comentario antes de que sea publicado.", - "require-email-verification": "Necesita confirmación de correo", - "require-email-verification-text": "Nuevos usuarios deben verificar sus correos antes de comentar", + "require-email-verification": "Necesita confirmación de e-mail", + "require-email-verification-text": "Nuevos usuarios deben verificar sus e-mails antes de comentar", "include-comment-stream": "Incluir la Descripción a un Hilo de Comentario para los y las Lectoras.", "include-comment-stream-desc": "Escribir un mensaje que será agregado a la parte de arriba del tu hilo de comentarios. Por ejemplo, un tema, guias de comunidad, etc.", "include-text": "Incluir tu texto aqui.", "comment-settings": "Configuración de Comentarios", "embed-comment-stream": "Colocar Hilo de Comentarios", - "enable-premod-links": "Pre-Moderar Commentarios que contienen Links", - "enable-premod-links-text": "Los y las Moderadoras deben probar cualquier comentario que contengan links antes de su publicación.", - "wordlist": "Palabras Suspendidas y Suspechosas", - "banned-word-text": "Comentarios que contengan estas palabras o frases, no separadas por comas y en mayusculas o minusuculas, serán automaticamente separadas de los comentarios publicados.", - "suspect-word-text": "Comments which contain these words or phrases (not case-sensitive) will be highlighted in the comment stream. Type a word and press Enter or Tab to add. Optionally paste a comma-separated list.", - "banned-words-title": "Banned words list", - "suspect-words-title": "Suspect words list", + "enable-premod-links": "Pre-Moderar Commentarios que contienen Enlaces", + "enable-premod-links-text": "Los y las Moderadoras deben aprobar cualquier comentario que contengan links antes de su publicación.", + "wordlist": "Palabras Suspendidas y Sospechosas", + "banned-word-text": "Comentarios que contengan estas palabras o frases, no separadas por comas y en mayusculas o minusuculas, serán automaticamente marcadas para separar los comentarios publicados.", + "suspect-word-text": "Comentarios que contengan estas palabras o frases, considerando mayusculas y minusculas, serán automaticamente destacadas en los comentarios publicados. Escribir una palabra y apretar Enter o Tabulador para agergarla. Opcionalmente pegar una lista separada por coma.", + "banned-words-title": "Lista de palabras prohibidas", + "suspect-words-title": "Lista de palabras sospechosas", "save-changes": "Guardar Cambios", "copy-and-paste": "Copiar y pegar el código de más abajo en tu CMS para colocar la caja de comentarios en tus articulos", "moderate": "Moderar", @@ -268,21 +271,21 @@ "comment-count-text-post": " caracteres", "comment-count-error": "Por favor escribe un número válido.", "domain-list-title": "Lista de Dominios Permitidos", - "domain-list-text": "Agrega dominios permitidos a Talk, e.g. tu localhost, staging y ambientes de production (ex. localhost:3000, staging.domain.com, domain.com)." + "domain-list-text": "Agrega dominios permitidos a Talk, por ejemplo tu localhost, staging y ambientes de producción (ej. localhost:3000, staging.domain.com, domain.com)." }, "embedlink": { "copy": "Copiar" }, "bandialog": { - "ban_user": "Quieres suspender el Usuario?", - "are_you_sure": "Estas segura que quieres suspender a {0}?", - "note": "Nota: Suspender este usuario también va a colocar este comentario en la cola de Rechazados.", + "ban_user": "¿Quieres suspender el Usuario?", + "are_you_sure": "¿Estás segura que quieres suspender a {0}?", + "note": "Nota: Suspender a este usuario también va a colocar este comentario en la cola de Rechazados.", "cancel": "Cancelar", "yes_ban_user": "Si, Suspendan el usuario" }, "dashbord": { "next-update": "{0} minutos hasta la siguiente actualización.", - "auto-update": "Los datos se actualizan automaticamente cada 5 minutos o cuando Recargas.", + "auto-update": "Los datos se actualizan automaticamente cada 5 minutos o cuando recargas.", "no_flags": "¡Nadie ha marcado nada en los últimos 5 minutos! ¡Bravo!", "no_likes": "A nadie le ha gustado algún comentario en los últimos 5 minutos. Todo tranquilo.", "flags": "Marcados", @@ -290,21 +293,19 @@ "comment_count": "comentarios" }, "streams": { - "empty_result": "No se encuentro articulo con esta busqueda. Tal vez extender la busqueda?", - "search": "", - "filter-streams": "", - "stream-status": "", - "all": "", - "open": "", - "closed": "", - "newest": "", - "oldest": "", - "sort-by": "", - "open": "", - "closed": "", + "empty_result": "No se encuentro articulo con esta busqueda. ¿Tal vez puedas extender la busqueda?", + "search": "buscar", + "filter-streams": "Filtrar Hilos de Comentarios", + "stream-status": "Estado del Hilo de Comentarios", + "all": "todxs", + "open": "abrir", + "closed": "cerrado", + "newest": "más nuevoß", + "oldest": "más viejo", + "sort-by": "ordenar por", "article": "artículo", - "pubdate": "", - "status": "" + "pubdate": "Fecha de Pblicación", + "status": "Estado" } } } diff --git a/client/coral-configure/translations.json b/client/coral-configure/translations.json index a40c12bc1..341fe58e7 100644 --- a/client/coral-configure/translations.json +++ b/client/coral-configure/translations.json @@ -9,7 +9,7 @@ "enablePremodLinks": "Pre-Moderate Comments Containing Links", "enablePremodLinksDescription": "Moderators must approve any comment containing a link before its published.", "enableQuestionBox": "Ask readers a question", - "enableQuestionBoxDescription": "This question will appear at the top of this comment stram. Ask readers about a certain issue in the article or pose discussion questions, etc.", + "enableQuestionBoxDescription": "This question will appear at the top of this comment stream. Ask readers about a certain issue in the article or pose discussion questions, etc.", "includeQuestionHere": "Write your question here." } }, @@ -20,8 +20,8 @@ "description": "Como Administrador/a puedes modificar las opciones de los comentarios en este artículo", "enablePremod": "Activar Pre Moderación", "enablePremodDescription": "Los y las Moderadoras deben aprobar cualquier comentario antes de su publicación", - "enablePremodLinks": "Pre-Moderar Commentarios que contienen Links", - "enablePremodLinksDescription": "Los y las Moderadoras deben probar cualquier comentario que contengan links antes de su publicación.", + "enablePremodLinks": "Pre-Moderar Comentarios que contienen Enlaces", + "enablePremodLinksDescription": "Los y las moderadoras deben aprobar cualquier comentario que contengan enlaces antes de su publicación.", "enableQuestionBox": "Hacer una pregunta a los y las lectoras.", "enableQuestionBoxDescription": "Esta pregunta aparecera en la parte de arriba del hilo de comentarios.", "includeQuestionHere": "Escribir la pregunta aquí." diff --git a/client/coral-embed-stream/src/Comment.css b/client/coral-embed-stream/src/Comment.css index 6966d82ab..01022ae66 100644 --- a/client/coral-embed-stream/src/Comment.css +++ b/client/coral-embed-stream/src/Comment.css @@ -1,9 +1,10 @@ .Reply { position: relative; + margin-bottom: 15px; } .Comment { - + margin-bottom: 15px; } .pendingComment { diff --git a/client/coral-embed-stream/src/Embed.js b/client/coral-embed-stream/src/Embed.js index 6ac3ab68a..2edca12c5 100644 --- a/client/coral-embed-stream/src/Embed.js +++ b/client/coral-embed-stream/src/Embed.js @@ -122,8 +122,8 @@ class Embed extends Component {
    - - {lang.t('profile')} + + {lang.t('MY_COMMENTS')} Configure Stream {loggedIn && this.props.logout().then(refetch)} changeTab={this.changeTab}/>} @@ -162,7 +162,6 @@ class Embed extends Component { charCount={asset.settings.charCountEnable && asset.settings.charCount} /> : null } -
    :

    {asset.settings.closedMessage}

    @@ -172,6 +171,7 @@ class Embed extends Component { refetch={refetch} offset={signInOffset}/>} {loggedIn && user && } + {loggedIn && } { highlightedComment && { - this.initialState = false; - loadMoreComments(assetId, comments, loadMore, parentId); - }}> - {topLevel ? lang.t('viewMoreComments') : this.replyCountFormat(replyCount)} - + ?
    + +
    : null; } } diff --git a/client/coral-embed-stream/style/default.css b/client/coral-embed-stream/style/default.css index 629efd29f..4c427543e 100644 --- a/client/coral-embed-stream/style/default.css +++ b/client/coral-embed-stream/style/default.css @@ -212,6 +212,7 @@ hr { .coral-plugin-commentcontent-text { margin-bottom: 7px; + font-size: 16px; } .coral-plugin-author-name-text { @@ -417,8 +418,11 @@ button.comment__action-button[disabled], /* Load More */ -button.coral-load-more { - width: 100%; +.coral-load-more { + text-align: center; +} + +.coral-load-more button { text-align: center; color: #FFF; background-color: #2376D8; @@ -427,9 +431,10 @@ button.coral-load-more { border-radius: 2px; line-height: 1em; text-transform: capitalize; + display: inline-block; } -button.coral-load-more:hover { +.coral-load-more:hover button { background-color: #4399FF; } diff --git a/client/coral-framework/actions/asset.js b/client/coral-framework/actions/asset.js index 02e72ea98..609525986 100644 --- a/client/coral-framework/actions/asset.js +++ b/client/coral-framework/actions/asset.js @@ -2,7 +2,7 @@ import * as actions from '../constants/asset'; import coralApi from '../helpers/response'; import {addNotification} from '../actions/notification'; -import I18n from 'coral-framework/modules/i18n/i18n'; +import I18n from '../../coral-framework/modules/i18n/i18n'; import translations from './../translations'; const lang = new I18n(translations); diff --git a/client/coral-framework/actions/auth.js b/client/coral-framework/actions/auth.js index 9dedaa2f2..01174cf05 100644 --- a/client/coral-framework/actions/auth.js +++ b/client/coral-framework/actions/auth.js @@ -1,8 +1,9 @@ -import I18n from 'coral-framework/modules/i18n/i18n'; +import I18n from '../../coral-framework/modules/i18n/i18n'; import translations from './../translations'; const lang = new I18n(translations); import * as actions from '../constants/auth'; import coralApi, {base} from '../helpers/response'; +import {pym} from 'coral-framework'; // Dialog Actions export const showSignInDialog = (offset = 0) => ({type: actions.SHOW_SIGNIN_DIALOG, offset}); @@ -135,7 +136,8 @@ const forgotPassowordFailure = () => ({type: actions.FETCH_FORGOT_PASSWORD_FAILU export const fetchForgotPassword = email => (dispatch) => { dispatch(forgotPassowordRequest(email)); - coralApi('/account/password/reset', {method: 'POST', body: {email}}) + const redirectUri = pym.parentUrl || location.href; + coralApi('/account/password/reset', {method: 'POST', body: {email, loc: redirectUri}}) .then(() => dispatch(forgotPassowordSuccess())) .catch(error => dispatch(forgotPassowordFailure(error))); }; diff --git a/client/coral-framework/actions/notification.js b/client/coral-framework/actions/notification.js index f2cc053ec..cb1aee5dd 100644 --- a/client/coral-framework/actions/notification.js +++ b/client/coral-framework/actions/notification.js @@ -1,4 +1,4 @@ -import {pym} from 'coral-framework'; +import {pym} from '../../coral-framework'; export const addNotification = (notifType, text) => { pym.sendMessage('coral-alert', `${notifType}|${text}`); diff --git a/client/coral-framework/actions/user.js b/client/coral-framework/actions/user.js index bf2a77402..3e80b718c 100644 --- a/client/coral-framework/actions/user.js +++ b/client/coral-framework/actions/user.js @@ -1,13 +1,21 @@ import {addNotification} from '../actions/notification'; import coralApi from '../helpers/response'; +import * as actions from '../constants/auth'; import I18n from 'coral-framework/modules/i18n/i18n'; import translations from './../translations'; const lang = new I18n(translations); +const editUsernameFailure = error => ({type: actions.EDIT_USERNAME_FAILURE, error}); +const editUsernameSuccess = () => ({type: actions.EDIT_USERNAME_SUCCESS}); + export const editName = (username) => (dispatch) => { return coralApi('/account/username', {method: 'PUT', body: {username}}) .then(() => { + dispatch(editUsernameSuccess()); dispatch(addNotification('success', lang.t('successNameUpdate'))); + }) + .catch(error => { + dispatch(editUsernameFailure(lang.t(`error.${error.translation_key}`))); }); }; diff --git a/client/coral-framework/constants/auth.js b/client/coral-framework/constants/auth.js index 9a217fb43..ce5d860b4 100644 --- a/client/coral-framework/constants/auth.js +++ b/client/coral-framework/constants/auth.js @@ -11,6 +11,11 @@ export const CREATE_USERNAME = 'CREATE_USERNAME'; export const SHOW_CREATEUSERNAME_DIALOG = 'SHOW_CREATEUSERNAME_DIALOG'; export const HIDE_CREATEUSERNAME_DIALOG = 'HIDE_CREATEUSERNAME_DIALOG'; +export const EDIT_USERNAME_REQUEST = 'CREATE_USERNAME_REQUEST'; +export const EDIT_USERNAME_SUCCESS = 'CREATE_USERNAME_SUCCESS'; +export const EDIT_USERNAME_FAILURE = 'CREATE_USERNAME_FAILURE'; +export const EDIT_USERNAME = 'CREATE_USERNAME'; + export const FETCH_SIGNUP_REQUEST = 'FETCH_SIGNUP_REQUEST'; export const FETCH_SIGNUP_FAILURE = 'FETCH_SIGNUP_FAILURE'; export const FETCH_SIGNUP_SUCCESS = 'FETCH_SIGNUP_SUCCESS'; diff --git a/client/coral-framework/graphql/queries/streamQuery.graphql b/client/coral-framework/graphql/queries/streamQuery.graphql index e9f4c827c..03af1de4c 100644 --- a/client/coral-framework/graphql/queries/streamQuery.graphql +++ b/client/coral-framework/graphql/queries/streamQuery.graphql @@ -29,6 +29,7 @@ query AssetQuery($asset_id: ID, $asset_url: String!, $comment_id: ID!, $has_comm requireEmailConfirmation } commentCount + totalCommentCount comments(limit: 10) { ...commentView replyCount diff --git a/client/coral-framework/translations.json b/client/coral-framework/translations.json index b327a7097..f9038aba7 100644 --- a/client/coral-framework/translations.json +++ b/client/coral-framework/translations.json @@ -1,5 +1,6 @@ { "en": { + "MY_COMMENTS": "My Comments", "profile": "Profile", "successUpdateSettings": "The changes you have made have been applied to the comment stream on this article", "successNameUpdate": "Your username has been updated", @@ -15,7 +16,7 @@ "viewReply": "view reply", "viewAllRepliesInitial": "view all {0} replies", "viewAllReplies": "view {0} replies", - "newCount": "View {0} more {1}", + "newCount": "View {0} new {1}", "comment": "comment", "comments": "comments", "error": { @@ -40,13 +41,15 @@ } }, "es": { - "profile": "Perfil", + "profile": "Pérfil", + "MY_COMMENTS": "Mis Comentarios", + "profile": "Pérfil", "successUpdateSettings": "La configuración de este articulo fue actualizada", - "successBioUpdate": "Tu bio fue actualizada", + "successBioUpdate": "Tu biografia fue actualizada", "contentNotAvailable": "El contenido no se encuentra disponible", - "bannedAccountMsg": "Tu cuenta se encuentra suspendida. Esto significa que no puedes dar Like, Marcar o escribir commentarios.", + "bannedAccountMsg": "Tu cuenta se encuentra suspendida. Esto significa que no puedes gustar, marcar o escribir commentarios.", "editNameMsg": "", - "viewMoreComments": "Var commentarios más", + "viewMoreComments": "Ver commentarios más", "viewReply": "ver respuesta", "viewAllRepliesInitial": "ver todas las {0} respuestas", "viewAllReplies": "ver {0} respuestas", @@ -54,22 +57,22 @@ "comment": "commentario", "comments": "commentarios", "error": { - "emailNotVerified": "Dirección de correo electrónico {0} no verificada.", - "email": "No es un email válido", + "emailNotVerified": "E-mail {0} no verificado.", + "email": "No es un e-mail válido", "password": "La contraseña debe tener por lo menos 8 caracteres", "username": "Los nombres pueden contener letras, números y _", "organizationName": "El nombre de la organización debe contener letras y/o números.", "confirmPassword": "Las contraseñas no coinciden", - "emailPasswordError": "Email y/o contraseña incorrecta.", - "EMAIL_REQUIRED": "Se requiere una dirección de correo electrónico", + "emailPasswordError": "E-mail y/o contraseña incorrecta.", + "EMAIL_REQUIRED": "Se requiere un e-mail", "PASSWORD_REQUIRED": "Debe ingresar una contraseña", "PASSWORD_LENGTH": "La contraseña es muy corta", - "EMAIL_IN_USE": "La dirección de correo electrónico se encuentra en uso", - "EMAIL_USERNAME_IN_USE": "Correo o Nombre en uso.", + "EMAIL_IN_USE": "El e-mail se encuentra en uso", + "EMAIL_USERNAME_IN_USE": "E-mail o Nombre en uso.", "USERNAME_IN_USE": "Nombre en uso.", "USERNAME_REQUIRED": "Debe ingresar un nombre", "NO_SPECIAL_CHARACTERS": "Los nombres pueden contener letras, números y _", - "PROFANITY_ERROR": "Los nombres no pueden contener blasfemias. Por favor contacte al administrador si cree que esto es un error", + "PROFANITY_ERROR": "Los nombres no pueden contener blasfemias. Por favor contacte al o la administradora si cree que esto es un error", "NOT_AUTHORIZED": "Acción no autorizada.", "EDIT_USERNAME_NOT_AUTHORIZED": "No tiene permiso para editar el nombre de usuario." } diff --git a/client/coral-plugin-best/translations.json b/client/coral-plugin-best/translations.json index c7dd42be8..6eb4b0572 100644 --- a/client/coral-plugin-best/translations.json +++ b/client/coral-plugin-best/translations.json @@ -5,8 +5,8 @@ "commentIsBest": "This comment is one of the best" }, "es": { - "like": "Establecer como mejor", - "liked": "Desarmado como mejor", + "setBest": "Etiquetar como el mejor", + "unsetBest": "Desetiquetar como el mejor", "commentIsBest": "Este comentario es uno de los mejores" } } diff --git a/client/coral-plugin-commentbox/translations.json b/client/coral-plugin-commentbox/translations.json index 0f77fc334..8ad8b1813 100644 --- a/client/coral-plugin-commentbox/translations.json +++ b/client/coral-plugin-commentbox/translations.json @@ -13,12 +13,12 @@ "es": { "post": "Publicar", "cancel": "Cancelar", - "reply": "Respuesta", - "comment": "Escribe un Comentario", + "reply": "Responder", + "comment": "Publicar un Comentario", "name": "Nombre", "comment-post-notif": "Tu comentario ha sido publicado.", - "comment-post-notif-premod": "Gracias por comentar. Nuestro equipo de moderación va a revisarlo muy pronto.", - "comment-post-banned-word": "Tu comentario contiene una o más palabras que no estan permitidasen nuestro espacio, por lo que no será publicado. Si crees que es un error, por favor contacta a nuestro equipo de moderación.", + "comment-post-notif-premod": "Gracias por el comentario. Nuestro equipo de moderación va a revisarlo muy pronto.", + "comment-post-banned-word": "Tu comentario contiene una o más palabras que no estan permitidas en nuestro espacio, por lo que no será publicado. Si crees que es un error, por favor contacta a nuestro equipo de moderación.", "characters-remaining": "carácteres restantes" } } diff --git a/client/coral-plugin-flags/translations.json b/client/coral-plugin-flags/translations.json index 255e13f3c..65986e285 100644 --- a/client/coral-plugin-flags/translations.json +++ b/client/coral-plugin-flags/translations.json @@ -25,28 +25,28 @@ "other": "Other" }, "es": { - "report": "Informe", - "reported": "Informado", - "report-notif": "Gracias por marcar este comentario. Nuestro equipo de moderación ha sido notificado y muy pronto lo va a revisar.", - "report-notif-remove": "Tu marca ha sido eliminada.", + "report": "Reportar", + "reported": "Reportado", + "report-notif": "Gracias por reportar este comentario. Nuestro equipo de moderación ha sido notificado y muy pronto lo va a revisar.", + "report-notif-remove": "Tu reporte ha sido eliminada.", "step-1-header": "Reportar un problema", - "step-2-header": "Ayudanos a entender", + "step-2-header": "Ayudanos a comprender", "step-3-header": "Gracias por tu participación", - "flag-username": "Marcar el nombre de usuario", - "flag-comment": "Marcar el comentario", + "flag-username": "Reportar el nombre de usuario", + "flag-comment": "Reportar el comentario", "continue": "Continuar", "done": "hecho", "no-agree-comment": "No estoy de acuerdo con este comentario", "comment-offensive": "Este comentario es ofensivo", "personal-info": "Este comentario muestra información personal", "username-offensive": "Este nombre de usuario es ofensivo", - "no-like-username": "No me gusta ese nombre de usuario", - "bio-offensive": "Esta bio es ofensiva", - "no-like-bio": "No me gusta esta bio", - "user-impersonating": "Este usario suplanta a alguien", - "marketing": "Esto parece una publicidad/marketing", - "thank-you": "Nos interesa tu protección y comentarios. Un moderador va a mirar tu marca.", - "flag-reason": "Razón por la que marcar (Opcional)", + "no-like-username": "No me gusta este nombre de usuario", + "bio-offensive": "Esta biografia es ofensiva", + "no-like-bio": "No me gusta esta biografia", + "user-impersonating": "Este usuario suplanta a alguien", + "marketing": "Esto parece una propaganda", + "thank-you": "Valoramos tanto tu seguridad en este espacio como tus comentarios. Un o una moderadora van a leer tu reporte.", + "flag-reason": "Razón por la que hacer este reporte (Opcional)", "other": "Otro" } } diff --git a/client/coral-plugin-history/Comment.css b/client/coral-plugin-history/Comment.css index f54b0ad29..2c0dee094 100644 --- a/client/coral-plugin-history/Comment.css +++ b/client/coral-plugin-history/Comment.css @@ -1,16 +1,74 @@ +@custom-media --big-viewport (min-width: 780px); + .myComment { border-bottom: 1px solid lightgrey; + display: flex; + align-items: baseline; + justify-content: space-between; } .myComment:last-child { - border-bottom: none; + border-bottom: solid 1px #EBEBEB; } .assetURL { font-size: 16px; color: black; + text-decoration: none; + font-weight: bold; } .commentBody { } + +.sidebar { + ul { + min-width: 136px; + } + + li { + margin-bottom: 10px; + + &:nth-child(1) { + color: #5394D7; + } + + &:nth-child(2) { + color: #909090; + } + + + i { + margin-right: 5px; + font-size: 15px; + vertical-align: bottom; + } + + a:hover { + cursor: pointer; + } + } +} + +@custom-media --mobile-viewport (max-width: 480px); + +@media (--mobile-viewport) { + .myComment { + flex-direction: column; + } + + .sidebar ul { + display: flex; + li { + margin-right: 20px; + } + } +} + +.pubdate { + display: inline-block; + font-size: inherit; + margin: inherit; + color: inherit; +} diff --git a/client/coral-plugin-history/Comment.js b/client/coral-plugin-history/Comment.js index 00dcc40c7..617d0a04f 100644 --- a/client/coral-plugin-history/Comment.js +++ b/client/coral-plugin-history/Comment.js @@ -1,13 +1,42 @@ import React, {PropTypes} from 'react'; +import {Icon} from '../coral-ui'; import styles from './Comment.css'; +import PubDate from '../coral-plugin-pubdate/PubDate'; +import Content from '../coral-plugin-commentcontent/CommentContent'; const Comment = props => { return ( ); }; diff --git a/client/coral-plugin-moderation/translations.json b/client/coral-plugin-moderation/translations.json index 331c6e392..6bbe2f9e1 100644 --- a/client/coral-plugin-moderation/translations.json +++ b/client/coral-plugin-moderation/translations.json @@ -3,6 +3,6 @@ "MODERATE_THIS_STREAM": "Moderate this stream" }, "es": { - "MODERATE_THIS_STREAM": "Modera este stream" + "MODERATE_THIS_STREAM": "Modera este hilo de comentarios" } } diff --git a/client/coral-settings/translations.json b/client/coral-settings/translations.json index 945d71b87..9ed95f6fc 100644 --- a/client/coral-settings/translations.json +++ b/client/coral-settings/translations.json @@ -11,12 +11,12 @@ }, "es":{ "profile": "Perfil", - "userNoComment": "No has dejado áun ningún comentario. ¡Unete a la conversación!", + "userNoComment": "No has dejado aún ningún comentario. ¡Únete a la conversación!", "allComments": "Todos los comentarios", "profileSettings": "Configuración del perfil", "myCommentHistory": "Mi historial de comentarios", "signIn": "Entrar", "toAccess": "para acceder a al perfil", - "fromSettingsPage": "Desde la peagina de configuración puede ver su historia de comentarios." + "fromSettingsPage": "Desde la página de configuración puedes ver tu historia de comentarios." } } diff --git a/client/coral-sign-in/translations.js b/client/coral-sign-in/translations.js deleted file mode 100644 index f6934bbad..000000000 --- a/client/coral-sign-in/translations.js +++ /dev/null @@ -1,102 +0,0 @@ -export default { - en: { - 'signIn': { - emailVerifyCTA: 'Please verify your email address.', - requestNewVerifyEmail: 'Request another email:', - verifyEmail: 'Thank you for creating an account! We sent an email to the address you provided to verify your account.', - verifyEmail2: 'You must verify your account before engaging with the community.', - notYou: 'Not you?', - loggedInAs: 'Logged in as', - facebookSignIn: 'Sign in with Facebook', - facebookSignUp: 'Sign up with Facebook', - logout: 'Logout', - signIn: 'Sign in to join the conversation', - or: 'Or', - email: 'E-mail Address', - password: 'Password', - forgotYourPass: 'Forgot your password?', - needAnAccount: 'Need an account?', - register: 'Register', - signUp: 'Sign Up', - confirmPassword: 'Confirm Password', - username: 'Username', - alreadyHaveAnAccount: 'Already have an account?', - recoverPassword: 'Recover password', - emailInUse: 'Email address already in use', - emailORusernameInUse: 'Email address or Username already in use', - requiredField: 'This field is required', - passwordsDontMatch: 'Passwords don\'t match.', - specialCharacters: 'Usernames can contain letters, numbers and _ only', - checkTheForm: 'Invalid Form. Please, check the fields' - }, - 'createdisplay': { - writeyourusername: 'Edit your username', - yourusername: 'Your username appears on every comment you post.', - ifyoudontchangeyourname: 'If you don\'t change your username at this step, your Facebook display name will appear alongside of all your comments.', - username: 'Username', - continue: 'Continue with the same Facebook username', - save: 'Save', - fakecommentdate: '1 minute ago', - fakecommentbody: 'This is an example comment. Readers can share their thoughts and opinions with newsrooms in the comments section.', - requiredField: 'Required field', - errorCreate: 'Error when changing username', - checkTheForm: 'Invalid Form. Please, check the fields', - specialCharacters: 'Usernames can contain letters, numbers and _ only' - }, - 'permalink': { - permalink: 'Link' - }, - 'report': 'Report', - 'like': 'Like', - }, - es: { - 'signIn': { - emailVerifyCTA: 'Por favor verifique su correo electronico.', - requestNewVerifyEmail: 'Enviar otro correo:', - verifyEmail: '¡Gracias por crear una cuenta! Le enviamos un correo a la dirección que dio para verificar su cuenta.', - verifyEmail2: 'Debe verificarla antes de poder involucrarse en la comunidad.', - notYou: 'No eres tu?', - loggedInAs: 'Entraste como', - facebookSignIn: 'Entrar con Facebook', - facebookSignUp: 'Regístrate con Facebook', - logout: 'Salir', - signIn: 'Entrar para Unirte a la Conversación', - or: 'o', - email: 'E-mail', - password: 'Contraseña', - forgotYourPass: 'Has olvidado tu contraseña?', - needAnAccount: 'Necesitas una cuenta?', - register: 'Regístrate', - signUp: 'Registro', - confirmPassword: 'Confirmar Contraseña', - username: 'Nombre', - alreadyHaveAnAccount: 'Ya tienes una cuenta?', - recoverPassword: 'Recuperar contraseña', - emailInUse: 'Este email se encuentra en uso', - emailORusernameInUse: 'Este email ó nombre se encuentran en uso', - requiredField: 'Este campo es requerido', - passwordsDontMatch: 'Las contraseñas no coinciden', - specialCharacters: 'Los nombres pueden contener letras, números y _', - checkTheForm: 'Formulario Inválido. Por favor, completa los campos' - }, - 'createdisplay': { - writeyourusername: 'Edita tu nombre', - yourusername: 'Tu nombre aparece en cada comentario que publiques.', - ifyoudontchangeyourname: 'Si no modificas tu nombre de usuario en este paso, tu nombre de Facebook aparecera al lado de cada comentario que publiques.', - username: 'Nombre', - continue: 'Continuar con nombre de Facebook', - save: 'Guardar', - fakecommentdate: 'hace un minuto', - fakecommentbody: 'Este es un comentario de ejemplo. Las lectoras pueden compartir sus ideas y opiniones con los periodistas en la sección de comentarios.', - requiredField: 'Campo necesario', - errorCreate: 'Hubo un error al cambiar el nombre de usuario', - checkTheForm: 'Formulario Invalido. Por favor, verifica los campos', - specialCharacters: 'Sólo pueden contener letras, números y _' - }, - 'permalink': { - permalink: 'Enlace' - }, - 'report': 'Informe', - 'like': 'Me gusta', - } -}; diff --git a/client/coral-sign-in/translations.json b/client/coral-sign-in/translations.json new file mode 100644 index 000000000..824888cca --- /dev/null +++ b/client/coral-sign-in/translations.json @@ -0,0 +1,102 @@ +{ + "en": { + "signIn": { + "emailVerifyCTA": "Please verify your email address.", + "requestNewVerifyEmail": "Request another email:", + "verifyEmail": "Thank you for creating an account! We sent an email to the address you provided to verify your account.", + "verifyEmail2": "You must verify your account before engaging with the community.", + "notYou": "Not you?", + "loggedInAs": "Logged in as", + "facebookSignIn": "Sign in with Facebook", + "facebookSignUp": "Sign up with Facebook", + "logout": "Logout", + "signIn": "Sign in to join the conversation", + "or": "Or", + "email": "E-mail Address", + "password": "Password", + "forgotYourPass": "Forgot your password?", + "needAnAccount": "Need an account?", + "register": "Register", + "signUp": "Sign Up", + "confirmPassword": "Confirm Password", + "username": "Username", + "alreadyHaveAnAccount": "Already have an account?", + "recoverPassword": "Recover password", + "emailInUse": "Email address already in use", + "emailORusernameInUse": "Email address or Username already in use", + "requiredField": "This field is required", + "passwordsDontMatch": "Passwords don\"t match.", + "specialCharacters": "Usernames can contain letters, numbers and _ only", + "checkTheForm": "Invalid Form. Please, check the fields" + }, + "createdisplay": { + "writeyourusername": "Edit your username", + "yourusername": "Your username appears on every comment you post.", + "ifyoudontchangeyourname": "If you don\"t change your username at this step, your Facebook display name will appear alongside of all your comments.", + "username": "Username", + "continue": "Continue with the same Facebook username", + "save": "Save", + "fakecommentdate": "1 minute ago", + "fakecommentbody": "This is an example comment. Readers can share their thoughts and opinions with newsrooms in the comments section.", + "requiredField": "Required field", + "errorCreate": "Error when changing username", + "checkTheForm": "Invalid Form. Please, check the fields", + "specialCharacters": "Usernames can contain letters, numbers and _ only" + }, + "permalink": { + "permalink": "Link" + }, + "report": "Report", + "like": "Like" + }, + "es": { + "signIn": { + "emailVerifyCTA": "Por favor verifique su e-mail.", + "requestNewVerifyEmail": "Enviar otro correo:", + "verifyEmail": "¡Gracias por crear una cuenta! Le enviamos un correo a la dirección que dio para verificar su cuenta.", + "verifyEmail2": "Debe verificarla antes de poder involucrarse en la comunidad.", + "notYou": "¿No eres tu?", + "loggedInAs": "Entraste como", + "facebookSignIn": "Entrar con Facebook", + "facebookSignUp": "Regístrate con Facebook", + "logout": "Salir", + "signIn": "Entrar para Unirte a la Conversación", + "or": "o", + "email": "E-mail", + "password": "Contraseña", + "forgotYourPass": "¿Has olvidado tu contraseña?", + "needAnAccount": "¿Necesitas una cuenta?", + "register": "Regístrate", + "signUp": "Registro", + "confirmPassword": "Confirmar Contraseña", + "username": "Nombre", + "alreadyHaveAnAccount": "¿Ya tienes una cuenta?", + "recoverPassword": "Recuperar contraseña", + "emailInUse": "Este e-mail se encuentra en uso", + "emailORusernameInUse": "Este e-mail ó nombre de usuario se encuentran en uso", + "requiredField": "Este campo es requerido", + "passwordsDontMatch": "Las contraseñas no coinciden", + "specialCharacters": "Los nombres pueden contener letras, números y _", + "checkTheForm": "Formulario Inválido. Por favor, completa los campos" + }, + "createdisplay": { + "writeyourusername": "Edita tu nombre", + "yourusername": "Tu nombre aparece en cada comentario que publiques.", + "ifyoudontchangeyourname": "Si no modificas tu nombre de usuario en este paso, tu nombre de Facebook aparecera al lado de cada comentario que publiques.", + "username": "Nombre", + "continue": "Continuar con nombre de Facebook", + "save": "Guardar", + "fakecommentdate": "hace un minuto", + "fakecommentbody": "Este es un comentario de ejemplo. Las lectoras pueden compartir sus ideas y opiniones con los periodistas en la sección de comentarios.", + "requiredField": "Campo necesario", + "errorCreate": "Hubo un error al cambiar el nombre de usuario", + "checkTheForm": "Formulario Inválido. Por favor, verifica los campos", + "specialCharacters": "Sólo pueden contener letras, números y _" + }, + "permalink": { + "permalink": "Enlace" + }, + "report": "Marcar", + "like": "Me gusta" + } +} diff --git a/client/coral-ui/components/TabBar.css b/client/coral-ui/components/TabBar.css index 33a4c6d8b..b5d44d570 100644 --- a/client/coral-ui/components/TabBar.css +++ b/client/coral-ui/components/TabBar.css @@ -19,7 +19,7 @@ } .base li:hover { - background: #f3f3f3; + background: #d5d5d5; cursor: pointer; } diff --git a/graph/resolvers/root_query.js b/graph/resolvers/root_query.js index ce11fcae9..6f4151ff6 100644 --- a/graph/resolvers/root_query.js +++ b/graph/resolvers/root_query.js @@ -103,7 +103,7 @@ const RootQuery = { .then((ids) => { // Perform the query using the available resolver. - return Users.getByQuery({ids, limit, cursor, sort}); + return Users.getByQuery({ids, limit, cursor, sort}).find({status: 'PENDING'}); }); } diff --git a/models/setting.js b/models/setting.js index ac54584a4..e63fa8f3e 100644 --- a/models/setting.js +++ b/models/setting.js @@ -47,6 +47,10 @@ const SettingSchema = new Schema({ organizationName: { type: String }, + autoCloseStream: { + type: Boolean, + default: false + }, closedTimeout: { type: Number, diff --git a/package.json b/package.json index 19db0b7e7..6fdf4560a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "talk", - "version": "1.1.0", + "version": "1.4.0", "description": "A commenting platform from The Coral Project. https://coralproject.net", "main": "app.js", "scripts": { diff --git a/routes/admin/index.js b/routes/admin/index.js index d250ea32a..1a9769591 100644 --- a/routes/admin/index.js +++ b/routes/admin/index.js @@ -12,7 +12,7 @@ router.get('/password-reset', (req, res) => { // TODO: store the redirect uri in the token or something fancy. // admins and regular users should probably be redirected to different places. - res.render('admin/password-reset', {redirectUri: process.env.TALK_ROOT_URL}); + res.render('admin/password-reset'); }); router.get('*', (req, res) => { diff --git a/routes/api/account/index.js b/routes/api/account/index.js index 44b4b3953..e1c73d638 100644 --- a/routes/api/account/index.js +++ b/routes/api/account/index.js @@ -41,14 +41,14 @@ router.post('/email/verify', (req, res, next) => { * if it does, create a JWT and send an email */ router.post('/password/reset', (req, res, next) => { - const {email} = req.body; + const {email, loc} = req.body; if (!email) { return next('you must submit an email when requesting a password.'); } UsersService - .createPasswordResetToken(email) + .createPasswordResetToken(email, loc) .then((token) => { // Check to see if the token isn't defined. @@ -101,11 +101,11 @@ router.put('/password/reset', (req, res, next) => { UsersService .verifyPasswordResetToken(token) - .then((user) => { - return UsersService.changePassword(user.id, password); + .then(([user, loc]) => { + return Promise.all([UsersService.changePassword(user.id, password), loc]); }) - .then(() => { - res.status(204).end(); + .then(([ , loc]) => { + res.json({redirect: loc}); }) .catch(() => { next(authorization.ErrNotAuthorized); diff --git a/services/assets.js b/services/assets.js index f8f795263..0aa4219da 100644 --- a/services/assets.js +++ b/services/assets.js @@ -57,11 +57,21 @@ module.exports = class AssetsService { static findOrCreateByUrl(url) { // Check the URL to confirm that is in the domain whitelist - return domainlist.urlCheck(url).then((whitelisted) => { + return Promise.all([ + domainlist.urlCheck(url), + SettingsService.retrieve() + ]).then(([whitelisted, settings]) => { + + const update = {$setOnInsert: {url}}; + + if (settings.autoCloseStream) { + update.$setOnInsert.closedAt = new Date(Date.now() + settings.closedTimeout * 1000); + } + if (!whitelisted) { return Promise.reject(errors.ErrInvalidAssetURL); } else { - return AssetModel.findOneAndUpdate({url}, {url}, { + return AssetModel.findOneAndUpdate({url}, update, { // Ensure that if it's new, we return the new object created. new: true, diff --git a/services/email/email-confirm.ejs b/services/email/email-confirm.html.ejs similarity index 100% rename from services/email/email-confirm.ejs rename to services/email/email-confirm.html.ejs diff --git a/services/email/notification.ejs b/services/email/notification.html.ejs similarity index 100% rename from services/email/notification.ejs rename to services/email/notification.html.ejs diff --git a/services/email/password-reset.ejs b/services/email/password-reset.html.ejs similarity index 100% rename from services/email/password-reset.ejs rename to services/email/password-reset.html.ejs diff --git a/services/mailer.js b/services/mailer.js index 2928570ad..35741ee9f 100644 --- a/services/mailer.js +++ b/services/mailer.js @@ -17,16 +17,41 @@ if (smtpRequiredProps.some(prop => !process.env[prop])) { } // load all the templates as strings -const templateStrings = {}; -fs.readdir(path.join(__dirname, 'email'), (err, files) => { - if (err) { - throw err; +const templates = { + data: {} +}; + +// load the temlates per request during development +templates.render = (name, format = 'txt', context) => new Promise((resolve, reject) => { + + // If we are in production mode, check the view cache. + if (process.env.NODE_ENV === 'production') { + if (name in templates.data && format in templates.data[name]) { + let view = templates.data[name][format]; + + return resolve(view(context)); + } } - files.forEach(file => { - fs.readFile(path.join(__dirname, 'email', file), 'utf8', (err, data) => { - templateStrings[file] = _.template(data); - }); + const filename = path.join(__dirname, 'email', [name, format, 'ejs'].join('.')); + + fs.readFile(filename, (err, file) => { + if (err) { + return reject(err); + } + + let view = _.template(file); + + // If we are in production mode, fill the view cache. + if (process.env.NODE_ENV === 'production') { + if (!(name in templates.data)) { + templates.data[name] = {}; + } + + templates.data[name][format] = view; + } + + return resolve(view(context)); }); }); @@ -70,10 +95,10 @@ const mailer = module.exports = { return Promise.all([ // Render the HTML version of the email. - templateStrings[`${template}.ejs`](locals), + templates.render(template, 'html', locals), // Render the TEXT version of the email. - templateStrings[`${template}.txt.ejs`](locals) + templates.render(template, 'txt', locals) ]) .then(([html, text]) => { diff --git a/services/users.js b/services/users.js index 4e1196252..1332ff7f0 100644 --- a/services/users.js +++ b/services/users.js @@ -1,4 +1,5 @@ const bcrypt = require('bcrypt'); +const url = require('url'); const jwt = require('jsonwebtoken'); const Wordlist = require('./wordlist'); @@ -16,6 +17,7 @@ const USER_ROLES = require('../models/user').USER_ROLES; const RECAPTCHA_WINDOW_SECONDS = 60 * 10; // 10 minutes. const RECAPTCHA_INCORRECT_TRIGGER = 5; // after 3 incorrect attempts, recaptcha will be required. +const SettingsService = require('./settings'); const ActionsService = require('./actions'); const MailerService = require('./mailer'); @@ -456,7 +458,7 @@ module.exports = class UsersService { * @param {Function} done callback after the operation is complete */ static suspendUser(id, message) { - return UserModel.update({ + return UserModel.findOneAndUpdate({ id }, { $set: { @@ -464,31 +466,27 @@ module.exports = class UsersService { canEditName: true } }) - .then(() => { - return UsersService.findById(id) - .then((user) => { - if (message) { - let localProfile = user.profiles.find((profile) => profile.provider === 'local'); + .then((user) => { + if (message) { + let localProfile = user.profiles.find((profile) => profile.provider === 'local'); - if (localProfile) { - const options = - { - template: 'suspension', // needed to know which template to render! - locals: { // specifies the template locals. - body: message - }, - subject: 'Email Suspension', - to: localProfile.id // This only works if the user has registered via e-mail. - // We may want a standard way to access a user's e-mail address in the future - }; + if (localProfile) { + const options = + { + template: 'suspension', // needed to know which template to render! + locals: { // specifies the template locals. + body: message + }, + subject: 'Email Suspension', + to: localProfile.id // This only works if the user has registered via e-mail. + // We may want a standard way to access a user's e-mail address in the future + }; - return MailerService.sendSimple(options); - } else { - return Promise.reject(errors.ErrMissingEmail); - } + return MailerService.sendSimple(options); + } else { + return Promise.reject(errors.ErrMissingEmail); } - }); - + } }); } @@ -524,15 +522,18 @@ module.exports = class UsersService { * Creates a JWT from a user email. Only works for local accounts. * @param {String} email of the local user */ - static createPasswordResetToken(email) { + static createPasswordResetToken(email, loc) { if (!email || typeof email !== 'string') { return Promise.reject('email is required when creating a JWT for resetting passord'); } email = email.toLowerCase(); - return UserModel.findOne({profiles: {$elemMatch: {id: email}}}) - .then((user) => { + return Promise.all([ + UserModel.findOne({profiles: {$elemMatch: {id: email}}}), + SettingsService.retrieve() + ]) + .then(([user, settings]) => { if (!user) { // Since we don't want to reveal that the email does/doesn't exist @@ -541,9 +542,21 @@ module.exports = class UsersService { return; } + let redirectDomain; + try { + redirectDomain = url.parse(loc).hostname; + } catch (e) { + return Promise.reject('redirect location is invalid'); + } + + if (settings.domains.whitelist.indexOf(redirectDomain) === -1) { + return Promise.reject('redirect location is not on the list of acceptable domains'); + } + const payload = { jti: uuid.v4(), email, + loc, userId: user.id, version: user.__v }; @@ -588,7 +601,9 @@ module.exports = class UsersService { }) // TODO: add search by __v as well - .then((decoded) => UsersService.findById(decoded.userId)); + .then((decoded) => { + return Promise.all([UsersService.findById(decoded.userId), decoded.loc]); + }); } /** diff --git a/services/wordlist.js b/services/wordlist.js index 8dc16fba2..2ae8ed90c 100644 --- a/services/wordlist.js +++ b/services/wordlist.js @@ -2,9 +2,13 @@ const debug = require('debug')('talk:services:wordlist'); const _ = require('lodash'); const natural = require('natural'); const tokenizer = new natural.WordTokenizer(); +const nameTokenizer = new natural.RegexpTokenizer({pattern: /\_/}); const SettingsService = require('./settings'); const Errors = require('../errors'); +// REGEX to prevent emoji's from entering the wordlist. +const EMOJI_REGEX = /(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe23\u20d0-\u20f0]|\ud83c[\udffb-\udfff])?)*/; + /** * The root wordlist object. * @type {Object} @@ -58,7 +62,27 @@ class Wordlist { * @return {Array} the parsed list */ static parseList(list) { - return _.uniq(list.map((word) => tokenizer.tokenize(word.toLowerCase()))); + return _.uniq(list.filter((word) => { + if (EMOJI_REGEX.test(word)) { + return false; + } + + return true; + }) + .map((word) => { + if (word.length === 1) { + return [word]; + } + + return tokenizer.tokenize(word.toLowerCase()); + }) + .filter((tokens) => { + if (tokens.length === 0) { + return false; + } + + return true; + })); } /** @@ -66,11 +90,11 @@ class Wordlist { * @param {String} phrase value to check for blockwords. * @return {Boolean} true if a blockword is found, false otherwise. */ - match(list, phrase) { + match(list, phrase, tk = tokenizer) { // Lowercase the word to ensure that we don't miss a match due to // capitalization. - let lowerPhraseWords = tokenizer.tokenize(phrase.toLowerCase()); + let lowerPhraseWords = tk.tokenize(phrase.toLowerCase()); // This will return true in the event that at least one blockword is found // in the phrase. @@ -199,28 +223,24 @@ class Wordlist { } /** - * check potential username for banned words, special characters + * check potential username for banned words */ static usernameCheck(username) { const wl = new Wordlist(); - return wl.load() + return wl + .load() .then(() => { - username = username.replace(/_/g, ''); - - // test each word, and fail if we find a match - const hasBadWords = wl.lists.banned.some(phrase => { - return username.indexOf(phrase.join('')) !== -1; - }); - - if (hasBadWords) { - throw Errors.ErrContainsProfanity; - } else { - return Promise.resolve(username); + if (!wl.checkName(wl.lists.banned, username)) { + return Errors.ErrContainsProfanity; } }); } + checkName(list, name) { + return !this.match(list, name, nameTokenizer); + } + /** * Connect middleware for scanning request bodies for wordlisted words and * attaching a ErrContainsProfanity to the req.wordlisted parameter, otherwise diff --git a/test/client/.babelrc b/test/client/.babelrc new file mode 100644 index 000000000..9bd819c32 --- /dev/null +++ b/test/client/.babelrc @@ -0,0 +1,3 @@ +{ + "extends": "../../client/.babelrc" +} diff --git a/test/client/coral-plugin-history/Comment.spec.js b/test/client/coral-plugin-history/Comment.spec.js deleted file mode 100644 index 6d69d54cd..000000000 --- a/test/client/coral-plugin-history/Comment.spec.js +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import {shallow, mount} from 'enzyme'; -import {expect} from 'chai'; -import Comment from '../../../client/coral-plugin-history/Comment'; - -describe('coral-plugin-history/Comment', () => { - let render; - const comment = {body: 'this is a comment', id: '123'}; - const asset = {url: 'https://google.com'}; - - beforeEach(() => { - render = shallow({}}/>); - }); - - it('should render the provided comment body', () => { - const wrapper = mount({}}/>); - expect(wrapper.find('.myCommentBody')).to.have.length(1); - expect(wrapper.find('.myCommentBody').text()).to.equal('this is a comment'); - }); - - it('should render the asset url as a link', () => { - const wrapper = mount({}}/>); - expect(wrapper.find('.myCommentAnchor')).to.have.length(1); - expect(wrapper.find('.myCommentAnchor').text()).to.equal('https://google.com'); - }); - - it('should render the comment with styles', () => { - expect(render.props().style).to.be.defined; - }); -}); diff --git a/test/client/coral-plugin-history/CommentHistory.spec.js b/test/client/coral-plugin-history/CommentHistory.spec.js deleted file mode 100644 index 671a50137..000000000 --- a/test/client/coral-plugin-history/CommentHistory.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -import React from 'react'; -import {shallow, mount} from 'enzyme'; -import {expect} from 'chai'; -import CommentHistory from '../../../client/coral-plugin-history/CommentHistory'; - -describe('coral-plugin-history/CommentHistory', () => { - let render; - const comments = [{body: 'a comment or something', 'status_history':[{'type':'premod', 'created_at':'2016-12-09T01:40:53.327Z', 'assigned_by':null}, {'created_at':'2016-12-09T22:52:44.888Z', 'type':'accepted', 'assigned_by':'92256159-1164-4f66-9970-c7f23de7e461'}], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-09T01:40:53.360Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'accepted', '__v':0, 'updated_at':'2016-12-09T22:52:44.893Z', 'id':'3962c2ea-4ec4-42e4-b9bd-c571ff30f56b'}, {'body':'another comment', 'status_history':[{'type':'premod', 'created_at':'2016-12-09T22:53:43.148Z', 'assigned_by':null}], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-09T22:53:43.158Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'premod', '__v':0, 'updated_at':'2016-12-09T22:53:43.158Z', 'id':'b51e27af-bcfd-4932-91be-e3f01a4802e6'}, {'body':'can I comment?', 'status_history':[{'type':'premod', 'created_at':'2016-12-13T23:23:47.123Z', 'assigned_by':null}, {'created_at':'2016-12-13T23:23:58.487Z', 'type':'accepted', 'assigned_by':'92256159-1164-4f66-9970-c7f23de7e461'}], 'asset_id':'cef81015-1b53-4d70-b9af-6eca680f22fc', 'created_at':'2016-12-13T23:23:47.131Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'accepted', '__v':0, 'updated_at':'2016-12-13T23:23:58.493Z', 'id':'dc9d7be1-b911-4dc3-8e1e-400e8b8d110e'}, {'body':'pre-mod comment', 'status_history':[{'type':'premod', 'created_at':'2016-12-08T21:34:56.994Z', 'assigned_by':null}, {'created_at':'2016-12-08T21:38:04.961Z', 'type':'rejected', 'assigned_by':'92256159-1164-4f66-9970-c7f23de7e461'}], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-08T21:34:56.997Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'rejected', '__v':0, 'updated_at':'2016-12-08T21:38:04.965Z', 'id':'6f02af16-a8f8-4ead-80ea-0d48824eb74d'}, {'body':'a flagged commetn', 'status_history':[{'type':'premod', 'created_at':'2016-12-08T21:38:26.342Z', 'assigned_by':null}, {'created_at':'2016-12-09T23:47:27.009Z', 'type':'accepted', 'assigned_by':'92256159-1164-4f66-9970-c7f23de7e461'}], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-08T21:38:26.344Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'accepted', '__v':0, 'updated_at':'2016-12-09T23:47:27.018Z', 'id':'784c5f91-36b9-4bda-b4ca-a114cef2c9f0'}, {'body':'a post mod comment', 'status_history':[{'type':'premod', 'created_at':'2016-12-08T22:19:05.870Z', 'assigned_by':null}, {'created_at':'2016-12-09T23:26:41.427Z', 'type':'accepted', 'assigned_by':'92256159-1164-4f66-9970-c7f23de7e461'}], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-08T22:19:05.874Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':'accepted', '__v':0, 'updated_at':'2016-12-09T23:26:41.450Z', 'id':'e8b86039-f850-4e53-bd9d-f8c9186a9637'}, {'body':'an actual post-mod comment here', 'status_history':[], 'asset_id':'96fddf96-7c83-4008-80ad-50091997d006', 'created_at':'2016-12-08T22:20:11.147Z', 'author_id':'92256159-1164-4f66-9970-c7f23de7e461', 'status':null, '__v':0, 'updated_at':'2016-12-08T22:20:11.147Z', 'id':'cff1a318-50c6-431e-9a63-de7a7b7136bf'}]; - const asset = { - 'settings': null, - 'created_at':'2016-12-06T21:36:09.302Z', - 'url':'localhost:3000/', - 'scraped':null, - 'status':'open', - 'updated_at':'2016-12-08T02:11:15.943Z', - '_id':'58472f499e775a38f23d5da0', - 'type':'article', - 'closedMessage':null, - 'id':'7302e637-f884-47c0-9723-02cc10a18617', - 'closedAt':null - }; - - comments.forEach((comment) => { - comment.asset = asset; - }); - - beforeEach(() => { - render = shallow({}}/>); - }); - - it('should render Comments as children when given comments and assets', () => { - const wrapper = mount({}}/>); - expect(wrapper.find('.commentHistory__list').children()).to.have.length(7); - }); - - it('should render with styles', () => { - expect(render.props().style).to.be.defined; - }); -}); diff --git a/test/server/services/users.js b/test/server/services/users.js index aeb62d106..22fe7ddd5 100644 --- a/test/server/services/users.js +++ b/test/server/services/users.js @@ -249,6 +249,17 @@ describe('services.UsersService', () => { done(); }); }); + + it('should not allow non-alphanumeric characters in usernames', () => { + return UsersService + .isValidUsername('hi🖕') + .then(() => { + expect(false).to.be.true; + }) + .catch((err) => { + expect(err).to.be.truthy; + }); + }); }); }); diff --git a/test/server/services/wordlist.js b/test/server/services/wordlist.js index 4a8b117ea..417844da4 100644 --- a/test/server/services/wordlist.js +++ b/test/server/services/wordlist.js @@ -9,7 +9,8 @@ describe('services.Wordlist', () => { banned: [ 'cookies', 'how to do bad things', - 'how to do really bad things' + 'how to do really bad things', + 's h i t' ], suspect: [ 'do bad things' @@ -32,9 +33,22 @@ describe('services.Wordlist', () => { }); - describe('#match', () => { + describe('#parseList', () => { + it('does not include emojis in the wordlist', () => { + let list = Wordlist.parseList([ + '🖕', + '🖕 asdf', + 'asd🖕asdf', + 'asd🖕', + ]); - const bannedList = Wordlist.parseList(wordlists.banned); + expect(list).to.have.length(0); + }); + }); + + const bannedList = Wordlist.parseList(wordlists.banned); + + describe('#match', () => { it('does match on a bad word', () => { [ @@ -62,6 +76,26 @@ describe('services.Wordlist', () => { }); + describe('#checkName', () => { + [ + 'flowers', + 'joy', + 'lots_of_candy' + ].forEach((username) => { + it(`does not match on list=banned name=${username}`, () => { + expect(wordlist.checkName(bannedList, username)).to.be.true; + }); + }); + + [ + 'cookies' + ].forEach((username) => { + it(`does match on list=banned name=${username}`, () => { + expect(wordlist.checkName(bannedList, username)).to.be.false; + }); + }); + }); + describe('#filter', () => { before(() => wordlist.upsert(wordlists)); diff --git a/views/admin.ejs b/views/admin.ejs index 36e3d15c8..947f15425 100644 --- a/views/admin.ejs +++ b/views/admin.ejs @@ -21,7 +21,7 @@ - +