url-password.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { useFormState } from "react-use-form-state";
  2. import { Flex } from "reflexbox/styled-components";
  3. import React, { useState } from "react";
  4. import { NextPage } from "next";
  5. import axios from "axios";
  6. import AppWrapper from "../components/AppWrapper";
  7. import { TextInput } from "../components/Input";
  8. import { Button } from "../components/Button";
  9. import Text, { H2 } from "../components/Text";
  10. import { Col } from "../components/Layout";
  11. import Icon from "../components/Icon";
  12. interface Props {
  13. protectedLink?: string;
  14. }
  15. const UrlPasswordPage: NextPage<Props> = ({ protectedLink }) => {
  16. const [loading, setLoading] = useState(false);
  17. const [formState, { password }] = useFormState<{ password: string }>();
  18. const [error, setError] = useState<string>();
  19. const onSubmit = async e => {
  20. e.preventDefault();
  21. const { password } = formState.values;
  22. if (!password) {
  23. return setError("Password must not be empty.");
  24. }
  25. setError("");
  26. setLoading(true);
  27. // TODO: better api calls
  28. try {
  29. const { data } = await axios.post("/api/url/requesturl", {
  30. id: protectedLink,
  31. password
  32. });
  33. window.location.replace(data.target);
  34. } catch ({ response }) {
  35. setError(response.data.error);
  36. }
  37. setLoading(false);
  38. };
  39. return (
  40. <AppWrapper>
  41. {!protectedLink ? (
  42. <H2 my={4} light>
  43. 404 | Link could not be found.
  44. </H2>
  45. ) : (
  46. <Col width={500} maxWidth="97%">
  47. <H2 my={3} bold>
  48. Protected link
  49. </H2>
  50. <Text mb={4}>Enter the password to be redirected to the link.</Text>
  51. <Flex
  52. as="form"
  53. alignItems="center"
  54. onSubmit={onSubmit}
  55. style={{ position: "relative" }}
  56. >
  57. <TextInput
  58. {...password("password")}
  59. placeholder="Password"
  60. height={[44, 54]}
  61. width={[1, 1 / 2]}
  62. mr={3}
  63. autoFocus
  64. required
  65. />
  66. <Button type="submit" height={[40, 44]}>
  67. {loading && <Icon name={"spinner"} stroke="white" mr={2} />}
  68. Go
  69. </Button>
  70. </Flex>
  71. <Text fontSize={14} color="red" mt={3} normal>
  72. {error}
  73. </Text>
  74. </Col>
  75. )}
  76. </AppWrapper>
  77. );
  78. };
  79. UrlPasswordPage.getInitialProps = async ({ req }) => {
  80. return {
  81. protectedLink: req && (req as any).protectedLink
  82. };
  83. };
  84. export default UrlPasswordPage;