Guest User

Untitled

a guest
Jun 20th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.32 KB | None | 0 0
  1. import React, { Component, Fragment } from 'react';
  2. import { withRouter, Link } from 'react-router-dom';
  3. import uuid from 'uuid/v4';
  4. import axios from 'axios';
  5.  
  6. import {
  7. Spin,
  8. Row,
  9. Col,
  10. Form,
  11. Input,
  12. Tooltip,
  13. Icon,
  14. Cascader,
  15. Select,
  16. Checkbox,
  17. Button,
  18. AutoComplete,
  19. } from 'antd';
  20. import './style.css';
  21.  
  22. const FormItem = Form.Item;
  23.  
  24. class AccountForm extends Component {
  25. state = {
  26. username: '',
  27. email: '',
  28. password: '',
  29. confirmPassword: '',
  30. confirmDirty: false,
  31. user: {},
  32. updated: false,
  33. update: '',
  34. picture: null,
  35. };
  36. componentDidMount() {
  37. axios.get('/auth/user').then(response => {
  38. console.log(response.data)
  39. if (!!response.data.user) {
  40. console.log('THERE IS A current logged in USER', response.data.user)
  41. this.setState({
  42. email: response.data.user.email,
  43. username: response.data.user.username,
  44. walletAddress: response.data.user.walletAddress,
  45. token: response.data.user.token,
  46. referralCode: response.data.user.referralCode,
  47. referralCodeCount: response.data.user.referralCodeCount,
  48. referralCodeHistory: response.data.user.referralCodeHistory,
  49. });
  50. } else {
  51. console.log("not logged in")
  52. }
  53. })
  54. }
  55. handleSubmit = e => {
  56. e.preventDefault();
  57. // this.setState({ isRegistering: true });
  58.  
  59. this.props.form.validateFields((err, values) => {
  60. if (!err) {
  61.  
  62. // TODO
  63. // implement update account on backend
  64. //
  65. // firebase
  66. // .database()
  67. // .ref(`users/${this.state.uid}`)
  68. // .update({
  69. // email: values.email,
  70. // username: values.username,
  71. // role: values.role,
  72. // studentId: values.studentId,
  73. // picture: this.state.picture,
  74. // })
  75. // .then(() => {
  76. // this.setState({
  77. // updated: true,
  78. // update: 'Account Successfully Updated!',
  79. // isRegistering: false,
  80. // });
  81. // setTimeout(() => {
  82. // this.setState({ updated: false, update: '' });
  83. // }, 8000);
  84. // })
  85. // .catch(error => {
  86. // this.setState({ error });
  87. // });
  88. }
  89. });
  90. };
  91.  
  92. hasErrors(fieldsError) {
  93. if (this.state.isRegistering) {
  94. fieldsError = Object.assign(fieldsError, {
  95. isRegistering: ['Updating your account'],
  96. });
  97. // console.log("fieldsError", fieldsError)
  98. }
  99. return Object.keys(fieldsError).some(field => fieldsError[field]);
  100. }
  101.  
  102. onSendVerificationEmail = (email) => {
  103.  
  104. }
  105.  
  106. render() {
  107. const {
  108. getFieldDecorator,
  109. getFieldsError,
  110. resetFields,
  111. setFields,
  112. } = this.props.form;
  113. const formItemLayout = {
  114. labelCol: {
  115. xs: { span: 24 },
  116. sm: { span: 10 },
  117. },
  118. wrapperCol: {
  119. xs: { span: 24 },
  120. sm: { span: 14 },
  121. },
  122. };
  123. return (
  124. <Form onSubmit={this.handleSubmit} className="login-form">
  125. <p style={{ fontSize: '34px', textAlign: 'center' }}>{this.state.username}'s Profile</p>
  126. <FormItem
  127. {...formItemLayout}
  128. label="username"
  129. >
  130. {getFieldDecorator('username', {
  131. initialValue: this.state.username,
  132. rules: [
  133. {
  134. required: true,
  135. message: 'Please input your username!',
  136. whitespace: true,
  137. },
  138. ],
  139. })(<Input />)}
  140. </FormItem>
  141. <FormItem {...formItemLayout} label="E-mail">
  142. {getFieldDecorator('email', {
  143. initialValue: this.state.email,
  144. rules: [
  145. {
  146. type: 'email',
  147. message: 'The input is not valid E-mail!',
  148. },
  149. { required: true, message: 'Please input your email!' },
  150. ],
  151. })(
  152. <Input
  153. prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
  154. placeholder="Email"
  155. />
  156. )}
  157. </FormItem>
  158. <FormItem
  159. {...formItemLayout}
  160. label="Wallet Address"
  161. >
  162. {getFieldDecorator('walletAddress', {
  163. initialValue: this.state.walletAddress,
  164. rules: [
  165. {
  166. required: false,
  167. message: 'Please input your Wallet Address!',
  168. whitespace: true,
  169. },
  170. ],
  171. })(<Input />)}
  172. </FormItem>
  173. <FormItem
  174. {...formItemLayout}
  175. label="Token"
  176. >
  177. <div><strong>{this.state.token}</strong></div>
  178. </FormItem>
  179. {this.state.referralCode &&
  180. <FormItem
  181. {...formItemLayout}
  182. label="Referral Code"
  183. >
  184. <div><strong>{this.state.referralCode}</strong></div>
  185. </FormItem>
  186. }
  187. {!this.state.referralCode &&
  188. <FormItem style={{ display: 'flex', margin: 'auto', width: '80%' }}>
  189. <div>To get a referral code, <strong>verify your email.</strong> For every friend you refer you’ll each get 10 tokens.</div>
  190. <a onClick={() => this.onSendVerificationEmail(this.state.email)}>Resend the verification</a>
  191. </FormItem>
  192. }
  193.  
  194. <FormItem style={{ display: 'flex', justifyContent: 'center' }}>
  195. <div>Users who used your referral code</div>
  196. <div>
  197. {this.state.referralCodeHistory && this.state.referralCodeHistory.map((user, index) => {
  198. return (<div key={index} style={{ marginLeft: '120px' }}><strong>{index + 1}. {user.username}</strong></div>);
  199. })}
  200. </div>
  201. </FormItem>
  202. <FormItem style={{ display: 'flex', justifyContent: 'center' }}>
  203. <Button
  204. type="primary"
  205. htmlType="submit"
  206. className="login-form-button"
  207. style={{ minWidth: '200px' }}
  208. disabled={
  209. // true ||
  210. this.hasErrors(getFieldsError()) ||
  211. this.state.isRegistering ||
  212. this.state.isUploading
  213. }
  214. >
  215. Update
  216. </Button>
  217. {this.state.isRegistering && <Spin />}
  218. </FormItem>
  219. {this.state.error && <p>{this.state.error.message}</p>}
  220. </Form>
  221. );
  222. }
  223. }
  224. AccountForm = withRouter(Form.create()(AccountForm));
  225.  
  226. class PasswordForm extends Component {
  227. state = {
  228. username: '',
  229. email: '',
  230. password: '',
  231. confirmPassword: '',
  232. confirmDirty: false,
  233. user: {},
  234. updated: false,
  235. update: '',
  236. };
  237. componentDidMount() {
  238. firebase.auth().onAuthStateChanged(authUser => {
  239. // console.log('componentDidMount() authUser', authUser);
  240. firebase
  241. .database()
  242. .ref(`users/${authUser.uid}`)
  243. .on('value', snapshot => {
  244. // console.log('snapshot.val()', snapshot.val());
  245. this.setState({ uid: authUser.uid, user: snapshot.val() });
  246. });
  247. });
  248. }
  249. handleSubmit = e => {
  250. e.preventDefault();
  251. this.props.form.validateFields((err, values) => {
  252. if (!err) {
  253. // console.log('Received values of form: ', values);
  254. if (this.state.user.password != values.password) {
  255. firebase
  256. .auth()
  257. .currentUser.updatePassword(values.password)
  258. .then(() => {
  259. firebase
  260. .database()
  261. .ref(`users/${this.state.uid}`)
  262. .update({
  263. password: values.password,
  264. })
  265. .then(() => {
  266. this.setState({ updated: true });
  267. setTimeout(() => {
  268. this.setState({ updated: false });
  269. }, 8000);
  270. })
  271. .catch(error => {
  272. this.setState({ error });
  273. });
  274. this.setState({
  275. updated: true,
  276. update: 'Password Successfully Updated!',
  277. });
  278. setTimeout(() => {
  279. this.setState({ updated: false, update: '' });
  280. }, 8000);
  281.  
  282. // Create a user in your own accessible Firebase Database too
  283. })
  284. .catch(error => {
  285. this.setState({ error });
  286. });
  287. }
  288. }
  289. });
  290. };
  291. compareToFirstPassword = (rule, value, callback) => {
  292. const form = this.props.form;
  293. if (value && value !== form.getFieldValue('password')) {
  294. callback('Two passwords that you enter is inconsistent!');
  295. } else {
  296. callback();
  297. }
  298. };
  299. validatePassword = (rule, value, callback) => {
  300. const form = this.props.form;
  301. let errors = [];
  302. if (value.length < 8) {
  303. errors.push('Your password must be at least 8 characters.');
  304. }
  305. if (value.search(/[a-z]/i) < 0) {
  306. errors.push('Your password must contain at least one letter.');
  307. }
  308. if (value.search(/[0-9]/) < 0) {
  309. errors.push('Your password must contain at least one digit.');
  310. }
  311. if (errors.length > 0) {
  312. callback(errors.join('\n'));
  313. }
  314. if (value && this.state.confirmDirty) {
  315. form.validateFields(['confirmPassword'], { force: true });
  316. }
  317. if (errors.length == 0) {
  318. callback();
  319. }
  320. };
  321. validateToNextPassword = (rule, value, callback) => {
  322. const form = this.props.form;
  323. if (value && this.state.confirmDirty) {
  324. form.validateFields(['confirmPassword'], { force: true });
  325. }
  326. callback();
  327. };
  328. handleConfirmBlur = e => {
  329. const value = e.target.value;
  330. this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  331. };
  332. render() {
  333. const { getFieldDecorator, resetFields, setFields } = this.props.form;
  334. const formItemLayout = {
  335. labelCol: {
  336. xs: { span: 24 },
  337. sm: { span: 8 },
  338. },
  339. wrapperCol: {
  340. xs: { span: 24 },
  341. sm: { span: 16 },
  342. },
  343. };
  344. return (
  345. <Form onSubmit={this.handleSubmit} className="login-form">
  346. <p style={{ fontSize: '34px', textAlign: 'center' }}>Password Change</p>
  347. <FormItem {...formItemLayout} label="Password">
  348. {getFieldDecorator('password', {
  349. initialValue: this.state.user.password,
  350. rules: [
  351. { required: true, message: 'Please input your Password!' },
  352. {
  353. validator: this.validatePassword,
  354. },
  355. ],
  356. })(
  357. <Input
  358. prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
  359. type="password"
  360. placeholder="Password"
  361. />
  362. )}
  363. </FormItem>
  364. <FormItem {...formItemLayout} label="Confirm Password">
  365. {getFieldDecorator('confirmPassword', {
  366. initialValue: this.state.user.password,
  367. rules: [
  368. {
  369. required: true,
  370. message: 'Please confirm your password!',
  371. },
  372. {
  373. validator: this.compareToFirstPassword,
  374. },
  375. ],
  376. })(
  377. <Input
  378. prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
  379. type="password"
  380. placeholder="Password"
  381. onBlur={this.handleConfirmBlur}
  382. />
  383. )}
  384. </FormItem>
  385. <FormItem style={{ display: 'flex', justifyContent: 'center' }}>
  386. <Button
  387. type="primary"
  388. htmlType="submit"
  389. className="login-form-button"
  390. style={{ minWidth: '200px' }}
  391. >
  392. Update
  393. </Button>
  394. </FormItem>
  395. {this.state.error && <p>{this.state.error.message}</p>}
  396. {this.state.updated && (
  397. <p style={{ fontSize: '20px', textAlign: 'center' }}>
  398. {this.state.update}
  399. </p>
  400. )}
  401. </Form>
  402. );
  403. }
  404. }
  405. PasswordForm = withRouter(Form.create()(PasswordForm));
  406.  
  407. class AccountPage extends React.PureComponent {
  408. // eslint-disable-line react/prefer-stateless-function
  409. render() {
  410. return (
  411. <Fragment>
  412. <Row
  413. type="flex"
  414. justify="center"
  415. align="middle"
  416. style={{
  417. minHeight: '670px',
  418. }}
  419. >
  420. <Col
  421. style={{ padding: '10px' }}
  422. xs={{ span: 24, offset: 0 }}
  423. lg={{ span: 8, offset: 0 }}
  424. >
  425. <AccountForm />
  426. </Col>
  427. </Row>
  428. </Fragment>
  429. );
  430. }
  431. }
  432.  
  433. export default withRouter(AccountPage);
Add Comment
Please, Sign In to add comment