aboutsummaryrefslogtreecommitdiff
path: root/Timeline/ClientApp/src/settings/Settings.tsx
blob: 075f86996e80d2d70eb389d61f371047305ce16a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import React, { useState } from 'react';
import { useHistory } from 'react-router';
import { useTranslation } from 'react-i18next';
import axios, { AxiosError } from 'axios';
import { Container, Row, Col, Input } from 'reactstrap';

import { apiBaseUrl } from '../config';

import { useUser, userLogout, useUserLoggedIn } from '../data/user';

import AppBar from '../common/AppBar';
import OperationDialog, {
  OperationInputErrorInfo,
} from '../common/OperationDialog';
import { CommonErrorResponse } from '../data/common';

interface ChangePasswordDialogProps {
  open: boolean;
  close: () => void;
}

async function changePassword(
  oldPassword: string,
  newPassword: string,
  token: string
): Promise<void> {
  const url = `${apiBaseUrl}/userop/changepassword?token=${token}`;
  try {
    await axios.post(url, {
      oldPassword,
      newPassword,
    });
  } catch (e) {
    const error = e as AxiosError<CommonErrorResponse>;
    if (
      error.response &&
      error.response.status === 400 &&
      error.response.data &&
      error.response.data.message
    ) {
      throw error.response.data.message;
    }
    throw e;
  }
}

const ChangePasswordDialog: React.FC<ChangePasswordDialogProps> = (props) => {
  const user = useUserLoggedIn();
  const history = useHistory();
  const { t } = useTranslation();

  const [redirect, setRedirect] = useState<boolean>(false);

  return (
    <OperationDialog
      open={props.open}
      title={t('settings.dialogChangePassword.title')}
      titleColor="dangerous"
      inputPrompt={t('settings.dialogChangePassword.prompt')}
      inputScheme={[
        {
          type: 'text',
          label: t('settings.dialogChangePassword.inputOldPassword'),
          password: true,
          validator: (v) =>
            v === ''
              ? 'settings.dialogChangePassword.errorEmptyOldPassword'
              : null,
        },
        {
          type: 'text',
          label: t('settings.dialogChangePassword.inputNewPassword'),
          password: true,
          validator: (v, values) => {
            const error: OperationInputErrorInfo = {};
            error[1] =
              v === ''
                ? 'settings.dialogChangePassword.errorEmptyNewPassword'
                : null;
            if (v === values[2]) {
              error[2] = null;
            } else {
              if (values[2] !== '') {
                error[2] = 'settings.dialogChangePassword.errorRetypeNotMatch';
              }
            }
            return error;
          },
        },
        {
          type: 'text',
          label: t('settings.dialogChangePassword.inputRetypeNewPassword'),
          password: true,
          validator: (v, values) =>
            v !== values[1]
              ? 'settings.dialogChangePassword.errorRetypeNotMatch'
              : null,
        },
      ]}
      onProcess={async ([oldPassword, newPassword]) => {
        await changePassword(
          oldPassword as string,
          newPassword as string,
          user.token
        );
        userLogout();
        setRedirect(true);
      }}
      close={() => {
        props.close();
        if (redirect) {
          history.push('/login');
        }
      }}
    />
  );
};

const Settings: React.FC = (_) => {
  const { i18n, t } = useTranslation();
  const user = useUser();
  const history = useHistory();

  const [dialog, setDialog] = useState<null | 'changepassword'>(null);

  const language = i18n.language.slice(0, 2);

  return (
    <>
      <AppBar />
      <Container fluid style={{ marginTop: '56px' }}>
        {user ? (
          <>
            <Row className="border-bottom p-3">
              <Col className="col-12">
                <h5
                  onClick={() => {
                    history.push(`/users/${user.username}`);
                  }}
                >
                  {t('settings.gotoSelf')}
                </h5>
              </Col>
            </Row>
            <Row className="border-bottom p-3">
              <Col className="col-12">
                <h5
                  className="text-danger"
                  onClick={() => setDialog('changepassword')}
                >
                  {t('settings.changePassword')}
                </h5>
              </Col>
            </Row>
            <Row className="border-bottom p-3">
              <Col className="col-12">
                <h5
                  className="text-danger"
                  onClick={() => {
                    userLogout();
                    history.push('/');
                  }}
                >
                  {t('settings.logout')}
                </h5>
              </Col>
            </Row>
          </>
        ) : null}
        <Row className="align-items-center border-bottom p-3">
          <Col className="col-12 col-sm">
            <h5>{t('settings.languagePrimary')}</h5>
            <p>{t('settings.languageSecondary')}</p>
          </Col>
          <Col className="col-auto ml-auto">
            <Input
              type="select"
              value={language}
              onChange={(e) => {
                void i18n.changeLanguage(e.target.value);
              }}
            >
              <option value="zh">中文</option>
              <option value="en">English</option>
            </Input>
          </Col>
        </Row>
        {dialog === 'changepassword' ? (
          <ChangePasswordDialog
            open
            close={() => {
              setDialog(null);
            }}
          />
        ) : null}
      </Container>
    </>
  );
};

export default Settings;