1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 12:56:41 +07:00

attaching accounts and displaying errors

This commit is contained in:
Fedor Katurov 2020-07-27 18:17:48 +07:00
parent 3ae22fb63d
commit b1c71faf3a
9 changed files with 140 additions and 18 deletions

View file

@ -10,6 +10,7 @@ import { selectAuthProfile } from '~/redux/auth/selectors';
import { IState } from '~/redux/store'; import { IState } from '~/redux/store';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { API } from '~/constants/api'; import { API } from '~/constants/api';
import { ProfileAccountsError } from '~/components/profile/ProfileAccountsError';
const mapStateToProps = (state: IState) => selectAuthProfile(state).socials; const mapStateToProps = (state: IState) => selectAuthProfile(state).socials;
const mapDispatchToProps = { const mapDispatchToProps = {
@ -33,6 +34,7 @@ const ProfileAccountsUnconnected: FC<IProps> = ({
authSetSocials, authSetSocials,
accounts, accounts,
is_loading, is_loading,
error,
}) => { }) => {
const onMessage = useCallback( const onMessage = useCallback(
(event: MessageEvent) => { (event: MessageEvent) => {
@ -57,6 +59,8 @@ const ProfileAccountsUnconnected: FC<IProps> = ({
[] []
); );
const resetErrors = useCallback(() => authSetSocials({ error: '' }), [authSetSocials]);
useEffect(() => { useEffect(() => {
authGetSocials(); authGetSocials();
}, [authGetSocials]); }, [authGetSocials]);
@ -68,6 +72,8 @@ const ProfileAccountsUnconnected: FC<IProps> = ({
return ( return (
<Group className={styles.wrap}> <Group className={styles.wrap}>
{error && <ProfileAccountsError onClose={resetErrors} error={error} />}
<Group className={styles.info}> <Group className={styles.info}>
<p> <p>
Ты можешь входить в Убежище, используя аккаунты на других сайтах вместо ввода логина и Ты можешь входить в Убежище, используя аккаунты на других сайтах вместо ввода логина и

View file

@ -3,7 +3,6 @@
} }
.list { .list {
padding: $gap;
box-shadow: inset transparentize(white, 0.9) 0 0 0 2px; box-shadow: inset transparentize(white, 0.9) 0 0 0 2px;
border-radius: $radius; border-radius: $radius;
} }
@ -38,6 +37,12 @@
grid-template-columns: 20px auto 20px; grid-template-columns: 20px auto 20px;
grid-column-gap: $gap * 1.5; grid-column-gap: $gap * 1.5;
align-items: center; align-items: center;
border-bottom: 1px solid transparentize(white, 0.9);
padding: $gap;
&:last-child {
border-bottom: none;
}
&__photo { &__photo {
width: 28px; width: 28px;

View file

@ -0,0 +1,22 @@
import React, { FC } from 'react';
import styles from './styles.scss';
import { Group } from '~/components/containers/Group';
import { ERROR_LITERAL } from '~/constants/errors';
import { Button } from '~/components/input/Button';
interface IProps {
onClose: () => void;
error: string;
}
const ProfileAccountsError: FC<IProps> = ({ onClose, error }) => (
<div className={styles.wrap}>
<Group className={styles.content}>
<div className={styles.title}>О НЕТ!</div>
<div className={styles.text}>{ERROR_LITERAL[error] || error}</div>
<Button onClick={onClose}>Оу, жаль</Button>
</Group>
</div>
);
export { ProfileAccountsError };

View file

@ -0,0 +1,36 @@
.wrap {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
background-color: transparentize(black, 0.5);
display: flex;
align-items: center;
justify-content: center;
@include can_backdrop {
background-color: transparentize($content_bg, 0.5);
backdrop-filter: blur(10px);
}
}
.title {
text-transform: capitalize;
font: $font_cell_title;
}
.text {
padding: $gap 0 $gap * 3;
}
.content {
max-width: 260px;
width: 100%;
color: white;
border-radius: $radius;
background-color: $content_bg;
padding: $gap * 2;
line-height: 1.2em;
}

View file

@ -7,7 +7,6 @@ export const API = {
LOGIN: '/user/login', LOGIN: '/user/login',
OAUTH_WINDOW: (provider: ISocialProvider) => OAUTH_WINDOW: (provider: ISocialProvider) =>
`${process.env.API_HOST}oauth/${provider}/redirect`, `${process.env.API_HOST}oauth/${provider}/redirect`,
VKONTAKTE_LOGIN: `${process.env.API_HOST}/oauth/vkontakte/redirect/login`,
ME: '/user/', ME: '/user/',
PROFILE: (username: string) => `/user/user/${username}/profile`, PROFILE: (username: string) => `/user/user/${username}/profile`,
MESSAGES: (username: string) => `/user/user/${username}/messages`, MESSAGES: (username: string) => `/user/user/${username}/messages`,
@ -15,8 +14,12 @@ export const API = {
GET_UPDATES: '/user/updates', GET_UPDATES: '/user/updates',
REQUEST_CODE: (code?: string) => `/user/restore/${code || ''}`, REQUEST_CODE: (code?: string) => `/user/restore/${code || ''}`,
UPLOAD: (target, type) => `/upload/${target}/${type}`, UPLOAD: (target, type) => `/upload/${target}/${type}`,
GET_SOCIALS: '/oauth/', GET_SOCIALS: '/oauth/',
DROP_SOCIAL: (provider, id) => `/oauth/${provider}/${id}`, DROP_SOCIAL: (provider, id) => `/oauth/${provider}/${id}`,
ATTACH_SOCIAL: `/oauth/attach`,
// TODO: REMOVE
VKONTAKTE_LOGIN: `${process.env.API_HOST}/oauth/vkontakte/redirect/login`,
}, },
NODE: { NODE: {
SAVE: '/node/', SAVE: '/node/',

View file

@ -20,6 +20,7 @@ export const ERRORS = {
REQUIRED: 'Required', REQUIRED: 'Required',
COMMENT_NOT_FOUND: 'Comment_Not_Found', COMMENT_NOT_FOUND: 'Comment_Not_Found',
FILE_IS_TOO_BIG: 'File_Is_Too_Big', FILE_IS_TOO_BIG: 'File_Is_Too_Big',
USER_EXIST_WITH_EMAIL: 'User_Exist_With_Email',
}; };
export const ERROR_LITERAL = { export const ERROR_LITERAL = {
@ -44,4 +45,6 @@ export const ERROR_LITERAL = {
[ERRORS.COMMENT_NOT_FOUND]: 'Комментарий не найден', [ERRORS.COMMENT_NOT_FOUND]: 'Комментарий не найден',
[ERRORS.UNKNOWN_FILE_TYPE]: 'Запрещенный тип файла', [ERRORS.UNKNOWN_FILE_TYPE]: 'Запрещенный тип файла',
[ERRORS.FILE_IS_TOO_BIG]: 'Файл слишком большой', [ERRORS.FILE_IS_TOO_BIG]: 'Файл слишком большой',
[ERRORS.USER_EXIST_WITH_EMAIL]:
'Мы не можем продолжить, потому что у другого пользователя есть этот email',
}; };

View file

@ -1,6 +1,6 @@
import { api, errorMiddleware, resultMiddleware, configWithToken } from '~/utils/api'; import { api, configWithToken, errorMiddleware, resultMiddleware } from '~/utils/api';
import { API } from '~/constants/api'; import { API } from '~/constants/api';
import { IResultWithStatus, IMessage, INotification } from '~/redux/types'; import { IMessage, INotification, IResultWithStatus } from '~/redux/types';
import { userLoginTransform } from '~/redux/auth/transforms'; import { userLoginTransform } from '~/redux/auth/transforms';
import { ISocialAccount, IUser } from './types'; import { ISocialAccount, IUser } from './types';
@ -115,3 +115,17 @@ export const apiDropSocial = ({
.delete(API.USER.DROP_SOCIAL(provider, id), configWithToken(access)) .delete(API.USER.DROP_SOCIAL(provider, id), configWithToken(access))
.then(resultMiddleware) .then(resultMiddleware)
.catch(errorMiddleware); .catch(errorMiddleware);
export const apiAttachSocial = ({
access,
token,
}: {
access: string;
token: string;
}): Promise<IResultWithStatus<{
account: ISocialAccount;
}>> =>
api
.post(API.USER.ATTACH_SOCIAL, { token }, configWithToken(access))
.then(resultMiddleware)
.catch(errorMiddleware);

View file

@ -1,9 +1,9 @@
import { call, delay, put, select, takeEvery, takeLatest } from 'redux-saga/effects'; import { call, delay, put, select, takeEvery, takeLatest } from 'redux-saga/effects';
import { AUTH_USER_ACTIONS, EMPTY_USER, USER_ERRORS, USER_ROLES } from '~/redux/auth/constants'; import { AUTH_USER_ACTIONS, EMPTY_USER, USER_ERRORS, USER_ROLES } from '~/redux/auth/constants';
import { import {
authAttachSocial,
authDropSocial, authDropSocial,
authGetMessages, authGetMessages,
authGetSocials,
authLoadProfile, authLoadProfile,
authLoggedIn, authLoggedIn,
authOpenProfile, authOpenProfile,
@ -24,6 +24,7 @@ import {
userSetLoginError, userSetLoginError,
} from '~/redux/auth/actions'; } from '~/redux/auth/actions';
import { import {
apiAttachSocial,
apiAuthGetUpdates, apiAuthGetUpdates,
apiAuthGetUser, apiAuthGetUser,
apiAuthGetUserMessages, apiAuthGetUserMessages,
@ -412,7 +413,37 @@ function* dropSocial({ provider, id }: ReturnType<typeof authDropSocial>) {
yield call(getSocials); yield call(getSocials);
} catch (e) { } catch (e) {
yield put(authSetSocials({ error: e.toString() })); yield put(authSetSocials({ error: e.message }));
}
}
function* attachSocial({ token }: ReturnType<typeof authAttachSocial>) {
if (!token) return;
try {
yield put(authSetSocials({ error: '', is_loading: true }));
const { data, error }: Unwrap<ReturnType<typeof apiAttachSocial>> = yield call(
reqWrapper,
apiAttachSocial,
{ token }
);
if (error) {
throw new Error(error);
}
const {
socials: { accounts },
}: ReturnType<typeof selectAuthProfile> = yield select(selectAuthProfile);
if (accounts.some(it => it.id === data.account.id && it.provider === data.account.provider)) {
yield put(authSetSocials({ is_loading: false }));
} else {
yield put(authSetSocials({ is_loading: false, accounts: [...accounts, data.account] }));
}
} catch (e) {
yield put(authSetSocials({ is_loading: false, error: e.message }));
} }
} }
@ -434,6 +465,7 @@ function* authSaga() {
yield takeLatest(AUTH_USER_ACTIONS.RESTORE_PASSWORD, restorePassword); yield takeLatest(AUTH_USER_ACTIONS.RESTORE_PASSWORD, restorePassword);
yield takeLatest(AUTH_USER_ACTIONS.GET_SOCIALS, getSocials); yield takeLatest(AUTH_USER_ACTIONS.GET_SOCIALS, getSocials);
yield takeLatest(AUTH_USER_ACTIONS.DROP_SOCIAL, dropSocial); yield takeLatest(AUTH_USER_ACTIONS.DROP_SOCIAL, dropSocial);
yield takeLatest(AUTH_USER_ACTIONS.ATTACH_SOCIAL, attachSocial);
} }
export default authSaga; export default authSaga;

View file

@ -4,7 +4,7 @@ import { API } from '~/constants/api';
import { store } from '~/redux/store'; import { store } from '~/redux/store';
import { IResultWithStatus } from '~/redux/types'; import { IResultWithStatus } from '~/redux/types';
export const authMiddleware = (r) => { export const authMiddleware = r => {
store.dispatch(push('/login')); store.dispatch(push('/login'));
return r; return r;
}; };
@ -23,26 +23,27 @@ export const HTTP_RESPONSES = {
TOO_MANY_REQUESTS: 429, TOO_MANY_REQUESTS: 429,
}; };
export const resultMiddleware = (<T extends {}>({ export const resultMiddleware = <T extends {}>({
status, status,
data, data,
}: { }: {
status: number; status: number;
data: T; data: T;
}): { status: number; data: T } => ({ status, data })); }): { status: number; data: T } => ({ status, data });
export const errorMiddleware = <T extends any>(debug): IResultWithStatus<T> => (debug && debug.response export const errorMiddleware = <T extends any>(debug): IResultWithStatus<T> =>
? debug.response debug && debug.response
? debug.response.data || debug.response
: { : {
status: HTTP_RESPONSES.CONNECTION_REFUSED, status: HTTP_RESPONSES.CONNECTION_REFUSED,
data: {}, data: {},
debug, debug,
error: 'Ошибка сети', error: 'Ошибка сети',
}); };
export const configWithToken = ( export const configWithToken = (
access: string, access: string,
config: AxiosRequestConfig = {}, config: AxiosRequestConfig = {}
): AxiosRequestConfig => ({ ): AxiosRequestConfig => ({
...config, ...config,
headers: { ...(config.headers || {}), Authorization: `Bearer ${access}` }, headers: { ...(config.headers || {}), Authorization: `Bearer ${access}` },