1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-19 21:29:43 +02:00

Add username to user

This commit is contained in:
Maksim Eltyshev 2020-04-03 00:35:25 +05:00
parent ec222a5e32
commit af00e3e191
143 changed files with 1051 additions and 420 deletions

View file

@ -51,6 +51,18 @@ export const clearCurrentUserPasswordUpdateError = () => ({
payload: {}, payload: {},
}); });
export const updateCurrentUserUsername = (data) => ({
type: EntryActionTypes.CURRENT_USER_USERNAME_UPDATE,
payload: {
data,
},
});
export const clearCurrentUserUsernameUpdateError = () => ({
type: EntryActionTypes.CURRENT_USER_USERNAME_UPDATE_ERROR_CLEAR,
payload: {},
});
export const uploadCurrentUserAvatar = (file) => ({ export const uploadCurrentUserAvatar = (file) => ({
type: EntryActionTypes.CURRENT_USER_AVATAR_UPLOAD, type: EntryActionTypes.CURRENT_USER_AVATAR_UPLOAD,
payload: { payload: {

View file

@ -36,6 +36,13 @@ export const clearUserPasswordUpdateError = (id) => ({
}, },
}); });
export const clearUserUsernameUpdateError = (id) => ({
type: ActionTypes.USER_USERNAME_UPDATE_ERROR_CLEAR,
payload: {
id,
},
});
export const deleteUser = (id) => ({ export const deleteUser = (id) => ({
type: ActionTypes.USER_DELETE, type: ActionTypes.USER_DELETE,
payload: { payload: {
@ -202,6 +209,30 @@ export const updateUserPasswordFailed = (id, error) => ({
}, },
}); });
export const updateUserUsernameRequested = (id, data) => ({
type: ActionTypes.USER_USERNAME_UPDATE_REQUESTED,
payload: {
id,
data,
},
});
export const updateUserUsernameSucceeded = (id, username) => ({
type: ActionTypes.USER_USERNAME_UPDATE_SUCCEEDED,
payload: {
id,
username,
},
});
export const updateUserUsernameFailed = (id, error) => ({
type: ActionTypes.USER_USERNAME_UPDATE_FAILED,
payload: {
id,
error,
},
});
export const uploadUserAvatarRequested = (id) => ({ export const uploadUserAvatarRequested = (id) => ({
type: ActionTypes.USER_AVATAR_UPLOAD_REQUESTED, type: ActionTypes.USER_AVATAR_UPLOAD_REQUESTED,
payload: { payload: {

View file

@ -16,6 +16,9 @@ const updateUserEmail = (id, data, headers) => socket.patch(`/users/${id}/email`
const updateUserPassword = (id, data, headers) => const updateUserPassword = (id, data, headers) =>
socket.patch(`/users/${id}/password`, data, headers); socket.patch(`/users/${id}/password`, data, headers);
const updateUserUsername = (id, data, headers) =>
socket.patch(`/users/${id}/username`, data, headers);
const uploadUserAvatar = (id, file, headers) => const uploadUserAvatar = (id, file, headers) =>
http.post( http.post(
`/users/${id}/upload-avatar`, `/users/${id}/upload-avatar`,
@ -34,6 +37,7 @@ export default {
updateUser, updateUser,
updateUserEmail, updateUserEmail,
updateUserPassword, updateUserPassword,
updateUserUsername,
uploadUserAvatar, uploadUserAvatar,
deleteUser, deleteUser,
}; };

View file

@ -8,6 +8,7 @@ import { withPopup } from '../../lib/popup';
import { Input, Popup } from '../../lib/custom-ui'; import { Input, Popup } from '../../lib/custom-ui';
import { useForm } from '../../hooks'; import { useForm } from '../../hooks';
import { isUsername } from '../../utils/validator';
import styles from './AddUserPopup.module.css'; import styles from './AddUserPopup.module.css';
@ -16,17 +17,23 @@ const createMessage = (error) => {
return error; return error;
} }
if (error.message === 'User is already exist') { switch (error.message) {
case 'Email already in use':
return { return {
type: 'error', type: 'error',
content: 'common.userIsAlreadyExist', content: 'common.emailAlreadyInUse',
}; };
} case 'Username already in use':
return {
type: 'error',
content: 'common.usernameAlreadyInUse',
};
default:
return { return {
type: 'warning', type: 'warning',
content: 'common.unknownError', content: 'common.unknownError',
}; };
}
}; };
const AddUserPopup = React.memo( const AddUserPopup = React.memo(
@ -38,6 +45,7 @@ const AddUserPopup = React.memo(
email: '', email: '',
password: '', password: '',
name: '', name: '',
username: '',
...defaultData, ...defaultData,
})); }));
@ -46,12 +54,14 @@ const AddUserPopup = React.memo(
const emailField = useRef(null); const emailField = useRef(null);
const passwordField = useRef(null); const passwordField = useRef(null);
const nameField = useRef(null); const nameField = useRef(null);
const usernameField = useRef(null);
const handleSubmit = useCallback(() => { const handleSubmit = useCallback(() => {
const cleanData = { const cleanData = {
...data, ...data,
email: data.email.trim(), email: data.email.trim(),
name: data.name.trim(), name: data.name.trim(),
username: data.username.trim() || null,
}; };
if (!isEmail(cleanData.email)) { if (!isEmail(cleanData.email)) {
@ -69,6 +79,11 @@ const AddUserPopup = React.memo(
return; return;
} }
if (cleanData.username && !isUsername(cleanData.username)) {
usernameField.current.select();
return;
}
onCreate(cleanData); onCreate(cleanData);
}, [onCreate, data]); }, [onCreate, data]);
@ -78,10 +93,20 @@ const AddUserPopup = React.memo(
useEffect(() => { useEffect(() => {
if (wasSubmitting && !isSubmitting) { if (wasSubmitting && !isSubmitting) {
if (!error) { if (error) {
onClose(); switch (error.message) {
} else if (error.message === 'User is already exist') { case 'Email already in use':
emailField.current.select(); emailField.current.select();
break;
case 'Username already in use':
usernameField.current.select();
break;
default:
}
} else {
onClose();
} }
} }
}, [isSubmitting, wasSubmitting, error, onClose]); }, [isSubmitting, wasSubmitting, error, onClose]);
@ -136,6 +161,22 @@ const AddUserPopup = React.memo(
className={styles.field} className={styles.field}
onChange={handleFieldChange} onChange={handleFieldChange}
/> />
<div className={styles.text}>
{t('common.username')} (
{t('common.optional', {
context: 'inline',
})}
)
</div>
<Input
fluid
ref={usernameField}
name="username"
value={data.username}
readOnly={isSubmitting}
className={styles.field}
onChange={handleFieldChange}
/>
<Button <Button
positive positive
content={t('action.addUser')} content={t('action.addUser')}

View file

@ -18,6 +18,8 @@ const Header = React.memo(
onNotificationDelete, onNotificationDelete,
onUserUpdate, onUserUpdate,
onUserAvatarUpload, onUserAvatarUpload,
onUserUsernameUpdate,
onUserUsernameUpdateMessageDismiss,
onUserEmailUpdate, onUserEmailUpdate,
onUserEmailUpdateMessageDismiss, onUserEmailUpdateMessageDismiss,
onUserPasswordUpdate, onUserPasswordUpdate,
@ -46,12 +48,16 @@ const Header = React.memo(
<UserPopup <UserPopup
email={user.email} email={user.email}
name={user.name} name={user.name}
username={user.username}
avatar={user.avatar} avatar={user.avatar}
isAvatarUploading={user.isAvatarUploading} isAvatarUploading={user.isAvatarUploading}
usernameUpdateForm={user.usernameUpdateForm}
emailUpdateForm={user.emailUpdateForm} emailUpdateForm={user.emailUpdateForm}
passwordUpdateForm={user.passwordUpdateForm} passwordUpdateForm={user.passwordUpdateForm}
onUpdate={onUserUpdate} onUpdate={onUserUpdate}
onAvatarUpload={onUserAvatarUpload} onAvatarUpload={onUserAvatarUpload}
onUsernameUpdate={onUserUsernameUpdate}
onUsernameUpdateMessageDismiss={onUserUsernameUpdateMessageDismiss}
onEmailUpdate={onUserEmailUpdate} onEmailUpdate={onUserEmailUpdate}
onEmailUpdateMessageDismiss={onUserEmailUpdateMessageDismiss} onEmailUpdateMessageDismiss={onUserEmailUpdateMessageDismiss}
onPasswordUpdate={onUserPasswordUpdate} onPasswordUpdate={onUserPasswordUpdate}
@ -76,6 +82,8 @@ Header.propTypes = {
onNotificationDelete: PropTypes.func.isRequired, onNotificationDelete: PropTypes.func.isRequired,
onUserUpdate: PropTypes.func.isRequired, onUserUpdate: PropTypes.func.isRequired,
onUserAvatarUpload: PropTypes.func.isRequired, onUserAvatarUpload: PropTypes.func.isRequired,
onUserUsernameUpdate: PropTypes.func.isRequired,
onUserUsernameUpdateMessageDismiss: PropTypes.func.isRequired,
onUserEmailUpdate: PropTypes.func.isRequired, onUserEmailUpdate: PropTypes.func.isRequired,
onUserEmailUpdateMessageDismiss: PropTypes.func.isRequired, onUserEmailUpdateMessageDismiss: PropTypes.func.isRequired,
onUserPasswordUpdate: PropTypes.func.isRequired, onUserPasswordUpdate: PropTypes.func.isRequired,

View file

@ -8,6 +8,7 @@ import { useDidUpdate, usePrevious, useToggle } from '../../lib/hooks';
import { Input } from '../../lib/custom-ui'; import { Input } from '../../lib/custom-ui';
import { useForm } from '../../hooks'; import { useForm } from '../../hooks';
import { isUsername } from '../../utils/validator';
import styles from './Login.module.css'; import styles from './Login.module.css';
@ -17,12 +18,12 @@ const createMessage = (error) => {
} }
switch (error.message) { switch (error.message) {
case 'Email does not exist': case 'Invalid email or username':
return { return {
type: 'error', type: 'error',
content: 'common.emailDoesNotExist', content: 'common.invalidEmailOrUsername',
}; };
case 'Password is not valid': case 'Invalid password':
return { return {
type: 'error', type: 'error',
content: 'common.invalidPassword', content: 'common.invalidPassword',
@ -51,7 +52,7 @@ const Login = React.memo(
const wasSubmitting = usePrevious(isSubmitting); const wasSubmitting = usePrevious(isSubmitting);
const [data, handleFieldChange, setData] = useForm(() => ({ const [data, handleFieldChange, setData] = useForm(() => ({
email: '', emailOrUsername: '',
password: '', password: '',
...defaultData, ...defaultData,
})); }));
@ -59,17 +60,17 @@ const Login = React.memo(
const message = useMemo(() => createMessage(error), [error]); const message = useMemo(() => createMessage(error), [error]);
const [focusPasswordFieldState, focusPasswordField] = useToggle(); const [focusPasswordFieldState, focusPasswordField] = useToggle();
const emailField = useRef(null); const emailOrUsernameField = useRef(null);
const passwordField = useRef(null); const passwordField = useRef(null);
const handleSubmit = useCallback(() => { const handleSubmit = useCallback(() => {
const cleanData = { const cleanData = {
...data, ...data,
email: data.email.trim(), emailOrUsername: data.emailOrUsername.trim(),
}; };
if (!isEmail(cleanData.email)) { if (!isEmail(cleanData.emailOrUsername) && !isUsername(cleanData.emailOrUsername)) {
emailField.current.select(); emailOrUsernameField.current.select();
return; return;
} }
@ -82,17 +83,17 @@ const Login = React.memo(
}, [onAuthenticate, data]); }, [onAuthenticate, data]);
useEffect(() => { useEffect(() => {
emailField.current.select(); emailOrUsernameField.current.select();
}, []); }, []);
useEffect(() => { useEffect(() => {
if (wasSubmitting && !isSubmitting && error) { if (wasSubmitting && !isSubmitting && error) {
switch (error.message) { switch (error.message) {
case 'Email does not exist': case 'Invalid email or username':
emailField.current.select(); emailOrUsernameField.current.select();
break; break;
case 'Password is not valid': case 'Invalid password':
setData((prevData) => ({ setData((prevData) => ({
...prevData, ...prevData,
password: '', password: '',
@ -136,12 +137,12 @@ const Login = React.memo(
)} )}
<Form size="large" onSubmit={handleSubmit}> <Form size="large" onSubmit={handleSubmit}>
<div className={styles.inputWrapper}> <div className={styles.inputWrapper}>
<div className={styles.inputLabel}>{t('common.email')}</div> <div className={styles.inputLabel}>{t('common.emailOrUsername')}</div>
<Input <Input
fluid fluid
ref={emailField} ref={emailOrUsernameField}
name="email" name="emailOrUsername"
value={data.email} value={data.emailOrUsername}
readOnly={isSubmitting} readOnly={isSubmitting}
className={styles.input} className={styles.input}
onChange={handleFieldChange} onChange={handleFieldChange}

View file

@ -16,12 +16,12 @@ const createMessage = (error) => {
} }
switch (error.message) { switch (error.message) {
case 'User is already exist': case 'Email already in use':
return { return {
type: 'error', type: 'error',
content: 'common.userIsAlreadyExist', content: 'common.emailAlreadyInUse',
}; };
case 'Current password is not valid': case 'Invalid current password':
return { return {
type: 'error', type: 'error',
content: 'common.invalidCurrentPassword', content: 'common.invalidCurrentPassword',
@ -83,11 +83,11 @@ const EditEmailStep = React.memo(
if (wasSubmitting && !isSubmitting) { if (wasSubmitting && !isSubmitting) {
if (error) { if (error) {
switch (error.message) { switch (error.message) {
case 'User is already exist': case 'Email already in use':
emailField.current.select(); emailField.current.select();
break; break;
case 'Current password is not valid': case 'Invalid current password':
setData((prevData) => ({ setData((prevData) => ({
...prevData, ...prevData,
currentPassword: '', currentPassword: '',

View file

@ -15,7 +15,7 @@ const createMessage = (error) => {
} }
switch (error.message) { switch (error.message) {
case 'Current password is not valid': case 'Invalid current password':
return { return {
type: 'error', type: 'error',
content: 'common.invalidCurrentPassword', content: 'common.invalidCurrentPassword',
@ -67,7 +67,7 @@ const EditPasswordStep = React.memo(
if (wasSubmitting && !isSubmitting) { if (wasSubmitting && !isSubmitting) {
if (!error) { if (!error) {
onClose(); onClose();
} else if (error.message === 'Current password is not valid') { } else if (error.message === 'Invalid current password') {
setData((prevData) => ({ setData((prevData) => ({
...prevData, ...prevData,
currentPassword: '', currentPassword: '',

View file

@ -0,0 +1,182 @@
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import { Button, Form, Message } from 'semantic-ui-react';
import { useDidUpdate, usePrevious, useToggle } from '../../lib/hooks';
import { Input, Popup } from '../../lib/custom-ui';
import { useForm } from '../../hooks';
import { isUsername } from '../../utils/validator';
import styles from './EditUsernameStep.module.css';
const createMessage = (error) => {
if (!error) {
return error;
}
switch (error.message) {
case 'Username already in use':
return {
type: 'error',
content: 'common.usernameAlreadyInUse',
};
case 'Invalid current password':
return {
type: 'error',
content: 'common.invalidCurrentPassword',
};
default:
return {
type: 'warning',
content: 'common.unknownError',
};
}
};
const EditUsernameStep = React.memo(
({ defaultData, username, isSubmitting, error, onUpdate, onMessageDismiss, onBack, onClose }) => {
const [t] = useTranslation();
const wasSubmitting = usePrevious(isSubmitting);
const [data, handleFieldChange, setData] = useForm({
username: '',
currentPassword: '',
...defaultData,
});
const message = useMemo(() => createMessage(error), [error]);
const [focusCurrentPasswordFieldState, focusCurrentPasswordField] = useToggle();
const usernameField = useRef(null);
const currentPasswordField = useRef(null);
const handleSubmit = useCallback(() => {
const cleanData = {
...data,
username: data.username.trim() || null,
};
if (cleanData.username && !isUsername(cleanData.username)) {
usernameField.current.select();
return;
}
if (cleanData.username === username) {
onClose();
return;
}
if (!cleanData.currentPassword) {
currentPasswordField.current.focus();
return;
}
onUpdate(cleanData);
}, [username, onUpdate, onClose, data]);
useEffect(() => {
usernameField.current.select();
}, []);
useEffect(() => {
if (wasSubmitting && !isSubmitting) {
if (error) {
switch (error.message) {
case 'Username already in use':
usernameField.current.select();
break;
case 'Invalid current password':
setData((prevData) => ({
...prevData,
currentPassword: '',
}));
focusCurrentPasswordField();
break;
default:
}
} else {
onClose();
}
}
}, [isSubmitting, wasSubmitting, error, onClose, setData, focusCurrentPasswordField]);
useDidUpdate(() => {
currentPasswordField.current.focus();
}, [focusCurrentPasswordFieldState]);
return (
<>
<Popup.Header onBack={onBack}>
{t('common.editUsername', {
context: 'title',
})}
</Popup.Header>
<Popup.Content>
{message && (
<Message
// eslint-disable-next-line react/jsx-props-no-spreading
{...{
[message.type]: true,
}}
visible
content={t(message.content)}
onDismiss={onMessageDismiss}
/>
)}
<Form onSubmit={handleSubmit}>
<div className={styles.text}>{t('common.newUsername')}</div>
<Input
fluid
ref={usernameField}
name="username"
value={data.username}
placeholder={username}
className={styles.field}
onChange={handleFieldChange}
/>
{data.username.trim() !== (username || '') && (
<>
<div className={styles.text}>{t('common.currentPassword')}</div>
<Input.Password
fluid
ref={currentPasswordField}
name="currentPassword"
value={data.currentPassword}
className={styles.field}
onChange={handleFieldChange}
/>
</>
)}
<Button
positive
content={t('action.save')}
loading={isSubmitting}
disabled={isSubmitting}
/>
</Form>
</Popup.Content>
</>
);
},
);
EditUsernameStep.propTypes = {
defaultData: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
username: PropTypes.string,
isSubmitting: PropTypes.bool.isRequired,
error: PropTypes.object, // eslint-disable-line react/forbid-prop-types
onUpdate: PropTypes.func.isRequired,
onMessageDismiss: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
EditUsernameStep.defaultProps = {
username: undefined,
error: undefined,
};
export default EditUsernameStep;

View file

@ -0,0 +1,10 @@
.field {
margin-bottom: 8px;
}
.text {
color: #444444;
font-size: 12px;
font-weight: bold;
padding-bottom: 6px;
}

View file

@ -7,6 +7,7 @@ import { Popup } from '../../lib/custom-ui';
import { useSteps } from '../../hooks'; import { useSteps } from '../../hooks';
import EditNameStep from './EditNameStep'; import EditNameStep from './EditNameStep';
import EditUsernameStep from './EditUsernameStep';
import EditAvatarStep from './EditAvatarStep'; import EditAvatarStep from './EditAvatarStep';
import EditEmailStep from './EditEmailStep'; import EditEmailStep from './EditEmailStep';
import EditPasswordStep from './EditPasswordStep'; import EditPasswordStep from './EditPasswordStep';
@ -15,6 +16,7 @@ import styles from './UserPopup.module.css';
const StepTypes = { const StepTypes = {
EDIT_NAME: 'EDIT_NAME', EDIT_NAME: 'EDIT_NAME',
EDIT_USERNAME: 'EDIT_USERNAME',
EDIT_AVATAR: 'EDIT_AVATAR', EDIT_AVATAR: 'EDIT_AVATAR',
EDIT_EMAIL: 'EDIT_EMAIL', EDIT_EMAIL: 'EDIT_EMAIL',
EDIT_PASSWORD: 'EDIT_PASSWORD', EDIT_PASSWORD: 'EDIT_PASSWORD',
@ -24,12 +26,16 @@ const UserStep = React.memo(
({ ({
email, email,
name, name,
username,
avatar, avatar,
isAvatarUploading, isAvatarUploading,
usernameUpdateForm,
emailUpdateForm, emailUpdateForm,
passwordUpdateForm, passwordUpdateForm,
onUpdate, onUpdate,
onAvatarUpload, onAvatarUpload,
onUsernameUpdate,
onUsernameUpdateMessageDismiss,
onEmailUpdate, onEmailUpdate,
onEmailUpdateMessageDismiss, onEmailUpdateMessageDismiss,
onPasswordUpdate, onPasswordUpdate,
@ -48,6 +54,10 @@ const UserStep = React.memo(
openStep(StepTypes.EDIT_AVATAR); openStep(StepTypes.EDIT_AVATAR);
}, [openStep]); }, [openStep]);
const handleUsernameEditClick = useCallback(() => {
openStep(StepTypes.EDIT_USERNAME);
}, [openStep]);
const handleEmailEditClick = useCallback(() => { const handleEmailEditClick = useCallback(() => {
openStep(StepTypes.EDIT_EMAIL); openStep(StepTypes.EDIT_EMAIL);
}, [openStep]); }, [openStep]);
@ -93,6 +103,19 @@ const UserStep = React.memo(
onBack={handleBack} onBack={handleBack}
/> />
); );
case StepTypes.EDIT_USERNAME:
return (
<EditUsernameStep
defaultData={usernameUpdateForm.data}
username={username}
isSubmitting={usernameUpdateForm.isSubmitting}
error={usernameUpdateForm.error}
onUpdate={onUsernameUpdate}
onMessageDismiss={onUsernameUpdateMessageDismiss}
onBack={handleBack}
onClose={onClose}
/>
);
case StepTypes.EDIT_EMAIL: case StepTypes.EDIT_EMAIL:
return ( return (
<EditEmailStep <EditEmailStep
@ -124,7 +147,11 @@ const UserStep = React.memo(
return ( return (
<> <>
<Popup.Header>{name}</Popup.Header> <Popup.Header>
{t('common.userActions', {
context: 'title',
})}
</Popup.Header>
<Popup.Content> <Popup.Content>
<Menu secondary vertical className={styles.menu}> <Menu secondary vertical className={styles.menu}>
<Menu.Item className={styles.menuItem} onClick={handleNameEditClick}> <Menu.Item className={styles.menuItem} onClick={handleNameEditClick}>
@ -137,6 +164,11 @@ const UserStep = React.memo(
context: 'title', context: 'title',
})} })}
</Menu.Item> </Menu.Item>
<Menu.Item className={styles.menuItem} onClick={handleUsernameEditClick}>
{t('action.editUsername', {
context: 'title',
})}
</Menu.Item>
<Menu.Item className={styles.menuItem} onClick={handleEmailEditClick}> <Menu.Item className={styles.menuItem} onClick={handleEmailEditClick}>
{t('action.editEmail', { {t('action.editEmail', {
context: 'title', context: 'title',
@ -162,14 +194,18 @@ const UserStep = React.memo(
UserStep.propTypes = { UserStep.propTypes = {
email: PropTypes.string.isRequired, email: PropTypes.string.isRequired,
name: PropTypes.string.isRequired, name: PropTypes.string.isRequired,
username: PropTypes.string,
avatar: PropTypes.string, avatar: PropTypes.string,
isAvatarUploading: PropTypes.bool.isRequired, isAvatarUploading: PropTypes.bool.isRequired,
/* eslint-disable react/forbid-prop-types */ /* eslint-disable react/forbid-prop-types */
usernameUpdateForm: PropTypes.object.isRequired,
emailUpdateForm: PropTypes.object.isRequired, emailUpdateForm: PropTypes.object.isRequired,
passwordUpdateForm: PropTypes.object.isRequired, passwordUpdateForm: PropTypes.object.isRequired,
/* eslint-enable react/forbid-prop-types */ /* eslint-enable react/forbid-prop-types */
onUpdate: PropTypes.func.isRequired, onUpdate: PropTypes.func.isRequired,
onAvatarUpload: PropTypes.func.isRequired, onAvatarUpload: PropTypes.func.isRequired,
onUsernameUpdate: PropTypes.func.isRequired,
onUsernameUpdateMessageDismiss: PropTypes.func.isRequired,
onEmailUpdate: PropTypes.func.isRequired, onEmailUpdate: PropTypes.func.isRequired,
onEmailUpdateMessageDismiss: PropTypes.func.isRequired, onEmailUpdateMessageDismiss: PropTypes.func.isRequired,
onPasswordUpdate: PropTypes.func.isRequired, onPasswordUpdate: PropTypes.func.isRequired,
@ -179,6 +215,7 @@ UserStep.propTypes = {
}; };
UserStep.defaultProps = { UserStep.defaultProps = {
username: undefined,
avatar: undefined, avatar: undefined,
}; };

View file

@ -7,7 +7,7 @@ import DeletePopup from '../DeletePopup';
import styles from './Item.module.css'; import styles from './Item.module.css';
const Item = React.memo(({ name, email, isAdmin, onUpdate, onDelete }) => { const Item = React.memo(({ name, username, email, isAdmin, onUpdate, onDelete }) => {
const [t] = useTranslation(); const [t] = useTranslation();
const handleIsAdminChange = useCallback(() => { const handleIsAdminChange = useCallback(() => {
@ -19,6 +19,7 @@ const Item = React.memo(({ name, email, isAdmin, onUpdate, onDelete }) => {
return ( return (
<Table.Row> <Table.Row>
<Table.Cell>{name}</Table.Cell> <Table.Cell>{name}</Table.Cell>
<Table.Cell>{username || '-'}</Table.Cell>
<Table.Cell>{email}</Table.Cell> <Table.Cell>{email}</Table.Cell>
<Table.Cell collapsing> <Table.Cell collapsing>
<Radio toggle checked={isAdmin} onChange={handleIsAdminChange} /> <Radio toggle checked={isAdmin} onChange={handleIsAdminChange} />
@ -41,10 +42,15 @@ const Item = React.memo(({ name, email, isAdmin, onUpdate, onDelete }) => {
Item.propTypes = { Item.propTypes = {
name: PropTypes.string.isRequired, name: PropTypes.string.isRequired,
username: PropTypes.string,
email: PropTypes.string.isRequired, email: PropTypes.string.isRequired,
isAdmin: PropTypes.bool.isRequired, isAdmin: PropTypes.bool.isRequired,
onUpdate: PropTypes.func.isRequired, onUpdate: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired,
}; };
Item.defaultProps = {
username: undefined,
};
export default Item; export default Item;

View file

@ -34,8 +34,9 @@ const UsersModal = React.memo(({ items, onUpdate, onDelete, onClose }) => {
<Table basic="very"> <Table basic="very">
<Table.Header> <Table.Header>
<Table.Row> <Table.Row>
<Table.HeaderCell>{t('common.name')}</Table.HeaderCell> <Table.HeaderCell width={4}>{t('common.name')}</Table.HeaderCell>
<Table.HeaderCell>{t('common.email')}</Table.HeaderCell> <Table.HeaderCell width={4}>{t('common.username')}</Table.HeaderCell>
<Table.HeaderCell width={4}>{t('common.email')}</Table.HeaderCell>
<Table.HeaderCell>{t('common.administrator')}</Table.HeaderCell> <Table.HeaderCell>{t('common.administrator')}</Table.HeaderCell>
<Table.HeaderCell /> <Table.HeaderCell />
</Table.Row> </Table.Row>
@ -45,6 +46,7 @@ const UsersModal = React.memo(({ items, onUpdate, onDelete, onClose }) => {
<Item <Item
key={item.id} key={item.id}
name={item.name} name={item.name}
username={item.username}
email={item.email} email={item.email}
isAdmin={item.isAdmin} isAdmin={item.isAdmin}
onUpdate={(data) => handleUpdate(item.id, data)} onUpdate={(data) => handleUpdate(item.id, data)}

View file

@ -34,6 +34,7 @@ export default {
USER_UPDATE: 'USER_UPDATE', USER_UPDATE: 'USER_UPDATE',
USER_EMAIL_UPDATE_ERROR_CLEAR: 'USER_EMAIL_UPDATE_ERROR_CLEAR', USER_EMAIL_UPDATE_ERROR_CLEAR: 'USER_EMAIL_UPDATE_ERROR_CLEAR',
USER_PASSWORD_UPDATE_ERROR_CLEAR: 'USER_PASSWORD_UPDATE_ERROR_CLEAR', USER_PASSWORD_UPDATE_ERROR_CLEAR: 'USER_PASSWORD_UPDATE_ERROR_CLEAR',
USER_USERNAME_UPDATE_ERROR_CLEAR: 'USER_USERNAME_UPDATE_ERROR_CLEAR',
USER_DELETE: 'USER_DELETE', USER_DELETE: 'USER_DELETE',
USER_TO_CARD_ADD: 'USER_TO_CARD_ADD', USER_TO_CARD_ADD: 'USER_TO_CARD_ADD',
USER_FROM_CARD_REMOVE: 'USER_FROM_CARD_REMOVE', USER_FROM_CARD_REMOVE: 'USER_FROM_CARD_REMOVE',
@ -56,6 +57,9 @@ export default {
USER_PASSWORD_UPDATE_REQUESTED: 'USER_PASSWORD_UPDATE_REQUESTED', USER_PASSWORD_UPDATE_REQUESTED: 'USER_PASSWORD_UPDATE_REQUESTED',
USER_PASSWORD_UPDATE_SUCCEEDED: 'USER_PASSWORD_UPDATE_SUCCEEDED', USER_PASSWORD_UPDATE_SUCCEEDED: 'USER_PASSWORD_UPDATE_SUCCEEDED',
USER_PASSWORD_UPDATE_FAILED: 'USER_PASSWORD_UPDATE_FAILED', USER_PASSWORD_UPDATE_FAILED: 'USER_PASSWORD_UPDATE_FAILED',
USER_USERNAME_UPDATE_REQUESTED: 'USER_USERNAME_UPDATE_REQUESTED',
USER_USERNAME_UPDATE_SUCCEEDED: 'USER_USERNAME_UPDATE_SUCCEEDED',
USER_USERNAME_UPDATE_FAILED: 'USER_USERNAME_UPDATE_FAILED',
USER_AVATAR_UPLOAD_REQUESTED: 'USER_AVATAR_UPLOAD_REQUESTED', USER_AVATAR_UPLOAD_REQUESTED: 'USER_AVATAR_UPLOAD_REQUESTED',
USER_AVATAR_UPLOAD_SUCCEEDED: 'USER_AVATAR_UPLOAD_SUCCEEDED', USER_AVATAR_UPLOAD_SUCCEEDED: 'USER_AVATAR_UPLOAD_SUCCEEDED',
USER_AVATAR_UPLOAD_FAILED: 'USER_AVATAR_UPLOAD_FAILED', USER_AVATAR_UPLOAD_FAILED: 'USER_AVATAR_UPLOAD_FAILED',

View file

@ -24,6 +24,8 @@ export default {
CURRENT_USER_EMAIL_UPDATE_ERROR_CLEAR: `${PREFIX}/CURRENT_USER_EMAIL_UPDATE_ERROR_CLEAR`, CURRENT_USER_EMAIL_UPDATE_ERROR_CLEAR: `${PREFIX}/CURRENT_USER_EMAIL_UPDATE_ERROR_CLEAR`,
CURRENT_USER_PASSWORD_UPDATE: `${PREFIX}/CURRENT_USER_PASSWORD_UPDATE`, CURRENT_USER_PASSWORD_UPDATE: `${PREFIX}/CURRENT_USER_PASSWORD_UPDATE`,
CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR: `${PREFIX}/CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR`, CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR: `${PREFIX}/CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR`,
CURRENT_USER_USERNAME_UPDATE: `${PREFIX}/CURRENT_USER_USERNAME_UPDATE`,
CURRENT_USER_USERNAME_UPDATE_ERROR_CLEAR: `${PREFIX}/CURRENT_USER_USERNAME_UPDATE_ERROR_CLEAR`,
CURRENT_USER_AVATAR_UPLOAD: `${PREFIX}/CURRENT_USER_AVATAR_UPLOAD`, CURRENT_USER_AVATAR_UPLOAD: `${PREFIX}/CURRENT_USER_AVATAR_UPLOAD`,
USER_DELETE: `${PREFIX}/USER_DELETE`, USER_DELETE: `${PREFIX}/USER_DELETE`,
USER_TO_CARD_ADD: `${PREFIX}/USER_TO_CARD_ADD`, USER_TO_CARD_ADD: `${PREFIX}/USER_TO_CARD_ADD`,

View file

@ -5,12 +5,14 @@ import { currentUserSelector, notificationsForCurrentUserSelector } from '../sel
import { import {
clearCurrentUserEmailUpdateError, clearCurrentUserEmailUpdateError,
clearCurrentUserPasswordUpdateError, clearCurrentUserPasswordUpdateError,
clearCurrentUserUsernameUpdateError,
deleteNotification, deleteNotification,
logout, logout,
openUsersModal, openUsersModal,
updateCurrentUser, updateCurrentUser,
updateCurrentUserEmail, updateCurrentUserEmail,
updateCurrentUserPassword, updateCurrentUserPassword,
updateCurrentUserUsername,
uploadCurrentUserAvatar, uploadCurrentUserAvatar,
} from '../actions/entry'; } from '../actions/entry';
import Header from '../components/Header'; import Header from '../components/Header';
@ -33,6 +35,8 @@ const mapDispatchToProps = (dispatch) =>
onNotificationDelete: deleteNotification, onNotificationDelete: deleteNotification,
onUserUpdate: updateCurrentUser, onUserUpdate: updateCurrentUser,
onUserAvatarUpload: uploadCurrentUserAvatar, onUserAvatarUpload: uploadCurrentUserAvatar,
onUserUsernameUpdate: updateCurrentUserUsername,
onUserUsernameUpdateMessageDismiss: clearCurrentUserUsernameUpdateError,
onUserEmailUpdate: updateCurrentUserEmail, onUserEmailUpdate: updateCurrentUserEmail,
onUserEmailUpdateMessageDismiss: clearCurrentUserEmailUpdateError, onUserEmailUpdateMessageDismiss: clearCurrentUserEmailUpdateError,
onUserPasswordUpdate: updateCurrentUserPassword, onUserPasswordUpdate: updateCurrentUserPassword,

View file

@ -58,6 +58,9 @@ export default {
editPassword_title: 'Edit Password', editPassword_title: 'Edit Password',
editProject_title: 'Edit Project', editProject_title: 'Edit Project',
editTimer_title: 'Edit Timer', editTimer_title: 'Edit Timer',
editUsername_title: 'Edit Username',
email: 'E-mail',
emailAlreadyInUse: 'E-mail already in use',
enterCardTitle: 'Enter card title...', enterCardTitle: 'Enter card title...',
enterDescription: 'Enter description...', enterDescription: 'Enter description...',
enterListTitle: 'Enter list title...', enterListTitle: 'Enter list title...',
@ -74,10 +77,12 @@ export default {
name: 'Name', name: 'Name',
newEmail: 'New e-mail', newEmail: 'New e-mail',
newPassword: 'New password', newPassword: 'New password',
newUsername: 'New username',
noConnectionToServer: 'No connection to server', noConnectionToServer: 'No connection to server',
notifications: 'Notifications', notifications: 'Notifications',
noUnreadNotifications: 'No unread notifications', noUnreadNotifications: 'No unread notifications',
openBoard_title: 'Open Board', openBoard_title: 'Open Board',
optional_inline: 'optional',
projectNotFound_title: 'Project Not Found', projectNotFound_title: 'Project Not Found',
refreshPageToLoadLastDataAndReceiveUpdates: refreshPageToLoadLastDataAndReceiveUpdates:
'<0>Refresh the page</0> to load last data<br />and receive updates', '<0>Refresh the page</0> to load last data<br />and receive updates',
@ -88,12 +93,14 @@ export default {
time: 'Time', time: 'Time',
timer: 'Timer', timer: 'Timer',
title: 'Title', title: 'Title',
userActions_title: 'User Actions',
userAddedThisCardToList: '<0>{{user}}</0><1> added this card to {{list}}</1>', userAddedThisCardToList: '<0>{{user}}</0><1> added this card to {{list}}</1>',
userIsAlreadyExist: 'User is already exist',
userLeftNewCommentToCard: '{{user}} left a new comment «{{comment}}» to <2>{{card}}</2>', userLeftNewCommentToCard: '{{user}} left a new comment «{{comment}}» to <2>{{card}}</2>',
userMovedCardFromListToList: '{{user}} moved <2>{{card}}</2> from {{fromList}} to {{toList}}', userMovedCardFromListToList: '{{user}} moved <2>{{card}}</2> from {{fromList}} to {{toList}}',
userMovedThisCardFromListToList: userMovedThisCardFromListToList:
'<0>{{user}}</0><1> moved this card from {{fromList}} to {{toList}}</1>', '<0>{{user}}</0><1> moved this card from {{fromList}} to {{toList}}</1>',
username: 'Username',
usernameAlreadyInUse: 'Username already in use',
users: 'Users', users: 'Users',
writeComment: 'Write a comment...', writeComment: 'Write a comment...',
}, },
@ -137,6 +144,7 @@ export default {
editTask_title: 'Edit Task', editTask_title: 'Edit Task',
editTimer_title: 'Edit Timer', editTimer_title: 'Edit Timer',
editTitle_title: 'Edit Title', editTitle_title: 'Edit Title',
editUsername_title: 'Edit Username',
logOut_title: 'Log Out', logOut_title: 'Log Out',
remove: 'Remove', remove: 'Remove',
removeFromProject: 'Remove from project', removeFromProject: 'Remove from project',

View file

@ -1,8 +1,8 @@
export default { export default {
translation: { translation: {
common: { common: {
email: 'E-mail', emailOrUsername: 'E-mail or username',
emailDoesNotExist: 'E-mail does not exist', invalidEmailOrUsername: 'Invalid e-mail or username',
invalidPassword: 'Invalid password', invalidPassword: 'Invalid password',
logInToPlanka: 'Log in to Planka', logInToPlanka: 'Log in to Planka',
noInternetConnection: 'No internet connection', noInternetConnection: 'No internet connection',

View file

@ -62,6 +62,9 @@ export default {
editPassword: 'Изменение пароля', editPassword: 'Изменение пароля',
editProject: 'Изменение проекта', editProject: 'Изменение проекта',
editTimer: 'Изменение таймера', editTimer: 'Изменение таймера',
editUsername: 'Изменение имени пользователя',
email: 'E-mail',
emailAlreadyInUse: 'E-mail уже занят',
enterCardTitle: 'Введите заголовок для этой карточки...', enterCardTitle: 'Введите заголовок для этой карточки...',
enterDescription: 'Введите описание...', enterDescription: 'Введите описание...',
enterListTitle: 'Введите заголовок списка...', enterListTitle: 'Введите заголовок списка...',
@ -78,10 +81,12 @@ export default {
name: 'Имя', name: 'Имя',
newEmail: 'Новый e-mail', newEmail: 'Новый e-mail',
newPassword: 'Новый пароль', newPassword: 'Новый пароль',
newUsername: 'Новое имя пользователя',
noConnectionToServer: 'Нет соединения с сервером', noConnectionToServer: 'Нет соединения с сервером',
notifications: 'Уведомления', notifications: 'Уведомления',
noUnreadNotifications: 'Уведомлений нет', noUnreadNotifications: 'Уведомлений нет',
openBoard: 'Откройте доску', openBoard: 'Откройте доску',
optional_inline: 'необязательно',
projectNotFound: 'Доска не найдена', projectNotFound: 'Доска не найдена',
refreshPageToLoadLastDataAndReceiveUpdates: refreshPageToLoadLastDataAndReceiveUpdates:
'<0>Обновите страницу</0>, чтобы загрузить<br />актуальные данные и получать обновления', '<0>Обновите страницу</0>, чтобы загрузить<br />актуальные данные и получать обновления',
@ -92,13 +97,15 @@ export default {
time: 'Время', time: 'Время',
timer: 'Таймер', timer: 'Таймер',
title: 'Название', title: 'Название',
userActions_title: 'Действия с пользователем',
userAddedThisCardToList: '<0>{{user}}</0><1> добавил(а) эту карточку в {{list}}</1>', userAddedThisCardToList: '<0>{{user}}</0><1> добавил(а) эту карточку в {{list}}</1>',
userIsAlreadyExist: 'Пользователь уже существует',
userLeftNewCommentToCard: '{{user}} оставил(а) комментарий «{{comment}}» к <2>{{card}}</2>', userLeftNewCommentToCard: '{{user}} оставил(а) комментарий «{{comment}}» к <2>{{card}}</2>',
userMovedCardFromListToList: userMovedCardFromListToList:
'{{user}} переместил(а) <2>{{card}}</2> из {{fromList}} в {{toList}}', '{{user}} переместил(а) <2>{{card}}</2> из {{fromList}} в {{toList}}',
userMovedThisCardFromListToList: userMovedThisCardFromListToList:
'<0>{{user}}</0><1> переместил(а) эту карточку из {{fromList}} в {{toList}}</1>', '<0>{{user}}</0><1> переместил(а) эту карточку из {{fromList}} в {{toList}}</1>',
username: 'Имя пользователя',
usernameAlreadyInUse: 'Имя пользователя уже занято',
users: 'Пользователи', users: 'Пользователи',
writeComment: 'Напишите комментарий...', writeComment: 'Напишите комментарий...',
}, },
@ -138,6 +145,7 @@ export default {
editTask: 'Изменить задачу', editTask: 'Изменить задачу',
editTimer: 'Изменить таймер', editTimer: 'Изменить таймер',
editTitle: 'Изменить название', editTitle: 'Изменить название',
editUsername_title: 'Изменить имя пользователя',
logOut: 'Выйти', logOut: 'Выйти',
remove: 'Убрать', remove: 'Убрать',
removeFromProject: 'Удалить из проекта', removeFromProject: 'Удалить из проекта',

View file

@ -1,8 +1,8 @@
export default { export default {
translation: { translation: {
common: { common: {
email: 'E-mail', emailOrUsername: 'E-mail или имя пользователя',
emailDoesNotExist: 'Неверный e-mail', invalidEmailOrUsername: 'Неверный e-mail или имя пользователя',
invalidPassword: 'Неверный пароль', invalidPassword: 'Неверный пароль',
logInToPlanka: 'Вход в Planka', logInToPlanka: 'Вход в Planka',
noInternetConnection: 'Нет соединения', noInternetConnection: 'Нет соединения',

View file

@ -20,6 +20,15 @@ const DEFAULT_PASSWORD_UPDATE_FORM = {
error: null, error: null,
}; };
const DEFAULT_USERNAME_UPDATE_FORM = {
data: {
username: '',
currentPassword: '',
},
isSubmitting: false,
error: null,
};
export default class extends Model { export default class extends Model {
static modelName = 'User'; static modelName = 'User';
@ -41,6 +50,9 @@ export default class extends Model {
passwordUpdateForm: attr({ passwordUpdateForm: attr({
getDefault: () => DEFAULT_PASSWORD_UPDATE_FORM, getDefault: () => DEFAULT_PASSWORD_UPDATE_FORM,
}), }),
usernameUpdateForm: attr({
getDefault: () => DEFAULT_USERNAME_UPDATE_FORM,
}),
}; };
static reducer({ type, payload }, User) { static reducer({ type, payload }, User) {
@ -92,6 +104,18 @@ export default class extends Model {
break; break;
} }
case ActionTypes.USER_USERNAME_UPDATE_ERROR_CLEAR: {
const userModel = User.withId(payload.id);
userModel.update({
usernameUpdateForm: {
...userModel.usernameUpdateForm,
error: null,
},
});
break;
}
case ActionTypes.USER_DELETE: case ActionTypes.USER_DELETE:
User.withId(payload.id).deleteWithRelated(); User.withId(payload.id).deleteWithRelated();
@ -167,6 +191,40 @@ export default class extends Model {
break; break;
} }
case ActionTypes.USER_USERNAME_UPDATE_REQUESTED: {
const userModel = User.withId(payload.id);
userModel.update({
usernameUpdateForm: {
...userModel.usernameUpdateForm,
data: payload.data,
isSubmitting: true,
},
});
break;
}
case ActionTypes.USER_USERNAME_UPDATE_SUCCEEDED: {
User.withId(payload.id).update({
username: payload.username,
usernameUpdateForm: DEFAULT_USERNAME_UPDATE_FORM,
});
break;
}
case ActionTypes.USER_USERNAME_UPDATE_FAILED: {
const userModel = User.withId(payload.id);
userModel.update({
usernameUpdateForm: {
...userModel.usernameUpdateForm,
isSubmitting: false,
error: payload.error,
},
});
break;
}
case ActionTypes.USER_AVATAR_UPLOAD_REQUESTED: case ActionTypes.USER_AVATAR_UPLOAD_REQUESTED:
User.withId(payload.id).update({ User.withId(payload.id).update({
isAvatarUploading: true, isAvatarUploading: true,

View file

@ -2,7 +2,7 @@ import ActionTypes from '../../constants/ActionTypes';
const initialState = { const initialState = {
data: { data: {
email: '', emailOrUsername: '',
password: '', password: '',
}, },
isSubmitting: false, isSubmitting: false,

View file

@ -4,6 +4,7 @@ const initialState = {
data: { data: {
email: '', email: '',
name: '', name: '',
username: '',
}, },
isSubmitting: false, isSubmitting: false,
error: null, error: null,

View file

@ -20,6 +20,9 @@ import {
updateUserPasswordSucceeded, updateUserPasswordSucceeded,
updateUserRequested, updateUserRequested,
updateUserSucceeded, updateUserSucceeded,
updateUserUsernameFailed,
updateUserUsernameRequested,
updateUserUsernameSucceeded,
uploadUserAvatarFailed, uploadUserAvatarFailed,
uploadUserAvatarRequested, uploadUserAvatarRequested,
uploadUserAvatarSucceeded, uploadUserAvatarSucceeded,
@ -146,6 +149,30 @@ export function* updateUserPasswordRequest(id, data) {
} }
} }
export function* updateUserUsernameRequest(id, data) {
yield put(updateUserUsernameRequested(id, data));
try {
const { item } = yield call(request, api.updateUserUsername, id, data);
const action = updateUserUsernameSucceeded(id, item);
yield put(action);
return {
success: true,
payload: action.payload,
};
} catch (error) {
const action = updateUserUsernameFailed(id, error);
yield put(action);
return {
success: false,
payload: action.payload,
};
}
}
export function* uploadUserAvatarRequest(id, file) { export function* uploadUserAvatarRequest(id, file) {
yield put(uploadUserAvatarRequested(id)); yield put(uploadUserAvatarRequested(id));

View file

@ -8,6 +8,7 @@ import {
updateUserEmailRequest, updateUserEmailRequest,
updateUserPasswordRequest, updateUserPasswordRequest,
updateUserRequest, updateUserRequest,
updateUserUsernameRequest,
uploadUserAvatarRequest, uploadUserAvatarRequest,
} from '../requests'; } from '../requests';
import { currentUserIdSelector, pathSelector } from '../../../selectors'; import { currentUserIdSelector, pathSelector } from '../../../selectors';
@ -17,6 +18,7 @@ import {
clearUserCreateError, clearUserCreateError,
clearUserEmailUpdateError, clearUserEmailUpdateError,
clearUserPasswordUpdateError, clearUserPasswordUpdateError,
clearUserUsernameUpdateError,
createUser, createUser,
deleteUser, deleteUser,
updateUser, updateUser,
@ -84,6 +86,26 @@ export function* clearCurrentUserPasswordUpdateErrorService() {
yield call(clearUserPasswordUpdateErrorService, id); yield call(clearUserPasswordUpdateErrorService, id);
} }
export function* updateUserUsernameService(id, data) {
yield call(updateUserUsernameRequest, id, data);
}
export function* updateCurrentUserUsernameService(data) {
const id = yield select(currentUserIdSelector);
yield call(updateUserUsernameService, id, data);
}
export function* clearUserUsernameUpdateErrorService(id) {
yield put(clearUserUsernameUpdateError(id));
}
export function* clearCurrentUserUsernameUpdateErrorService() {
const id = yield select(currentUserIdSelector);
yield call(clearUserUsernameUpdateErrorService, id);
}
export function* uploadUserAvatarService(id, file) { export function* uploadUserAvatarService(id, file) {
yield call(uploadUserAvatarRequest, id, file); yield call(uploadUserAvatarRequest, id, file);
} }

View file

@ -6,6 +6,7 @@ import {
addUserToFilterInCurrentBoardService, addUserToFilterInCurrentBoardService,
clearCurrentUserEmailUpdateErrorService, clearCurrentUserEmailUpdateErrorService,
clearCurrentUserPasswordUpdateErrorService, clearCurrentUserPasswordUpdateErrorService,
clearCurrentUserUsernameUpdateErrorService,
clearUserCreateErrorService, clearUserCreateErrorService,
createUserService, createUserService,
deleteUserService, deleteUserService,
@ -16,6 +17,7 @@ import {
updateCurrentUserEmailService, updateCurrentUserEmailService,
updateCurrentUserPasswordService, updateCurrentUserPasswordService,
updateCurrentUserService, updateCurrentUserService,
updateCurrentUserUsernameService,
uploadCurrentUserAvatarService, uploadCurrentUserAvatarService,
} from '../services'; } from '../services';
import EntryActionTypes from '../../../constants/EntryActionTypes'; import EntryActionTypes from '../../../constants/EntryActionTypes';
@ -42,6 +44,12 @@ export default function* () {
takeLatest(EntryActionTypes.CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR, () => takeLatest(EntryActionTypes.CURRENT_USER_PASSWORD_UPDATE_ERROR_CLEAR, () =>
clearCurrentUserPasswordUpdateErrorService(), clearCurrentUserPasswordUpdateErrorService(),
), ),
takeLatest(EntryActionTypes.CURRENT_USER_USERNAME_UPDATE, ({ payload: { data } }) =>
updateCurrentUserUsernameService(data),
),
takeLatest(EntryActionTypes.CURRENT_USER_USERNAME_UPDATE_ERROR_CLEAR, () =>
clearCurrentUserUsernameUpdateErrorService(),
),
takeLatest(EntryActionTypes.CURRENT_USER_AVATAR_UPLOAD, ({ payload: { file } }) => takeLatest(EntryActionTypes.CURRENT_USER_AVATAR_UPLOAD, ({ payload: { file } }) =>
uploadCurrentUserAvatarService(file), uploadCurrentUserAvatarService(file),
), ),

View file

@ -0,0 +1,6 @@
const USERNAME_REGEX = /^[a-zA-Z0-9]+(_?[a-zA-Z0-9])*$/;
// eslint-disable-next-line import/prefer-default-export
export const isUsername = (string) => {
return string.length >= 3 && string.length <= 16 && USERNAME_REGEX.test(string);
};

View file

@ -1,20 +1,24 @@
const bcrypt = require('bcrypt'); const bcrypt = require('bcrypt');
const validator = require('validator');
const Errors = { const Errors = {
EMAIL_NOT_EXIST: { INVALID_EMAIL_OR_USERNAME: {
unauthorized: 'Email does not exist', invalidEmailOrUsername: 'Invalid email or username',
}, },
PASSWORD_NOT_VALID: { INVALID_PASSWORD: {
unauthorized: 'Password is not valid', invalidPassword: 'Invalid password',
}, },
}; };
module.exports = { module.exports = {
inputs: { inputs: {
email: { emailOrUsername: {
type: 'string', type: 'string',
custom: (value) =>
value.includes('@')
? validator.isEmail(value)
: value.length >= 3 && value.length <= 16 && /^[a-zA-Z0-9]+(_?[a-zA-Z0-9])*$/.test(value),
required: true, required: true,
isEmail: true,
}, },
password: { password: {
type: 'string', type: 'string',
@ -23,22 +27,23 @@ module.exports = {
}, },
exits: { exits: {
unauthorized: { invalidEmailOrUsername: {
responseType: 'unauthorized',
},
invalidPassword: {
responseType: 'unauthorized', responseType: 'unauthorized',
}, },
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const user = await sails.helpers.getUser({ const user = await sails.helpers.getUserByEmailOrUsername(inputs.emailOrUsername);
email: inputs.email.toLowerCase(),
});
if (!user) { if (!user) {
throw Errors.EMAIL_NOT_EXIST; throw Errors.INVALID_EMAIL_OR_USERNAME;
} }
if (!bcrypt.compareSync(inputs.password, user.password)) { if (!bcrypt.compareSync(inputs.password, user.password)) {
throw Errors.PASSWORD_NOT_VALID; throw Errors.INVALID_PASSWORD;
} }
return exits.success({ return exits.success({

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
}; };
@ -18,7 +18,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -28,7 +28,7 @@ module.exports = {
const { project } = await sails.helpers const { project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
PROJECT_NOT_FOUND: { PROJECT_NOT_FOUND: {
notFound: 'Project is not found', projectNotFound: 'Project not found',
}, },
}; };
@ -22,7 +22,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { projectNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
BOARD_NOT_FOUND: { BOARD_NOT_FOUND: {
notFound: 'Board is not found', boardNotFound: 'Board not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { boardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
BOARD_NOT_FOUND: { BOARD_NOT_FOUND: {
notFound: 'Board is not found', boardNotFound: 'Board not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { boardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -29,7 +29,7 @@ module.exports = {
const { board, project } = await sails.helpers const { board, project } = await sails.helpers
.getBoardToProjectPath(inputs.id) .getBoardToProjectPath(inputs.id)
.intercept('notFound', () => Errors.BOARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.BOARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,
@ -64,7 +64,7 @@ module.exports = {
{}, {},
); );
cards.map(card => ({ cards.map((card) => ({
...card, ...card,
isSubscribed: isSubscribedByCardId[card.id] || false, isSubscribed: isSubscribedByCardId[card.id] || false,
})); }));

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
BOARD_NOT_FOUND: { BOARD_NOT_FOUND: {
notFound: 'Board is not found', boardNotFound: 'Board not found',
}, },
}; };
@ -21,7 +21,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { boardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,12 +1,12 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
LABEL_NOT_FOUND: { LABEL_NOT_FOUND: {
notFound: 'Label is not found', labelNotFound: 'Label not found',
}, },
CARD_LABEL_EXIST: { LABEL_ALREADY_IN_CARD: {
conflict: 'Card label is already exist', labelAlreadyInCard: 'Label already in card',
}, },
}; };
@ -25,10 +25,13 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
conflict: { labelNotFound: {
responseType: 'notFound',
},
labelAlreadyInCard: {
responseType: 'conflict', responseType: 'conflict',
}, },
}, },
@ -38,7 +41,7 @@ module.exports = {
const { card, project } = await sails.helpers const { card, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,
@ -60,7 +63,7 @@ module.exports = {
const cardLabel = await sails.helpers const cardLabel = await sails.helpers
.createCardLabel(card, label, this.req) .createCardLabel(card, label, this.req)
.intercept('conflict', () => Errors.CARD_LABEL_EXIST); .intercept('labelAlreadyInCard', () => Errors.LABEL_ALREADY_IN_CARD);
return exits.success({ return exits.success({
item: cardLabel, item: cardLabel,

View file

@ -1,9 +1,9 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
CARD_LABEL_NOT_FOUND: { LABEL_NOT_IN_CARD: {
notFound: 'Card label is not found', labelNotInCard: 'Label not in card',
}, },
}; };
@ -22,7 +22,10 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound',
},
labelNotInCard: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -32,7 +35,7 @@ module.exports = {
const { board, project } = await sails.helpers const { board, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,
@ -49,13 +52,13 @@ module.exports = {
}); });
if (!cardLabel) { if (!cardLabel) {
throw Errors.CARD_LABEL_NOT_FOUND; throw Errors.LABEL_NOT_IN_CARD;
} }
cardLabel = await sails.helpers.deleteCardLabel(cardLabel, board, this.req); cardLabel = await sails.helpers.deleteCardLabel(cardLabel, board, this.req);
if (!cardLabel) { if (!cardLabel) {
throw Errors.CARD_LABEL_NOT_FOUND; throw Errors.LABEL_NOT_IN_CARD;
} }
return exits.success({ return exits.success({

View file

@ -1,12 +1,12 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
CARD_MEMBERSHIP_EXIST: { USER_ALREADY_CARD_MEMBER: {
conflict: 'Card membership is already exist', userAlreadyCardMember: 'User already card member',
}, },
}; };
@ -25,10 +25,13 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
conflict: { userNotFound: {
responseType: 'notFound',
},
userAlreadyCardMember: {
responseType: 'conflict', responseType: 'conflict',
}, },
}, },
@ -38,7 +41,7 @@ module.exports = {
const { card, project } = await sails.helpers const { card, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
let isUserMemberForProject = await sails.helpers.isUserMemberForProject( let isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,
@ -57,7 +60,7 @@ module.exports = {
const cardMembership = await sails.helpers const cardMembership = await sails.helpers
.createCardMembership(card, inputs.userId, this.req) .createCardMembership(card, inputs.userId, this.req)
.intercept('conflict', () => Errors.CARD_MEMBERSHIP_EXIST); .intercept('userAlreadyCardMember', () => Errors.USER_ALREADY_CARD_MEMBER);
return exits.success({ return exits.success({
item: cardMembership, item: cardMembership,

View file

@ -1,9 +1,9 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
CARD_MEMBERSHIP_NOT_FOUND: { USER_NOT_CARD_MEMBER: {
notFound: 'Card membership is not found', userNotCardMember: 'User not card member',
}, },
}; };
@ -22,7 +22,10 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound',
},
userNotCardMember: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -32,7 +35,7 @@ module.exports = {
const { board, project } = await sails.helpers const { board, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,
@ -49,13 +52,13 @@ module.exports = {
}); });
if (!cardMembership) { if (!cardMembership) {
throw Errors.CARD_MEMBERSHIP_NOT_FOUND; throw Errors.USER_NOT_CARD_MEMBER;
} }
cardMembership = await sails.helpers.deleteCardMembership(cardMembership, board, this.req); cardMembership = await sails.helpers.deleteCardMembership(cardMembership, board, this.req);
if (!cardMembership) { if (!cardMembership) {
throw Errors.CARD_MEMBERSHIP_NOT_FOUND; throw Errors.USER_NOT_CARD_MEMBER;
} }
return exits.success({ return exits.success({

View file

@ -2,7 +2,7 @@ const moment = require('moment');
const Errors = { const Errors = {
LIST_NOT_FOUND: { LIST_NOT_FOUND: {
notFound: 'List is not found', listNotFound: 'List not found',
}, },
}; };
@ -28,11 +28,11 @@ module.exports = {
}, },
dueDate: { dueDate: {
type: 'string', type: 'string',
custom: value => moment(value, moment.ISO_8601, true).isValid(), custom: (value) => moment(value, moment.ISO_8601, true).isValid(),
}, },
timer: { timer: {
type: 'json', type: 'json',
custom: value => custom: (value) =>
_.isPlainObject(value) && _.isPlainObject(value) &&
_.size(value) === 2 && _.size(value) === 2 &&
(_.isNull(value.startedAt) || moment(value.startedAt, moment.ISO_8601, true).isValid()) && (_.isNull(value.startedAt) || moment(value.startedAt, moment.ISO_8601, true).isValid()) &&
@ -41,7 +41,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { listNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -51,7 +51,7 @@ module.exports = {
const { list, project } = await sails.helpers const { list, project } = await sails.helpers
.getListToProjectPath(inputs.listId) .getListToProjectPath(inputs.listId)
.intercept('notFound', () => Errors.LIST_NOT_FOUND); .intercept('pathNotFound', () => Errors.LIST_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -24,7 +24,7 @@ module.exports = {
const cardToProjectPath = await sails.helpers const cardToProjectPath = await sails.helpers
.getCardToProjectPath(inputs.id) .getCardToProjectPath(inputs.id)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
let { card } = cardToProjectPath; let { card } = cardToProjectPath;
const { project } = cardToProjectPath; const { project } = cardToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -24,7 +24,7 @@ module.exports = {
const { card, project } = await sails.helpers const { card, project } = await sails.helpers
.getCardToProjectPath(inputs.id) .getCardToProjectPath(inputs.id)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -2,10 +2,10 @@ const moment = require('moment');
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
LIST_NOT_FOUND: { LIST_NOT_FOUND: {
notFound: 'List is not found', listNotFound: 'List not found',
}, },
}; };
@ -34,12 +34,12 @@ module.exports = {
}, },
dueDate: { dueDate: {
type: 'string', type: 'string',
custom: value => moment(value, moment.ISO_8601, true).isValid(), custom: (value) => moment(value, moment.ISO_8601, true).isValid(),
allowNull: true, allowNull: true,
}, },
timer: { timer: {
type: 'json', type: 'json',
custom: value => custom: (value) =>
_.isPlainObject(value) && _.isPlainObject(value) &&
_.size(value) === 2 && _.size(value) === 2 &&
(_.isNull(value.startedAt) || moment(value.startedAt, moment.ISO_8601, true).isValid()) && (_.isNull(value.startedAt) || moment(value.startedAt, moment.ISO_8601, true).isValid()) &&
@ -51,7 +51,10 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound',
},
listNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -61,7 +64,7 @@ module.exports = {
const cardToProjectPath = await sails.helpers const cardToProjectPath = await sails.helpers
.getCardToProjectPath(inputs.id) .getCardToProjectPath(inputs.id)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
let { card } = cardToProjectPath; let { card } = cardToProjectPath;
const { list, project } = cardToProjectPath; const { list, project } = cardToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
}; };
@ -18,7 +18,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -28,7 +28,7 @@ module.exports = {
const { card, project } = await sails.helpers const { card, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
COMMENT_ACTION_NOT_FOUND: { COMMENT_ACTION_NOT_FOUND: {
notFound: 'Comment action is not found', commentActionNotFound: 'Comment action not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { commentActionNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -33,7 +33,7 @@ module.exports = {
const actionToProjectPath = await sails.helpers const actionToProjectPath = await sails.helpers
.getActionToProjectPath(criteria) .getActionToProjectPath(criteria)
.intercept('notFound', () => Errors.COMMENT_ACTION_NOT_FOUND); .intercept('pathNotFound', () => Errors.COMMENT_ACTION_NOT_FOUND);
let { action } = actionToProjectPath; let { action } = actionToProjectPath;
const { board, project } = actionToProjectPath; const { board, project } = actionToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
COMMENT_ACTION_NOT_FOUND: { COMMENT_ACTION_NOT_FOUND: {
notFound: 'Comment action is not found', commentActionNotFound: 'Comment action not found',
}, },
}; };
@ -18,7 +18,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { commentActionNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -32,7 +32,7 @@ module.exports = {
type: 'commentCard', type: 'commentCard',
userId: currentUser.id, userId: currentUser.id,
}) })
.intercept('notFound', () => Errors.COMMENT_ACTION_NOT_FOUND); .intercept('pathNotFound', () => Errors.COMMENT_ACTION_NOT_FOUND);
let { action } = actionToProjectPath; let { action } = actionToProjectPath;
const { board, project } = actionToProjectPath; const { board, project } = actionToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
BOARD_NOT_FOUND: { BOARD_NOT_FOUND: {
notFound: 'Board is not found', boardNotFound: 'Board not found',
}, },
}; };
@ -24,7 +24,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { boardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -34,7 +34,7 @@ module.exports = {
const { board, project } = await sails.helpers const { board, project } = await sails.helpers
.getBoardToProjectPath(inputs.boardId) .getBoardToProjectPath(inputs.boardId)
.intercept('notFound', () => Errors.BOARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.BOARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
LABEL_NOT_FOUND: { LABEL_NOT_FOUND: {
notFound: 'Label is not found', labelNotFound: 'Label not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { labelNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -24,7 +24,7 @@ module.exports = {
const labelToProjectPath = await sails.helpers const labelToProjectPath = await sails.helpers
.getLabelToProjectPath(inputs.id) .getLabelToProjectPath(inputs.id)
.intercept('notFound', () => Errors.LABEL_NOT_FOUND); .intercept('pathNotFound', () => Errors.LABEL_NOT_FOUND);
let { label } = labelToProjectPath; let { label } = labelToProjectPath;
const { project } = labelToProjectPath; const { project } = labelToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
LABEL_NOT_FOUND: { LABEL_NOT_FOUND: {
notFound: 'Label is not found', labelNotFound: 'Label not found',
}, },
}; };
@ -24,7 +24,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { labelNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -34,7 +34,7 @@ module.exports = {
const labelToProjectPath = await sails.helpers const labelToProjectPath = await sails.helpers
.getLabelToProjectPath(inputs.id) .getLabelToProjectPath(inputs.id)
.intercept('notFound', () => Errors.LABEL_NOT_FOUND); .intercept('pathNotFound', () => Errors.LABEL_NOT_FOUND);
let { label } = labelToProjectPath; let { label } = labelToProjectPath;
const { project } = labelToProjectPath; const { project } = labelToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
BOARD_NOT_FOUND: { BOARD_NOT_FOUND: {
notFound: 'Board is not found', boardNotFound: 'Board not found',
}, },
}; };
@ -22,7 +22,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { boardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -32,7 +32,7 @@ module.exports = {
const { board, project } = await sails.helpers const { board, project } = await sails.helpers
.getBoardToProjectPath(inputs.boardId) .getBoardToProjectPath(inputs.boardId)
.intercept('notFound', () => Errors.BOARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.BOARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
LIST_NOT_FOUND: { LIST_NOT_FOUND: {
notFound: 'List is not found', listNotFound: 'List not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { listNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -24,7 +24,7 @@ module.exports = {
const listToProjectPath = await sails.helpers const listToProjectPath = await sails.helpers
.getListToProjectPath(inputs.id) .getListToProjectPath(inputs.id)
.intercept('notFound', () => Errors.LIST_NOT_FOUND); .intercept('pathNotFound', () => Errors.LIST_NOT_FOUND);
let { list } = listToProjectPath; let { list } = listToProjectPath;
const { project } = listToProjectPath; const { project } = listToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
LIST_NOT_FOUND: { LIST_NOT_FOUND: {
notFound: 'List is not found', listNotFound: 'List not found',
}, },
}; };
@ -21,7 +21,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { listNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -31,7 +31,7 @@ module.exports = {
const listToProjectPath = await sails.helpers const listToProjectPath = await sails.helpers
.getListToProjectPath(inputs.id) .getListToProjectPath(inputs.id)
.intercept('notFound', () => Errors.LIST_NOT_FOUND); .intercept('pathNotFound', () => Errors.LIST_NOT_FOUND);
let { list } = listToProjectPath; let { list } = listToProjectPath;
const { project } = listToProjectPath; const { project } = listToProjectPath;

View file

@ -10,12 +10,6 @@ module.exports = {
}, },
}, },
exits: {
notFound: {
responseType: 'notFound',
},
},
async fn(inputs, exits) { async fn(inputs, exits) {
const { currentUser } = this.req; const { currentUser } = this.req;

View file

@ -1,12 +1,12 @@
const Errors = { const Errors = {
PROJECT_NOT_FOUND: { PROJECT_NOT_FOUND: {
notFound: 'Project is not found', projectNotFound: 'Project not found',
}, },
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
PROJECT_MEMBERSHIP_EXIST: { USER_ALREADY_PROJECT_MEMBER: {
conflict: 'Project membership is already exist', userAlreadyProjectMember: 'User already project member',
}, },
}; };
@ -25,10 +25,13 @@ module.exports = {
}, },
exits: { exits: {
notFound: { projectNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
conflict: { userNotFound: {
responseType: 'notFound',
},
userAlreadyProjectMember: {
responseType: 'conflict', responseType: 'conflict',
}, },
}, },
@ -48,7 +51,7 @@ module.exports = {
const projectMembership = await sails.helpers const projectMembership = await sails.helpers
.createProjectMembership(project, user, this.req) .createProjectMembership(project, user, this.req)
.intercept('conflict', () => Errors.PROJECT_MEMBERSHIP_EXIST); .intercept('userAlreadyProjectMember', () => Errors.USER_ALREADY_PROJECT_MEMBER);
return exits.success({ return exits.success({
item: projectMembership, item: projectMembership,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
PROJECT_MEMBERSHIP_NOT_FOUND: { PROJECT_MEMBERSHIP_NOT_FOUND: {
notFound: 'Project membership is not found', projectMembershipNotFound: 'Project membership not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { projectMembershipNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
PROJECT_NOT_FOUND: { PROJECT_NOT_FOUND: {
notFound: 'Project is not found', projectNotFound: 'Project not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { projectNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
PROJECT_NOT_FOUND: { PROJECT_NOT_FOUND: {
notFound: 'Project is not found', projectNotFound: 'Project not found',
}, },
}; };
@ -18,7 +18,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { projectNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
CARD_NOT_FOUND: { CARD_NOT_FOUND: {
notFound: 'Card is not found', cardNotFound: 'Card not found',
}, },
}; };
@ -21,7 +21,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { cardNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -31,7 +31,7 @@ module.exports = {
const { card, project } = await sails.helpers const { card, project } = await sails.helpers
.getCardToProjectPath(inputs.cardId) .getCardToProjectPath(inputs.cardId)
.intercept('notFound', () => Errors.CARD_NOT_FOUND); .intercept('pathNotFound', () => Errors.CARD_NOT_FOUND);
const isUserMemberForProject = await sails.helpers.isUserMemberForProject( const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id, project.id,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
TASK_NOT_FOUND: { TASK_NOT_FOUND: {
notFound: 'Task is not found', taskNotFound: 'Task not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { taskNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -24,7 +24,7 @@ module.exports = {
const taskToProjectPath = await sails.helpers const taskToProjectPath = await sails.helpers
.getTaskToProjectPath(inputs.id) .getTaskToProjectPath(inputs.id)
.intercept('notFound', () => Errors.TASK_NOT_FOUND); .intercept('pathNotFound', () => Errors.TASK_NOT_FOUND);
let { task } = taskToProjectPath; let { task } = taskToProjectPath;
const { board, project } = taskToProjectPath; const { board, project } = taskToProjectPath;

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
TASK_NOT_FOUND: { TASK_NOT_FOUND: {
notFound: 'Task is not found', taskNotFound: 'Task not found',
}, },
}; };
@ -21,7 +21,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { taskNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },
@ -31,7 +31,7 @@ module.exports = {
const taskToProjectPath = await sails.helpers const taskToProjectPath = await sails.helpers
.getTaskToProjectPath(inputs.id) .getTaskToProjectPath(inputs.id)
.intercept('notFound', () => Errors.TASK_NOT_FOUND); .intercept('pathNotFound', () => Errors.TASK_NOT_FOUND);
let { task } = taskToProjectPath; let { task } = taskToProjectPath;
const { board, project } = taskToProjectPath; const { board, project } = taskToProjectPath;

View file

@ -1,6 +1,9 @@
const Errors = { const Errors = {
USER_EXIST: { EMAIL_ALREADY_IN_USE: {
conflict: 'User is already exist', emailAlreadyInUse: 'Email already in use',
},
USERNAME_ALREADY_IN_USE: {
usernameAlreadyInUse: 'Username already in use',
}, },
}; };
@ -19,20 +22,32 @@ module.exports = {
type: 'string', type: 'string',
required: true, required: true,
}, },
username: {
type: 'string',
isNotEmptyString: true,
minLength: 3,
maxLength: 16,
regex: /^[a-zA-Z0-9]+(_?[a-zA-Z0-9])*$/,
allowNull: true,
},
}, },
exits: { exits: {
conflict: { emailAlreadyInUse: {
responseType: 'conflict',
},
usernameAlreadyInUse: {
responseType: 'conflict', responseType: 'conflict',
}, },
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const values = _.pick(inputs, ['email', 'password', 'name']); const values = _.pick(inputs, ['email', 'password', 'name', 'username']);
const user = await sails.helpers const user = await sails.helpers
.createUser(values, this.req) .createUser(values, this.req)
.intercept('conflict', () => Errors.USER_EXIST); .intercept('emailAlreadyInUse', () => Errors.EMAIL_ALREADY_IN_USE)
.intercept('usernameAlreadyInUse', () => Errors.USERNAME_ALREADY_IN_USE);
return exits.success({ return exits.success({
item: user, item: user,

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
}; };
@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
notFound: { userNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -2,13 +2,13 @@ const bcrypt = require('bcrypt');
const Errors = { const Errors = {
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
CURRENT_PASSWORD_NOT_VALID: { INVALID_CURRENT_PASSWORD: {
forbidden: 'Current password is not valid', invalidCurrentPassword: 'Invalid current password',
}, },
USER_EXIST: { EMAIL_ALREADY_IN_USE: {
conflict: 'User is already exist', emailAlreadyInUse: 'Email already in use',
}, },
}; };
@ -31,13 +31,13 @@ module.exports = {
}, },
exits: { exits: {
notFound: { userNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
forbidden: { invalidCurrentPassword: {
responseType: 'forbidden', responseType: 'forbidden',
}, },
conflict: { emailAlreadyInUse: {
responseType: 'conflict', responseType: 'conflict',
}, },
}, },
@ -47,7 +47,7 @@ module.exports = {
if (inputs.id === currentUser.id) { if (inputs.id === currentUser.id) {
if (!inputs.currentPassword) { if (!inputs.currentPassword) {
throw Errors.CURRENT_PASSWORD_NOT_VALID; throw Errors.INVALID_CURRENT_PASSWORD;
} }
} else if (!currentUser.isAdmin) { } else if (!currentUser.isAdmin) {
throw Errors.USER_NOT_FOUND; // Forbidden throw Errors.USER_NOT_FOUND; // Forbidden
@ -63,14 +63,14 @@ module.exports = {
inputs.id === currentUser.id && inputs.id === currentUser.id &&
!bcrypt.compareSync(inputs.currentPassword, user.password) !bcrypt.compareSync(inputs.currentPassword, user.password)
) { ) {
throw Errors.CURRENT_PASSWORD_NOT_VALID; throw Errors.INVALID_CURRENT_PASSWORD;
} }
const values = _.pick(inputs, ['email']); const values = _.pick(inputs, ['email']);
user = await sails.helpers user = await sails.helpers
.updateUser(user, values, this.req) .updateUser(user, values, this.req)
.intercept('conflict', () => Errors.USER_EXIST); .intercept('emailAlreadyInUse', () => Errors.EMAIL_ALREADY_IN_USE);
if (!user) { if (!user) {
throw Errors.USER_NOT_FOUND; throw Errors.USER_NOT_FOUND;

View file

@ -2,10 +2,10 @@ const bcrypt = require('bcrypt');
const Errors = { const Errors = {
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
CURRENT_PASSWORD_NOT_VALID: { INVALID_CURRENT_PASSWORD: {
forbidden: 'Current password is not valid', invalidCurrentPassword: 'Invalid current password',
}, },
}; };
@ -27,10 +27,10 @@ module.exports = {
}, },
exits: { exits: {
notFound: { userNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
forbidden: { invalidCurrentPassword: {
responseType: 'forbidden', responseType: 'forbidden',
}, },
}, },
@ -40,7 +40,7 @@ module.exports = {
if (inputs.id === currentUser.id) { if (inputs.id === currentUser.id) {
if (!inputs.currentPassword) { if (!inputs.currentPassword) {
throw Errors.CURRENT_PASSWORD_NOT_VALID; throw Errors.INVALID_CURRENT_PASSWORD;
} }
} else if (!currentUser.isAdmin) { } else if (!currentUser.isAdmin) {
throw Errors.USER_NOT_FOUND; // Forbidden throw Errors.USER_NOT_FOUND; // Forbidden
@ -56,7 +56,7 @@ module.exports = {
inputs.id === currentUser.id && inputs.id === currentUser.id &&
!bcrypt.compareSync(inputs.currentPassword, user.password) !bcrypt.compareSync(inputs.currentPassword, user.password)
) { ) {
throw Errors.CURRENT_PASSWORD_NOT_VALID; throw Errors.INVALID_CURRENT_PASSWORD;
} }
const values = _.pick(inputs, ['password']); const values = _.pick(inputs, ['password']);

View file

@ -0,0 +1,85 @@
const bcrypt = require('bcrypt');
const Errors = {
USER_NOT_FOUND: {
userNotFound: 'User not found',
},
INVALID_CURRENT_PASSWORD: {
invalidCurrentPassword: 'Invalid current password',
},
USERNAME_ALREADY_IN_USE: {
usernameAlreadyInUse: 'Username already in use',
},
};
module.exports = {
inputs: {
id: {
type: 'string',
regex: /^[0-9]+$/,
required: true,
},
username: {
isNotEmptyString: true,
minLength: 3,
maxLength: 16,
regex: /^[a-zA-Z0-9]+(_?[a-zA-Z0-9])*$/,
allowNull: true,
},
currentPassword: {
type: 'string',
isNotEmptyString: true,
},
},
exits: {
userNotFound: {
responseType: 'notFound',
},
invalidCurrentPassword: {
responseType: 'forbidden',
},
usernameAlreadyInUse: {
responseType: 'conflict',
},
},
async fn(inputs, exits) {
const { currentUser } = this.req;
if (inputs.id === currentUser.id) {
if (!inputs.currentPassword) {
throw Errors.INVALID_CURRENT_PASSWORD;
}
} else if (!currentUser.isAdmin) {
throw Errors.USER_NOT_FOUND; // Forbidden
}
let user = await sails.helpers.getUser(inputs.id);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
if (
inputs.id === currentUser.id &&
!bcrypt.compareSync(inputs.currentPassword, user.password)
) {
throw Errors.INVALID_CURRENT_PASSWORD;
}
const values = _.pick(inputs, ['username']);
user = await sails.helpers
.updateUser(user, values, this.req)
.intercept('usernameAlreadyInUse', () => Errors.USERNAME_ALREADY_IN_USE);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
return exits.success({
item: user.username,
});
},
};

View file

@ -1,6 +1,6 @@
const Errors = { const Errors = {
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
}; };
@ -20,12 +20,12 @@ module.exports = {
}, },
avatar: { avatar: {
type: 'json', type: 'json',
custom: value => _.isNull(value), custom: (value) => _.isNull(value),
}, },
}, },
exits: { exits: {
notFound: { userNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
}, },

View file

@ -7,7 +7,7 @@ const sharp = require('sharp');
const Errors = { const Errors = {
USER_NOT_FOUND: { USER_NOT_FOUND: {
notFound: 'User is not found', userNotFound: 'User not found',
}, },
}; };
@ -32,9 +32,7 @@ const createReceiver = () => {
} }
firstFileHandled = true; firstFileHandled = true;
const resize = sharp() const resize = sharp().resize(36, 36).jpeg();
.resize(36, 36)
.jpeg();
const transform = new stream.Transform({ const transform = new stream.Transform({
transform(chunk, streamEncoding, callback) { transform(chunk, streamEncoding, callback) {
@ -71,10 +69,10 @@ module.exports = {
}, },
exits: { exits: {
notFound: { userNotFound: {
responseType: 'notFound', responseType: 'notFound',
}, },
unprocessableEntity: { uploadError: {
responseType: 'unprocessableEntity', responseType: 'unprocessableEntity',
}, },
}, },
@ -97,11 +95,11 @@ module.exports = {
this.req.file('file').upload(createReceiver(), async (error, files) => { this.req.file('file').upload(createReceiver(), async (error, files) => {
if (error) { if (error) {
return exits.unprocessableEntity(error.message); return exits.uploadError(error.message);
} }
if (files.length === 0) { if (files.length === 0) {
return exits.unprocessableEntity('No file was uploaded'); return exits.uploadError('No file was uploaded');
} }
user = await sails.helpers.updateUser( user = await sails.helpers.updateUser(

View file

@ -35,7 +35,7 @@ module.exports = {
const userIds = await sails.helpers.getSubscriptionUserIdsForCard(action.cardId, action.userId); const userIds = await sails.helpers.getSubscriptionUserIdsForCard(action.cardId, action.userId);
userIds.forEach(async userId => { userIds.forEach(async (userId) => {
const notification = await Notification.create({ const notification = await Notification.create({
userId, userId,
actionId: action.id, actionId: action.id,

View file

@ -6,7 +6,7 @@ module.exports = {
}, },
values: { values: {
type: 'json', type: 'json',
custom: value => _.isPlainObject(value) && _.isFinite(value.position), custom: (value) => _.isPlainObject(value) && _.isFinite(value.position),
required: true, required: true,
}, },
request: { request: {
@ -32,7 +32,7 @@ module.exports = {
position: nextPosition, position: nextPosition,
}); });
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast(`user:${userId}`, 'boardUpdate', { sails.sockets.broadcast(`user:${userId}`, 'boardUpdate', {
item: { item: {
id, id,
@ -48,7 +48,7 @@ module.exports = {
projectId: inputs.project.id, projectId: inputs.project.id,
}).fetch(); }).fetch();
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,
'boardCreate', 'boardCreate',

View file

@ -13,12 +13,16 @@ module.exports = {
}, },
}, },
exits: {
labelAlreadyInCard: {},
},
async fn(inputs, exits) { async fn(inputs, exits) {
const cardLabel = await CardLabel.create({ const cardLabel = await CardLabel.create({
cardId: inputs.card.id, cardId: inputs.card.id,
labelId: inputs.label.id, labelId: inputs.label.id,
}) })
.intercept('E_UNIQUE', 'conflict') .intercept('E_UNIQUE', 'labelAlreadyInCard')
.fetch(); .fetch();
sails.sockets.broadcast( sails.sockets.broadcast(

View file

@ -6,7 +6,7 @@ module.exports = {
}, },
userOrUserId: { userOrUserId: {
type: 'ref', type: 'ref',
custom: value => _.isPlainObject(value) || _.isString(value), custom: (value) => _.isPlainObject(value) || _.isString(value),
required: true, required: true,
}, },
request: { request: {
@ -14,6 +14,10 @@ module.exports = {
}, },
}, },
exits: {
userAlreadyCardMember: {},
},
async fn(inputs, exits) { async fn(inputs, exits) {
const { userId = inputs.userOrUserId } = inputs.userOrUserId; const { userId = inputs.userOrUserId } = inputs.userOrUserId;
@ -21,7 +25,7 @@ module.exports = {
userId, userId,
cardId: inputs.card.id, cardId: inputs.card.id,
}) })
.intercept('E_UNIQUE', 'conflict') .intercept('E_UNIQUE', 'userAlreadyCardMember')
.fetch(); .fetch();
sails.sockets.broadcast( sails.sockets.broadcast(

View file

@ -6,7 +6,7 @@ module.exports = {
}, },
values: { values: {
type: 'json', type: 'json',
custom: value => _.isPlainObject(value) && _.isFinite(value.position), custom: (value) => _.isPlainObject(value) && _.isFinite(value.position),
required: true, required: true,
}, },
user: { user: {

View file

@ -6,7 +6,7 @@ module.exports = {
}, },
values: { values: {
type: 'json', type: 'json',
custom: value => _.isPlainObject(value) && _.isFinite(value.position), custom: (value) => _.isPlainObject(value) && _.isFinite(value.position),
required: true, required: true,
}, },
request: { request: {

View file

@ -14,7 +14,7 @@ module.exports = {
}, },
exits: { exits: {
conflict: {}, userAlreadyProjectMember: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
@ -22,7 +22,7 @@ module.exports = {
projectId: inputs.project.id, projectId: inputs.project.id,
userId: inputs.user.id, userId: inputs.user.id,
}) })
.intercept('E_UNIQUE', 'conflict') .intercept('E_UNIQUE', 'userAlreadyProjectMember')
.fetch(); .fetch();
const { userIds, projectMemberships } = await sails.helpers.getMembershipUserIdsForProject( const { userIds, projectMemberships } = await sails.helpers.getMembershipUserIdsForProject(
@ -30,7 +30,7 @@ module.exports = {
true, true,
); );
userIds.forEach(userId => { userIds.forEach((userId) => {
if (userId !== projectMembership.userId) { if (userId !== projectMembership.userId) {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,

View file

@ -4,8 +4,11 @@ module.exports = {
inputs: { inputs: {
values: { values: {
type: 'json', type: 'json',
custom: value => custom: (value) =>
_.isPlainObject(value) && _.isString(value.email) && _.isString(value.password), _.isPlainObject(value) &&
_.isString(value.email) &&
_.isString(value.password) &&
(!value.username || _.isString(value.username)),
required: true, required: true,
}, },
request: { request: {
@ -14,10 +17,16 @@ module.exports = {
}, },
exits: { exits: {
conflict: {}, emailAlreadyInUse: {},
usernameAlreadyInUse: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
if (inputs.values.username) {
// eslint-disable-next-line no-param-reassign
inputs.values.username = inputs.values.username.toLowerCase();
}
const user = await User.create({ const user = await User.create({
...inputs.values, ...inputs.values,
email: inputs.values.email.toLowerCase(), email: inputs.values.email.toLowerCase(),
@ -28,13 +37,20 @@ module.exports = {
message: message:
'Unexpected error from database adapter: conflicting key value violates exclusion constraint "user_email_unique"', 'Unexpected error from database adapter: conflicting key value violates exclusion constraint "user_email_unique"',
}, },
'conflict', 'emailAlreadyInUse',
)
.intercept(
{
message:
'Unexpected error from database adapter: conflicting key value violates exclusion constraint "user_username_unique"',
},
'usernameAlreadyInUse',
) )
.fetch(); .fetch();
const userIds = await sails.helpers.getAdminUserIds(); const userIds = await sails.helpers.getAdminUserIds();
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,
'userCreate', 'userCreate',

View file

@ -17,7 +17,7 @@ module.exports = {
const userIds = await sails.helpers.getMembershipUserIdsForProject(board.projectId); const userIds = await sails.helpers.getMembershipUserIdsForProject(board.projectId);
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,
'boardDelete', 'boardDelete',

View file

@ -34,7 +34,7 @@ module.exports = {
projectMembership.projectId, projectMembership.projectId,
); );
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,
'projectMembershipDelete', 'projectMembershipDelete',
@ -47,7 +47,7 @@ module.exports = {
sails.sockets.removeRoomMembersFromRooms( sails.sockets.removeRoomMembersFromRooms(
`user:${projectMembership.userId}`, `user:${projectMembership.userId}`,
boardIds.map(boardId => `board:${boardId}`), boardIds.map((boardId) => `board:${boardId}`),
); );
const project = await Project.findOne(projectMembership.projectId); const project = await Project.findOne(projectMembership.projectId);

View file

@ -20,9 +20,9 @@ module.exports = {
const userIds = sails.helpers.mapRecords(projectMemberships, 'userId'); const userIds = sails.helpers.mapRecords(projectMemberships, 'userId');
const boards = await sails.helpers.getBoardsForProject(project.id); const boards = await sails.helpers.getBoardsForProject(project.id);
const boardRooms = boards.map(board => `board:${board.id}`); const boardRooms = boards.map((board) => `board:${board.id}`);
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.removeRoomMembersFromRooms(`user:${userId}`, boardRooms); sails.sockets.removeRoomMembersFromRooms(`user:${userId}`, boardRooms);
sails.sockets.broadcast( sails.sockets.broadcast(

View file

@ -38,7 +38,7 @@ module.exports = {
const userIds = _.union([user.id], adminUserIds, userIdsForProject); const userIds = _.union([user.id], adminUserIds, userIdsForProject);
userIds.forEach(userId => { userIds.forEach((userId) => {
sails.sockets.broadcast( sails.sockets.broadcast(
`user:${userId}`, `user:${userId}`,
'userDelete', 'userDelete',

View file

@ -7,20 +7,20 @@ module.exports = {
}, },
exits: { exits: {
notFound: {}, pathNotFound: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const action = await Action.findOne(inputs.criteria); const action = await Action.findOne(inputs.criteria);
if (!action) { if (!action) {
throw 'notFound'; throw 'pathNotFound';
} }
const path = await sails.helpers const path = await sails.helpers
.getCardToProjectPath(action.cardId) .getCardToProjectPath(action.cardId)
.intercept('notFound', nodes => ({ .intercept('pathNotFound', (nodes) => ({
notFound: { pathNotFound: {
action, action,
...nodes, ...nodes,
}, },

View file

@ -4,7 +4,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
beforeId: { beforeId: {

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
limit: { limit: {
type: 'number', type: 'number',
@ -10,9 +10,7 @@ module.exports = {
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const actions = await Action.find(inputs.criteria) const actions = await Action.find(inputs.criteria).sort('id DESC').limit(inputs.limit);
.sort('id DESC')
.limit(inputs.limit);
return exits.success(actions); return exits.success(actions);
}, },

View file

@ -7,21 +7,21 @@ module.exports = {
}, },
exits: { exits: {
notFound: {}, pathNotFound: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const board = await Board.findOne(inputs.criteria); const board = await Board.findOne(inputs.criteria);
if (!board) { if (!board) {
throw 'notFound'; throw 'pathNotFound';
} }
const project = await Project.findOne(board.projectId); const project = await Project.findOne(board.projectId);
if (!project) { if (!project) {
throw { throw {
notFound: { pathNotFound: {
board, board,
}, },
}; };

View file

@ -2,12 +2,12 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
exceptBoardId: { exceptBoardId: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
}, },

View file

@ -7,20 +7,20 @@ module.exports = {
}, },
exits: { exits: {
notFound: {}, pathNotFound: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const card = await Card.findOne(inputs.criteria); const card = await Card.findOne(inputs.criteria);
if (!card) { if (!card) {
throw 'notFound'; throw 'pathNotFound';
} }
const path = await sails.helpers const path = await sails.helpers
.getListToProjectPath(card.listId) .getListToProjectPath(card.listId)
.intercept('notFound', nodes => ({ .intercept('pathNotFound', (nodes) => ({
notFound: { pathNotFound: {
card, card,
...nodes, ...nodes,
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

View file

@ -2,12 +2,12 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
exceptCardId: { exceptCardId: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
criteria: { criteria: {
type: 'json', type: 'json',
custom: value => _.isArray(value) || _.isPlainObject(value), custom: (value) => _.isArray(value) || _.isPlainObject(value),
}, },
}, },

View file

@ -7,20 +7,20 @@ module.exports = {
}, },
exits: { exits: {
notFound: {}, pathNotFound: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const label = await Label.findOne(inputs.criteria); const label = await Label.findOne(inputs.criteria);
if (!label) { if (!label) {
throw 'notFound'; throw 'pathNotFound';
} }
const path = await sails.helpers const path = await sails.helpers
.getBoardToProjectPath(label.boardId) .getBoardToProjectPath(label.boardId)
.intercept('notFound', nodes => ({ .intercept('pathNotFound', (nodes) => ({
notFound: { pathNotFound: {
label, label,
...nodes, ...nodes,
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

View file

@ -7,20 +7,20 @@ module.exports = {
}, },
exits: { exits: {
notFound: {}, pathNotFound: {},
}, },
async fn(inputs, exits) { async fn(inputs, exits) {
const list = await List.findOne(inputs.criteria); const list = await List.findOne(inputs.criteria);
if (!list) { if (!list) {
throw 'notFound'; throw 'pathNotFound';
} }
const path = await sails.helpers const path = await sails.helpers
.getBoardToProjectPath(list.boardId) .getBoardToProjectPath(list.boardId)
.intercept('notFound', nodes => ({ .intercept('pathNotFound', (nodes) => ({
notFound: { pathNotFound: {
list, list,
...nodes, ...nodes,
}, },

View file

@ -2,12 +2,12 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
exceptListId: { exceptListId: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
withProjectMemberships: { withProjectMemberships: {

View file

@ -2,12 +2,12 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
exceptUserId: { exceptUserId: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

View file

@ -2,7 +2,7 @@ module.exports = {
inputs: { inputs: {
id: { id: {
type: 'json', type: 'json',
custom: value => _.isString(value) || _.isArray(value), custom: (value) => _.isString(value) || _.isArray(value),
required: true, required: true,
}, },
}, },

Some files were not shown because too many files have changed in this diff Show more