diff --git a/client/coral-admin/src/actions/comments.js b/client/coral-admin/src/actions/comments.js index 3c1437de7..ac7af12fd 100644 --- a/client/coral-admin/src/actions/comments.js +++ b/client/coral-admin/src/actions/comments.js @@ -15,7 +15,7 @@ export const fetchModerationQueueComments = () => { return Promise.all([ coralApi('/queue/comments/premod'), - coralApi('/queue/users/pending'), + coralApi('/queue/users/flagged'), coralApi('/queue/comments/rejected'), coralApi('/queue/comments/flagged') ]) @@ -46,7 +46,7 @@ export const fetchPendingUsersQueue = () => { return dispatch => { dispatch({type: commentTypes.COMMENTS_MODERATION_QUEUE_FETCH_REQUEST}); - return coralApi('/queue/users/pending') + return coralApi('/queue/users/flagged') .then(addUsersCommentsActions.bind(this, dispatch)); }; }; diff --git a/client/coral-admin/src/actions/users.js b/client/coral-admin/src/actions/users.js index 44f0325d9..954d89820 100644 --- a/client/coral-admin/src/actions/users.js +++ b/client/coral-admin/src/actions/users.js @@ -21,3 +21,11 @@ export const sendNotificationEmail = (userId, subject, body) => { .catch(error => dispatch({type: userTypes.USER_EMAIL_FAILURE, error})); }; }; + +// let a user edit their username +export const enableUsernameEdit = (userId) => { + return (dispatch) => { + return coralApi(`/users/${userId}/username-enable`, {method: 'POST'}) + .catch(error => dispatch({type: userTypes.USERNAME_ENABLE_FAILURE, error})); + }; +}; diff --git a/client/coral-admin/src/components/ModerationList.js b/client/coral-admin/src/components/ModerationList.js index c1df40d31..47e91e551 100644 --- a/client/coral-admin/src/components/ModerationList.js +++ b/client/coral-admin/src/components/ModerationList.js @@ -3,7 +3,7 @@ import styles from './ModerationList.css'; import key from 'keymaster'; import Hammer from 'hammerjs'; import Comment from './Comment'; -import UserAction from './UserAction'; +import User from './User'; import SuspendUserModal from './SuspendUserModal'; // Each action has different meaning and configuration @@ -138,7 +138,7 @@ export default class ModerationList extends React.Component { if (menuOption === 'REJECTED') { this.setState({suspendUserModal: action}); } else if (menuOption === 'ACCEPTED') { - this.props.userStatusUpdate('ACTIVE', action.item_id); + this.props.userStatusUpdate('APPROVED', action.item_id); } } } @@ -177,7 +177,7 @@ export default class ModerationList extends React.Component { // If the item is an action... const user = users[item.item_id]; - modItem = user && { +const User = props => { const {action, user} = props; let userStatus = user.status; - const links = user.settings.bio ? linkify.getMatches(user.settings.bio) : []; // Do not display unless the user status is 'pending' or 'banned'. // This means that they have already been reviewed and approved. @@ -27,8 +21,6 @@ const UserAction = props => { {user.displayName}
- {links ? - Contains Link : null}
{props.modActions.map( (action, i) => @@ -48,32 +40,12 @@ const UserAction = props => { {lang.t('comment.banned_user')} : null}
- { - user.settings.bio && -
-
-
{lang.t('user.user_bio')}:
- - - - - -
-
- }
{`${action.count} ${action.action_type === 'flag_bio' ? lang.t('user.bio_flags') : lang.t('user.username_flags')}`}
; }; -export default UserAction; - -const linkStyles = { - backgroundColor: 'rgb(255, 219, 135)', - padding: '1px 2px' -}; +export default User; const lang = new I18n(translations); diff --git a/client/coral-admin/src/constants/users.js b/client/coral-admin/src/constants/users.js index 3cd5e5b4b..9cd7e2093 100644 --- a/client/coral-admin/src/constants/users.js +++ b/client/coral-admin/src/constants/users.js @@ -2,4 +2,5 @@ export const UPDATE_STATUS_REQUEST = 'UPDATE_STATUS_REQUEST'; export const UPDATE_STATUS_SUCCESS = 'UPDATE_STATUS_SUCCESS'; export const UPDATE_STATUS_FAILURE = 'UPDATE_STATUS_FAILURE'; export const USER_EMAIL_FAILURE = 'USER_EMAIL_FAILURE'; +export const USERNAME_ENABLE_FAILURE = 'USERNAME_ENABLE_FAILURE'; export const USERS_MODERATION_QUEUE_FETCH_SUCCESS = 'USERS_MODERATION_QUEUE_FETCH_SUCCESS'; diff --git a/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js b/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js index d1d1afd53..327913927 100644 --- a/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js +++ b/client/coral-admin/src/containers/ModerationQueue/ModerationContainer.js @@ -11,7 +11,7 @@ import { fetchFlaggedQueue, fetchModerationQueueComments, } from 'actions/comments'; -import {userStatusUpdate, sendNotificationEmail} from 'actions/users'; +import {userStatusUpdate, sendNotificationEmail, enableUsernameEdit} from 'actions/users'; import {fetchSettings} from 'actions/settings'; import ModerationQueue from './ModerationQueue'; @@ -122,7 +122,8 @@ const mapDispatchToProps = dispatch => { userStatusUpdate: (status, userId, commentId) => dispatch(userStatusUpdate(status, userId, commentId)).then(() => { dispatch(fetchModerationQueueComments()); }), - suspendUser: (userId, subject, text) => dispatch(userStatusUpdate('suspended', userId)) + suspendUser: (userId, subject, text) => dispatch(userStatusUpdate('BANNED', userId)) + .then(() => dispatch(enableUsernameEdit(userId))) .then(() => dispatch(sendNotificationEmail(userId, subject, text))) .then(() => dispatch(fetchModerationQueueComments())) , diff --git a/client/coral-embed-stream/src/Comment.js b/client/coral-embed-stream/src/Comment.js index 778614880..c0c0d57d1 100644 --- a/client/coral-embed-stream/src/Comment.js +++ b/client/coral-embed-stream/src/Comment.js @@ -94,14 +94,7 @@ class Comment extends React.Component { style={{marginLeft: depth * 30}}>
+ author={comment.user}/>
diff --git a/client/coral-embed-stream/src/Embed.js b/client/coral-embed-stream/src/Embed.js index 9eea38bb4..a853efead 100644 --- a/client/coral-embed-stream/src/Embed.js +++ b/client/coral-embed-stream/src/Embed.js @@ -11,6 +11,7 @@ const {fetchAssetSuccess} = assetActions; import {queryStream} from 'coral-framework/graphql/queries'; import {postComment, postAction, deleteAction} from 'coral-framework/graphql/mutations'; +import {editName} from 'coral-framework/actions/user'; import {Notification, notificationActions, authActions, assetActions, pym} from 'coral-framework'; import Stream from './Stream'; @@ -84,6 +85,8 @@ class Embed extends Component { const openStream = closedAt === null; + const banned = user && user.status === 'BANNED'; + const expandForLogin = showSignInDialog ? { minHeight: document.body.scrollHeight + 200 } : {}; @@ -100,7 +103,7 @@ class Embed extends Component { Settings Configure Stream - {loggedIn && } + {loggedIn && } { openStream @@ -109,7 +112,12 @@ class Embed extends Component { content={asset.settings.infoBoxContent} enable={asset.settings.infoBoxEnable} /> - }> + + }> { user ? : null @@ -148,28 +155,28 @@ class Embed extends Component { clearNotification={this.props.clearNotification} notification={{text: null}} /> - - + + - - + + - + -
+ ); } @@ -193,6 +200,7 @@ const mapDispatchToProps = dispatch => ({ }); }, clearNotification: () => dispatch(clearNotification()), + editName: (displayName) => dispatch(editName(displayName)), showSignInDialog: (offset) => dispatch(showSignInDialog(offset)), logout: () => dispatch(logout()), dispatch: d => dispatch(d) diff --git a/client/coral-framework/actions/auth.js b/client/coral-framework/actions/auth.js index 1d9faf900..bda46ae42 100644 --- a/client/coral-framework/actions/auth.js +++ b/client/coral-framework/actions/auth.js @@ -15,15 +15,15 @@ export const hideCreateDisplayNameDialog = () => ({type: actions.HIDE_CREATEDISP const createDisplayNameSuccess = () => ({type: actions.CREATEDISPLAYNAME_SUCCESS}); const createDisplayNameFailure = error => ({type: actions.CREATEDISPLAYNAME_FAILURE, error}); -export const updateDisplayName = displayName => ({type: actions.UPDATE_DISPLAYNAME, displayName}); +export const updateDisplayName = ({displayName}) => ({type: actions.UPDATE_DISPLAYNAME, displayName}); export const createDisplayName = (userId, formData) => dispatch => { dispatch(createDisplayNameRequest()); - coralApi(`/users/${userId}/displayname`, {method: 'POST', body: formData}) - .then((user) => { + coralApi('/account/displayname', {method: 'PUT', body: formData}) + .then(() => { dispatch(createDisplayNameSuccess()); dispatch(hideCreateDisplayNameDialog()); - dispatch(updateDisplayName(user)); + dispatch(updateDisplayName(formData)); }) .catch(error => { dispatch(createDisplayNameFailure(lang.t(`error.${error.message}`))); diff --git a/client/coral-framework/actions/user.js b/client/coral-framework/actions/user.js index 4620262d3..42d2e0398 100644 --- a/client/coral-framework/actions/user.js +++ b/client/coral-framework/actions/user.js @@ -1,4 +1,3 @@ -import * as actions from '../constants/user'; import {addNotification} from '../actions/notification'; import coralApi from '../helpers/response'; @@ -6,16 +5,9 @@ import I18n from 'coral-framework/modules/i18n/i18n'; import translations from './../translations'; const lang = new I18n(translations); -const saveBioRequest = () => ({type: actions.SAVE_BIO_REQUEST}); -const saveBioSuccess = settings => ({type: actions.SAVE_BIO_SUCCESS, settings}); -const saveBioFailure = error => ({type: actions.SAVE_BIO_FAILURE, error}); - -export const saveBio = (user_id, formData) => dispatch => { - dispatch(saveBioRequest()); - coralApi('/account/settings', {method: 'PUT', body: formData}) +export const editName = (displayName) => (dispatch) => { + return coralApi('/account/displayname', {method: 'PUT', body: {displayName}}) .then(() => { - dispatch(addNotification('success', lang.t('successBioUpdate'))); - dispatch(saveBioSuccess(formData)); - }) - .catch(error => dispatch(saveBioFailure(error))); + dispatch(addNotification('success', lang.t('successNameUpdate'))); + }); }; diff --git a/client/coral-framework/components/RestrictedContent.css b/client/coral-framework/components/RestrictedContent.css index 47ced7b0b..ca5a6517c 100644 --- a/client/coral-framework/components/RestrictedContent.css +++ b/client/coral-framework/components/RestrictedContent.css @@ -2,3 +2,13 @@ background: #D8D8D8; padding: 25px; } + +.editNameInput { + margin-top: 10px; + margin-bottom: 10px; +} + +.alert { + margin-top: 10px; + color: #B71C1C; +} diff --git a/client/coral-framework/components/SuspendedAccount.js b/client/coral-framework/components/SuspendedAccount.js index 46d1f1d58..4c221aa81 100644 --- a/client/coral-framework/components/SuspendedAccount.js +++ b/client/coral-framework/components/SuspendedAccount.js @@ -1,11 +1,79 @@ -import React from 'react'; +import React, {Component, PropTypes} from 'react'; import I18n from 'coral-framework/modules/i18n/i18n'; import translations from 'coral-framework/translations.json'; const lang = new I18n(translations); import styles from './RestrictedContent.css'; +import {Button} from 'coral-ui'; +import validate from '../helpers/validate'; -export default () => ( -
- {lang.t('suspendedAccountMsg')} -
-); +class SuspendedAccount extends Component { + + static propTypes = { + canEditName: PropTypes.bool, + editName: PropTypes.func.isRequired + } + + state = { + displayName: '', + alert: '' + } + + onSubmitClick = (e) => { + const {editName} = this.props; + const {displayName} = this.state; + e.preventDefault(); + if (validate.displayName(displayName)) { + editName(displayName) + .then(() => location.reload()) + .catch((error) => { + this.setState({alert: lang.t(`error.${error.message}`)}); + }); + } else { + this.setState({alert: lang.t('editName.error')}); + } + + } + + render () { + const {canEditName} = this.props; + const {displayName, alert} = this.state; + + return
+ { + canEditName ? + lang.t('editName.msg') + : lang.t('bannedAccountMsg') + } + { + canEditName ? +
+
+ {alert} +
+ + this.setState({displayName: e.target.value})} + rows={3}/>
+ +
: null + } +
; + } +} + +export default SuspendedAccount; diff --git a/client/coral-framework/constants/user.js b/client/coral-framework/constants/user.js index 57f4e706b..5e0a23d7a 100644 --- a/client/coral-framework/constants/user.js +++ b/client/coral-framework/constants/user.js @@ -1,6 +1,6 @@ -export const SAVE_BIO_REQUEST = 'SAVE_BIO_REQUEST'; -export const SAVE_BIO_SUCCESS = 'SAVE_BIO_SUCCESS'; -export const SAVE_BIO_FAILURE = 'SAVE_BIO_FAILURE'; +export const EDIT_NAME_REQUEST = 'EDIT_NAME_REQUEST'; +export const EDIT_NAME_SUCCESS = 'EDIT_NAME_SUCCESS'; +export const EDIT_NAME_FAILURE = 'EDIT_NAME_FAILURE'; export const COMMENTS_BY_USER_REQUEST = 'COMMENTS_BY_USER_REQUEST'; export const COMMENTS_BY_USER_SUCCESS = 'COMMENTS_BY_USER_SUCCESS'; export const COMMENTS_BY_USER_FAILURE = 'COMMENTS_BY_USER_FAILURE'; diff --git a/client/coral-framework/graphql/fragments/commentView.graphql b/client/coral-framework/graphql/fragments/commentView.graphql index fb8051155..29f9b3bfe 100644 --- a/client/coral-framework/graphql/fragments/commentView.graphql +++ b/client/coral-framework/graphql/fragments/commentView.graphql @@ -6,9 +6,6 @@ fragment commentView on Comment { user { id name: displayName - settings { - bio - } } actions { type: action_type diff --git a/client/coral-framework/graphql/queries/index.js b/client/coral-framework/graphql/queries/index.js index 1a9e8d36e..7ce065baa 100644 --- a/client/coral-framework/graphql/queries/index.js +++ b/client/coral-framework/graphql/queries/index.js @@ -11,6 +11,9 @@ function getQueryVariable(variable) { return decodeURIComponent(pair[1]); } } + + // If no query is included, return a default string for development + return 'http://dev.default.stream'; } export const queryStream = graphql(STREAM_QUERY, { diff --git a/client/coral-framework/reducers/auth.js b/client/coral-framework/reducers/auth.js index da68db043..c894ecde4 100644 --- a/client/coral-framework/reducers/auth.js +++ b/client/coral-framework/reducers/auth.js @@ -1,4 +1,4 @@ -import {Map} from 'immutable'; +import {Map, fromJS} from 'immutable'; import * as actions from '../constants/auth'; const initialState = Map({ @@ -21,7 +21,7 @@ const initialState = Map({ const purge = user => { const {settings, profiles, ...userData} = user; // eslint-disable-line - return userData; + return fromJS(userData); }; export default function auth (state = initialState, action) { @@ -131,8 +131,9 @@ export default function auth (state = initialState, action) { .set('passwordRequestFailure', 'There was an error sending your password reset email. Please try again soon!') .set('passwordRequestSuccess', null); case actions.UPDATE_DISPLAYNAME: + console.log('Action', action); return state - .set('user', purge(action.displayName)); + .setIn(['user', 'displayName'], action.displayName); case actions.VERIFY_EMAIL_FAILURE: return state .set('emailVerificationFailure', true) diff --git a/client/coral-framework/translations.json b/client/coral-framework/translations.json index 07b719f6b..989a41cc4 100644 --- a/client/coral-framework/translations.json +++ b/client/coral-framework/translations.json @@ -1,9 +1,15 @@ { "en": { "successUpdateSettings": "The changes you have made have been applied to the comment stream on this article", - "successBioUpdate": "Your Bio has been updated", + "successNameUpdate": "Your display name has been updated", "contentNotAvailable": "This content is not available", - "suspendedAccountMsg": "Your account is currently suspended. This means that you cannot Like, Flag, or write comments. Please contact moderator@fakeurl.com for more information", + "bannedAccountMsg": "Your account is currently suspended. This means that you cannot Like, Flag, or write comments. Please contact moderator@fakeurl.com for more information", + "editName": { + "msg": "Your account is currently suspended because your display name has been deemed inappropriate. To restore your account, please enter a new username. You may contact moderator@fakeurl.com for more information.", + "label": "New Display Name", + "button": "Submit", + "error": "Display names can contain letters, numbers and _ only" + }, "error": { "emailNotVerified": "Email address {0} not verified.", "email": "Not a valid E-Mail", @@ -26,7 +32,8 @@ "successUpdateSettings": "La configuración de este articulo fue actualizada", "successBioUpdate": "Tu bio fue actualizada", "contentNotAvailable": "El contenido no se encuentra disponible", - "suspendedAccountMsg": "Tu cuenta se encuentra suspendida. Esto significa que no puedes dar Like, Marcar o escribir commentarios. Por favor, contacta moderator@fakeurl for more information", + "bannedAccountMsg": "Tu cuenta se encuentra suspendida. Esto significa que no puedes dar Like, Marcar o escribir commentarios. Por favor, contacta moderator@fakeurl for more information", + "editNameMsg": "", "error": { "emailNotVerified": "Dirección de correo electrónico {0} no verificada.", "email": "No es un email válido", diff --git a/client/coral-plugin-author-name/AuthorName.js b/client/coral-plugin-author-name/AuthorName.js index 624750c60..bca1d716b 100644 --- a/client/coral-plugin-author-name/AuthorName.js +++ b/client/coral-plugin-author-name/AuthorName.js @@ -1,6 +1,4 @@ import React, {Component} from 'react'; -import {Tooltip} from 'coral-ui'; -import FlagBio from 'coral-plugin-flags/FlagBio'; const packagename = 'coral-plugin-author-name'; import styles from './styles.css'; @@ -24,24 +22,11 @@ export default class AuthorName extends Component { render () { const {author} = this.props; - const {showTooltip} = this.state; return ( -
- - {author && author.name} - {author.settings.bio ? : null} - - {showTooltip && author.settings.bio - && ( - -
- {author.settings.bio} -
-
- -
-
- )} +
+ {author && author.name}
); } diff --git a/client/coral-settings/components/NotLoggedIn.js b/client/coral-settings/components/NotLoggedIn.js index 8266a745e..095d43a8f 100644 --- a/client/coral-settings/components/NotLoggedIn.js +++ b/client/coral-settings/components/NotLoggedIn.js @@ -15,7 +15,6 @@ export default ({showSignInDialog}) => ( From the Settings Page you can
  • See your comment history
  • -
  • Write a bio about yourself to display to the community
diff --git a/client/coral-settings/containers/SettingsContainer.js b/client/coral-settings/containers/SettingsContainer.js index f02badd80..4398ed5c6 100644 --- a/client/coral-settings/containers/SettingsContainer.js +++ b/client/coral-settings/containers/SettingsContainer.js @@ -4,12 +4,10 @@ import React, {Component} from 'react'; import I18n from 'coral-framework/modules/i18n/i18n'; import {myCommentHistory} from 'coral-framework/graphql/queries'; -import {saveBio} from 'coral-framework/actions/user'; -import BioContainer from './BioContainer'; import {link} from 'coral-framework/PymConnection'; import NotLoggedIn from '../components/NotLoggedIn'; -import {TabBar, Tab, TabContent, Spinner} from 'coral-ui'; +import {Spinner} from 'coral-ui'; import SettingsHeader from '../components/SettingsHeader'; import CommentHistory from 'coral-plugin-history/CommentHistory'; @@ -33,8 +31,7 @@ class SettingsContainer extends Component { } render() { - const {loggedIn, userData, asset, showSignInDialog, data, user} = this.props; - const {activeTab} = this.state; + const {loggedIn, asset, showSignInDialog, data} = this.props; const {me} = this.props.data; if (!loggedIn || !me) { @@ -48,25 +45,30 @@ class SettingsContainer extends Component { return (
- - {lang.t('allComments')} ({user.myComments.length}) - {lang.t('profileSettings')} - - - { - me.comments.length ? - - : -

{lang.t('userNoComment')}

- } -
- - - + { + + // Hiding bio until moderation can get figured out + /* + {lang.t('allComments')} ({user.myComments.length}) + {lang.t('profileSettings')} + + */ + me.comments.length ? + + : +

{lang.t('userNoComment')}

+ + // Hiding user bio pending effective moderation system. + /*
+ + + */ + } +
); } @@ -78,8 +80,9 @@ const mapStateToProps = state => ({ auth: state.auth.toJS() }); -const mapDispatchToProps = dispatch => ({ - saveBio: (user_id, formData) => dispatch(saveBio(user_id, formData)) +const mapDispatchToProps = () => ({ + + // saveBio: (user_id, formData) => dispatch(saveBio(user_id, formData)) }); export default compose( diff --git a/graph/mutators/index.js b/graph/mutators/index.js index b799cf83d..58d0ed62c 100644 --- a/graph/mutators/index.js +++ b/graph/mutators/index.js @@ -2,7 +2,6 @@ const _ = require('lodash'); const Comment = require('./comment'); const Action = require('./action'); -const User = require('./user'); module.exports = (context) => { @@ -10,7 +9,6 @@ module.exports = (context) => { return _.merge(...[ Comment, Action, - User, ].map((mutators) => { // Each set of mutators is a function which takes the context. diff --git a/graph/mutators/user.js b/graph/mutators/user.js deleted file mode 100644 index 96049bbab..000000000 --- a/graph/mutators/user.js +++ /dev/null @@ -1,31 +0,0 @@ -const UsersService = require('../../services/users'); - -/** - * Updates a users settings. - * @param {Object} user the user performing the request - * @param {String} bio the new user bio - * @return {Promise} - */ -const updateUserSettings = ({user}, {bio}) => { - return UsersService.updateSettings(user.id, {bio}); -}; - -module.exports = (context) => { - - // TODO: refactor to something that'll return an error in the event an attempt - // is made to mutate state while not logged in. There's got to be a better way - // to do this. - if (context.user && context.user.can('mutation:updateUserSettings')) { - return { - User: { - updateSettings: (settings) => updateUserSettings(context, settings) - } - }; - } - - return { - User: { - updateSettings: () => {} - } - }; -}; diff --git a/graph/resolvers/root_mutation.js b/graph/resolvers/root_mutation.js index ddc8e4223..ef46b839a 100644 --- a/graph/resolvers/root_mutation.js +++ b/graph/resolvers/root_mutation.js @@ -8,9 +8,6 @@ const RootMutation = { deleteAction(_, {id}, {mutators: {Action}}) { return Action.delete({id}); }, - updateUserSettings(_, {settings}, {mutators: {User}}) { - return User.updateSettings(settings); - } }; module.exports = RootMutation; diff --git a/graph/typeDefs.graphql b/graph/typeDefs.graphql index 744a53252..b1f9b82f7 100644 --- a/graph/typeDefs.graphql +++ b/graph/typeDefs.graphql @@ -10,11 +10,6 @@ enum SORT_ORDER { # Date represented as an ISO8601 string. scalar Date -type UserSettings { - # bio of the user. - bio: String -} - input CommentsQuery { # current status of a comment. statuses: [COMMENT_STATUS] @@ -22,7 +17,7 @@ input CommentsQuery { # asset that a comment is on. asset_id: ID - # the parent of the comment that we want to retrive. + # the parent of the comment that we want to retrieve. parent_id: ID # comments returned will only be ones which have at least one action of this @@ -61,8 +56,8 @@ type User { # the current roles of the user. roles: [USER_ROLES] - # settings for a user. - settings: UserSettings + # determines whether the user can edit their username + canEditName: Boolean # returns all comments based on a query. comments(query: CommentsQuery): [Comment] @@ -150,7 +145,7 @@ type Asset { # The scraped title of the asset. title: String - # The URL that the asset is locaed on. + # The URL that the asset is located on. url: String # The top level comments that are attached to the asset. @@ -205,11 +200,6 @@ input CreateActionInput { item_id: ID! } -input UpdateUserSettingsInput { - # user bio - bio: String! -} - type RootMutation { # creates a comment on the asset. createComment(asset_id: ID!, parent_id: ID, body: String!): Comment @@ -220,8 +210,6 @@ type RootMutation { # delete an action based on the action id. deleteAction(id: ID!): Boolean - # updates a user's settings, it will return if the query was successful. - updateUserSettings(settings: UpdateUserSettingsInput!): Boolean } schema { diff --git a/models/user.js b/models/user.js index 43bbde084..06dc3c7d1 100644 --- a/models/user.js +++ b/models/user.js @@ -12,7 +12,7 @@ const USER_STATUS = [ 'ACTIVE', 'BANNED', 'PENDING', - 'SUSPENDED', + 'APPROVED' // Indicates that the users' displayname has been approved ]; // ProfileSchema is the mongoose schema defined as the representation of a @@ -97,6 +97,12 @@ const UserSchema = new mongoose.Schema({ default: 'ACTIVE' }, + // Determines whether the user can edit their username. + canEditName: { + type: Boolean, + default: false + }, + // User's settings settings: { bio: { @@ -141,7 +147,7 @@ const USER_GRAPH_OPERATIONS = [ 'mutation:createComment', 'mutation:createAction', 'mutation:deleteAction', - 'mutation:updateUserSettings' + 'mutation:editName' ]; /** diff --git a/routes/api/account/index.js b/routes/api/account/index.js index cc1370cc8..d383e9f36 100644 --- a/routes/api/account/index.js +++ b/routes/api/account/index.js @@ -115,19 +115,18 @@ router.put('/password/reset', (req, res, next) => { }); }); -router.put('/settings', authorization.needed(), (req, res, next) => { - - const { - bio - } = req.body; - +router.put('/displayname', authorization.needed(), (req, res, next) => { UsersService - .updateSettings(req.user.id, {bio}) + .editName(req.user.id, req.body.displayName) .then(() => { res.status(204).end(); }) - .catch((err) => { - next(err); + .catch(error => { + if (error.code === 11000) { + next(errors.ErrDisplayTaken); + } else { + next(error); + } }); }); diff --git a/routes/api/auth/index.js b/routes/api/auth/index.js index 050aa1135..e3acf2c77 100644 --- a/routes/api/auth/index.js +++ b/routes/api/auth/index.js @@ -2,6 +2,7 @@ const express = require('express'); const passport = require('../../../services/passport'); const authorization = require('../../../middleware/authorization'); const errors = require('../../../errors'); +const UsersService = require('../../../services/users'); const router = express.Router(); @@ -69,15 +70,20 @@ const HandleAuthPopupCallback = (req, res, next) => (err, user) => { return res.render('auth-callback', {err: JSON.stringify(errors.ErrNotAuthorized), data: null}); } - // Perform the login of the user! - req.logIn(user, (err) => { - if (err) { - return res.render('auth-callback', {err: JSON.stringify(err), data: null}); - } + // Authorize the user to edit their displayName. + UsersService.toggleNameEdit(user.id, true) + .then(() => { + + // Perform the login of the user! + req.logIn(user, (err) => { + if (err) { + return res.render('auth-callback', {err: JSON.stringify(err), data: null}); + } - // We logged in the user! Let's send back the user data. - res.render('auth-callback', {err: null, data: JSON.stringify(user)}); - }); + // We logged in the user! Let's send back the user data. + res.render('auth-callback', {err: null, data: JSON.stringify(user)}); + }); + }); }; /** diff --git a/routes/api/queue/index.js b/routes/api/queue/index.js index 2373b808f..b3cbb1a52 100644 --- a/routes/api/queue/index.js +++ b/routes/api/queue/index.js @@ -79,7 +79,7 @@ router.get('/comments/flagged', authorization.needed('ADMIN'), (req, res, next) }); // Returns back all the users that are in the moderation queue. -router.get('/users/pending', (req, res, next) => { +router.get('/users/flagged', (req, res, next) => { UsersService.moderationQueue() .then((users) => { return Promise.all([ diff --git a/routes/api/users/index.js b/routes/api/users/index.js index f7cdea2be..5d9386d14 100644 --- a/routes/api/users/index.js +++ b/routes/api/users/index.js @@ -60,15 +60,16 @@ router.post('/:user_id/status', authorization.needed('ADMIN'), (req, res, next) .catch(next); }); -router.post('/:user_id/displayname', authorization.needed(), (req, res, next) => { - UsersService.setDisplayName(req.params.user_id, req.body.displayName) - .then((user) => { - res.status(201).json(user); - }) - .catch(next); +router.post('/:user_id/username-enable', authorization.needed('ADMIN'), (req, res, next) => { + UsersService + .toggleNameEdit(req.params.user_id, true) + .then(() => { + res.status(204).end(); + }); }); -router.post('/:user_id/email', authorization.needed('admin'), (req, res, next) => { +router.post('/:user_id/email', authorization.needed('ADMIN'), (req, res, next) => { + UsersService.findById(req.params.user_id) .then(user => { let localProfile = user.profiles.find((profile) => profile.provider === 'local'); @@ -170,7 +171,7 @@ router.post('/:user_id/actions', authorization.needed(), (req, res, next) => { // Set the user status to "pending" for review by moderators if (action_type.slice(0, 4) === 'FLAG') { - return UsersService.setStatus(req.user.id, 'PENDING') + return UsersService.setStatus(req.params.user_id, 'PENDING') .then(() => action); } else { return action; diff --git a/services/users.js b/services/users.js index fd39a50c1..bab7b0d20 100644 --- a/services/users.js +++ b/services/users.js @@ -350,26 +350,16 @@ module.exports = class UsersService { return Promise.reject(new Error(`status ${status} is not supported`)); } - return UserModel.update({id}, {$set: {status}}); - } - - /** - * Set the display name of a user. - * @param {String} id id of a user - * @param {String} displayName display name to set - * @param {Function} done callback after the operation is complete - */ - static setDisplayName(id, displayName) { - - return UsersService.isValidDisplayName(displayName) - .then(() => { // displayName is valid - return UserModel.update( - {id}, - {$set: {'displayName': displayName}}) - .then(() => { - return UserModel.findOne({'id': id}); - }); - }); + return UserModel.update({ + id, + status: { + $ne: 'APPROVED' + } + }, { + $set: { + status + } + }); } /** @@ -644,4 +634,37 @@ module.exports = class UsersService { return UserModel.find({status: 'PENDING'}); } + /** + * Gives the user the ability to edit their username. + * @param {String} id the id of the user to be toggled. + * @param {Boolean} canEditName sets whether the user can edit their name. + * @return {Promise} + */ + static toggleNameEdit(id, canEditName) { + return UserModel.update({id}, { + $set: {canEditName} + }); + } + + /** + * Updates the user's displayName. + * @param {String} id the id of the user to be enabled. + * @param {String} displayName The new displayname for the user. + * @return {Promise} + */ + static editName(id, displayName) { + return UserModel.update({ + id, + canEditName: true + }, { + $set: { + displayName: displayName.toLowerCase(), + canEditName: false, + status: 'PENDING' + } + }).then((result) => { + return result.nModified > 0 ? result : + Promise.reject(new Error('You do not have permission to update your username.')); + }); + } }; diff --git a/test/e2e/pages/adminPage.js b/test/e2e/pages/adminPage.js index 3cc00d5fc..e359715ac 100644 --- a/test/e2e/pages/adminPage.js +++ b/test/e2e/pages/adminPage.js @@ -10,8 +10,7 @@ const embedStreamCommands = { return this .waitForElementVisible('@moderationList') .waitForElementVisible('@approveButton') - .click('@approveButton') - .waitForElementNotPresent('@approveButton'); + .click('@approveButton'); } }; diff --git a/test/routes/api/account/index.js b/test/routes/api/account/index.js new file mode 100644 index 000000000..5b9acfa9d --- /dev/null +++ b/test/routes/api/account/index.js @@ -0,0 +1,71 @@ +const passport = require('../../../passport'); + +const app = require('../../../../app'); +const chai = require('chai'); +const expect = chai.expect; + +const SettingsService = require('../../../../services/settings'); +const settings = {id: '1', moderation: 'PRE', wordlist: {banned: ['bad words'], suspect: ['suspect words']}}; + +// Setup chai. +chai.should(); +chai.use(require('chai-http')); + +const UsersService = require('../../../../services/users'); + +describe('/api/v1/account/displayname', () => { + let mockUser; + + beforeEach(() => SettingsService.init(settings).then(() => { + return UsersService.createLocalUser('ana@gmail.com', '123321123', 'Ana'); + }) + .then((user) => { + mockUser = user; + })); + + describe('#put', () => { + it('it should enable a user to edit their username if canEditName is enabled', () => { + return chai.request(app) + .post(`/api/v1/users/${mockUser.id}/username-enable`) + .set(passport.inject({id: '456', roles: ['ADMIN']})) + .then(() => chai.request(app) + .put('/api/v1/account/displayname') + .set(passport.inject({id: mockUser.id, roles: []})) + .send({displayName: 'MojoJojo'})) + .then((res) => { + expect(res).to.have.status(204); + }); + }); + + it('it should return an error if the wrong user tries to edit a username', (done) => { + chai.request(app) + .post(`/api/v1/users/${mockUser.id}/username-enable`) + .set(passport.inject({id: '456', roles: ['ADMIN']})) + .then(() => chai.request(app) + .put('/api/v1/account/displayname') + .set(passport.inject({id: 'wrongid', roles: []})) + .send({displayName: 'MojoJojo'})) + .then(() => { + done(new Error('Exected Error')); + }) + .catch((err) => { + expect(err).to.be.truthy; + done(); + }); + }); + + it('it should return an error when the user tries to edit their username if canEditName is disabled', (done) => { + chai.request(app) + .put('/api/v1/account/displayname') + .set(passport.inject({id: mockUser.id, roles: []})) + .send({username: 'MojoJojo'}) + .then(() => { + done(new Error('Exected Error')); + }) + .catch((err) => { + expect(err).to.be.truthy; + done(); + }); + }); + }); +}); diff --git a/test/routes/api/queue/index.js b/test/routes/api/queue/index.js index ab60a9f20..9f89a961e 100644 --- a/test/routes/api/queue/index.js +++ b/test/routes/api/queue/index.js @@ -110,7 +110,7 @@ describe('/api/v1/queue', () => { it('should return all pending users and actions', function(done){ chai.request(app) - .get('/api/v1/queue/users/pending') + .get('/api/v1/queue/users/flagged') .set(passport.inject({roles: ['ADMIN']})) .end(function(err, res){ expect(err).to.be.null; diff --git a/test/routes/api/user/index.js b/test/routes/api/user/index.js index d1771726d..f6e202243 100644 --- a/test/routes/api/user/index.js +++ b/test/routes/api/user/index.js @@ -52,33 +52,48 @@ describe('/api/v1/users/:user_id/email/confirm', () => { describe('/api/v1/users/:user_id/actions', () => { - const users = [{ - displayName: 'Ana', - email: 'ana@gmail.com', - password: '123456789' - }, { - displayName: 'Maria', - email: 'maria@gmail.com', - password: '123456789' - }]; + let mockUser; - beforeEach(() => { - return SettingsService.init(settings).then(() => { - return UsersService.createLocalUsers(users); - }); - }); + beforeEach(() => SettingsService.init(settings).then(() => { + return UsersService.createLocalUser('ana@gmail.com', '123321123', 'Ana'); + }) + .then((user) => { + mockUser = user; + })); describe('#post', () => { it('it should update actions', () => { return chai.request(app) - .post('/api/v1/users/abc/actions') + .post(`/api/v1/users/${mockUser.id}/actions`) .set(passport.inject({id: '456', roles: ['ADMIN']})) .send({'action_type': 'FLAG', metadata: {reason: 'Bio is too awesome.'}}) .then((res) => { expect(res).to.have.status(201); expect(res).to.have.body; expect(res.body).to.have.property('action_type', 'FLAG'); - expect(res.body).to.have.property('item_id', 'abc'); + expect(res.body).to.have.property('item_id', mockUser.id); + }); + }); + }); +}); + +describe('/api/v1/users/:user_id/username-enable', () => { + let mockUser; + + beforeEach(() => SettingsService.init(settings).then(() => { + return UsersService.createLocalUser('ana@gmail.com', '123321123', 'Ana'); + }) + .then((user) => { + mockUser = user; + })); + + describe('#post', () => { + it('it should enable a user to edit their username', () => { + return chai.request(app) + .post(`/api/v1/users/${mockUser.id}/username-enable`) + .set(passport.inject({id: '456', roles: ['ADMIN']})) + .then((res) => { + expect(res).to.have.status(204); }); }); }); diff --git a/test/services/users.js b/test/services/users.js index ba2bedcc3..5774d45ae 100644 --- a/test/services/users.js +++ b/test/services/users.js @@ -178,25 +178,6 @@ describe('services.UsersService', () => { }); }); - describe('#setDisplayName', () => { - it('should set the display name to a new unique one', () => { - return UsersService - .setDisplayName(mockUsers[0].id, 'maria') - .then(() => UsersService.findById(mockUsers[0].id)) - .then((user) => { - expect(user).to.have.property('displayName', 'maria'); - }); - }); - - it('should return an error when the displayName is not unique', () => { - return UsersService - .setDisplayName(mockUsers[0].id, 'marvel') - .catch((error) => { - expect(error).to.not.be.null; - }); - }); - }); - describe('#ban', () => { it('should set the status to banned', () => { return UsersService @@ -227,4 +208,56 @@ describe('services.UsersService', () => { }); }); }); + + describe('#toggleNameEdit', () => { + it('should toggle the canEditName field', () => { + return UsersService + .toggleNameEdit(mockUsers[0].id, true) + .then(() => UsersService.findById(mockUsers[0].id)) + .then((user) => { + expect(user).to.have.property('canEditName', true); + }); + }); + }); + + describe('#editName', () => { + it('should let the user edit their username if the proper toggle is set', () => { + return UsersService + .toggleNameEdit(mockUsers[0].id, true) + .then(() => UsersService.editName(mockUsers[0].id, 'Jojo')) + .then(() => UsersService.findById(mockUsers[0].id)) + .then((user) => { + expect(user).to.have.property('displayName', 'jojo'); + expect(user).to.have.property('canEditName', false); + }); + }); + + it('should return an error if canEditName is false', (done) => { + UsersService + .editName(mockUsers[0].id, 'Jojo') + .then(() => UsersService.findById(mockUsers[0].id)) + .then(() => { + done(new Error('Error expected')); + }) + .catch((err) => { + expect(err).to.be.truthy; + done(); + }); + }); + + it('should return an error if the username is already taken', (done) => { + UsersService + .toggleNameEdit(mockUsers[0].id, true) + .then(() => UsersService.editName(mockUsers[0].id, 'Marvel')) + .then(() => UsersService.findById(mockUsers[0].id)) + .then(() => { + done(new Error('Error expected')); + }) + .catch((err) => { + expect(err).to.be.truthy; + done(); + }); + }); + }); + });