Browse Source

login for project

Vadym Hlushko 3 years ago
commit
b8dc560404

+ 23 - 0
project/.gitignore

@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*

+ 70 - 0
project/README.md

@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
+
+The page will reload if you make edits.\
+You will also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
+
+If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
+
+You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

File diff suppressed because it is too large
+ 38801 - 0
project/package-lock.json


+ 47 - 0
project/package.json

@@ -0,0 +1,47 @@
+{
+  "name": "login",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/jest-dom": "^5.14.1",
+    "@testing-library/react": "^11.2.7",
+    "@testing-library/user-event": "^12.8.3",
+    "graphql-request": "^3.5.0",
+    "react": "^17.0.2",
+    "react-dom": "^17.0.2",
+    "react-redux": "^7.2.5",
+    "react-scripts": "4.0.3",
+    "redux": "^4.1.1",
+    "redux-thunk": "^2.3.0",
+    "web-vitals": "^1.1.2",
+    "proxy": "http://snippet.asmer.fs.a-level.com.ua"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  },
+  "devDependencies": {
+    "body-parser": "^1.19.0",
+    "express": "^4.17.1"
+  }
+}

BIN
project/public/favicon.ico


+ 47 - 0
project/public/index.html

@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
+    
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>login</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
+    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
+  </body>
+</html>

BIN
project/public/logo192.png


BIN
project/public/logo512.png


+ 25 - 0
project/public/manifest.json

@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}

+ 3 - 0
project/public/robots.txt

@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:

+ 204 - 0
project/src/App.css

@@ -0,0 +1,204 @@
+a:hover,a:focus{
+  outline: none;
+  text-decoration: none;
+ }
+ .tab{
+  
+  padding: 40px 50px;
+  position: relative;
+  
+ }
+ .tab:before{
+  content: "";
+  width: 100%;
+  height: 100%;
+  display: block;
+  position: absolute;
+  top: 0;
+  left: 0;
+  background: linear-gradient(#2e3a6a,#2f0b45);
+  opacity: 0.85;
+  border-radius: 50px;
+ }
+ .tab .nav-tabs{
+  border-bottom: none;
+  padding: 0 20px;
+  position: relative;
+ }
+ .tab .nav-tabs li{ margin: 0 30px 0 0; }
+ .tab .nav-tabs li a{
+  font-size: 18px;
+  color: #fff;
+  border-radius: 0;
+  text-transform: uppercase;
+  background: transparent;
+  padding: 0;
+  margin-right: 0;
+  border: none;
+  border-bottom: 2px solid transparent;
+  opacity: 0.5;
+  position: relative;
+  transition: all 0.5s ease 0s;
+ }
+ .tab .nav-tabs li a:hover{ background: transparent; }
+ .tab .nav-tabs li.active a,
+ .tab .nav-tabs li.active a:focus,
+ .tab .nav-tabs li.active a:hover{
+  border: none;
+  background: transparent;
+  opacity: 1;
+  border-bottom: 2px solid #eec111;
+  color: #fff;
+ }
+ .tab .tab-content{
+  padding: 20px 0 0 0;
+  margin-top: 40px;
+  background: transparent;
+  z-index: 1;
+  position: relative;
+ }
+ .form-bg{ background: #ddd; }
+ .form-horizontal .form-group{
+  margin: 0 0 15px 0;
+  position: relative;
+ }
+ .form-horizontal .form-control{
+  height: 40px;
+  background: rgba(255,255,255,0.2);
+  border: none;
+  border-radius: 20px;
+  box-shadow: none;
+  padding: 0 20px;
+  font-size: 14px;
+  font-weight: bold;
+  color: #fff;
+  transition: all 0.3s ease 0s;
+ }
+ .form-horizontal .form-control:focus{
+  box-shadow: none;
+  outline: 0 none;
+ }
+ .form-horizontal .form-group label{
+  padding: 0 20px;
+  color: #7f8291;
+  text-transform: capitalize;
+  margin-bottom: 10px;
+ }
+ .form-horizontal .main-checkbox{
+  width: 20px;
+  height: 20px;
+  background: #eec111;
+  float: left;
+  margin: 5px 0 0 20px;
+  border: 1px solid #eec111;
+  position: relative;
+ }
+ .form-horizontal .main-checkbox label{
+  width: 20px;
+  height: 20px;
+  position: absolute;
+  top: 0;
+  left: 0;
+  cursor: pointer;
+ }
+ .form-horizontal .main-checkbox label:after{
+  content: "";
+  width: 10px;
+  height: 5px;
+  position: absolute;
+  top: 5px;
+  left: 4px;
+  border: 3px solid #fff;
+  border-top: none;
+  border-right: none;
+  background: transparent;
+  opacity: 0;
+  -webkit-transform: rotate(-45deg);
+  transform: rotate(-45deg);
+ }
+ .form-horizontal .main-checkbox input[type=checkbox]{ visibility: hidden; }
+ .form-horizontal .main-checkbox input[type=checkbox]:checked + label:after{ opacity: 1; }
+ .form-horizontal .text{
+  float: left;
+  font-size: 14px;
+  font-weight: bold;
+  color: #fff;
+  margin-left: 7px;
+  line-height: 20px;
+  padding-top: 5px;
+  text-transform: capitalize;
+ }
+ .form-horizontal .btn{
+  width: 100%;
+  background: #eec111;
+  padding: 10px 20px;
+  border: none;
+  font-size: 14px;
+  font-weight: bold;
+  color: #fff;
+  border-radius: 20px;
+  text-transform: uppercase;
+  margin: 20px 0 30px 0;
+ }
+ .form-horizontal .btn:focus{
+  background: #eec111;
+  color: #fff;
+  outline: none;
+  box-shadow: none;
+ }
+ .form-horizontal .forgot-pass{
+  border-top: 1px solid #615f6c;
+  margin: 0;
+  text-align: center;
+ }
+ .form-horizontal .forgot-pass .btn{
+  width: auto;
+  background: transparent;
+  margin: 30px 0 0 0;
+  color: #615f6c;
+  text-transform: capitalize;
+  transition: all 0.3s ease 0s;
+ }
+ .form-horizontal .forgot-pass .btn:hover{ color: #eec111; }
+ @media only screen and (max-width: 479px){
+  .tab{ padding: 40px 20px; }
+ }
+
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}

+ 210 - 0
project/src/App.js

@@ -0,0 +1,210 @@
+import logo from './logo.svg';
+import './App.css';
+import React, { useState, Component, useEffect, useRef } from "react";
+import {Provider, connect}   from 'react-redux';
+import thunk  from 'redux-thunk';
+import {createStore, combineReducers,applyMiddleware } from 'redux';
+import Form from './components/Form';
+
+
+
+
+
+const getGQL = url => 
+    (query, variables) =>
+        fetch(url, {
+            method: 'POST',
+            headers: {
+                "content-type": "application/json",
+                ...(localStorage.authToken ? {Authorization: "Bearer " + localStorage.authToken} : {})
+            },
+            body: JSON.stringify({query, variables})
+        }).then(res => res.json())
+
+    let gql = getGQL("http://snippet.asmer.fs.a-level.com.ua/graphql")
+
+function promiseReducer(state , {type, name ,status , payload, error}) {
+  if (!state){
+      return {} //{status , payload , error}
+  }
+  if (type === 'PROMISE') {
+      return {
+          ...state,
+          [name]: [status,payload , error]
+      }
+  }
+  return state
+}
+
+let reg = async(login,password) => {
+  let query = `mutation reg($l:String! , $p:String!) {
+      createUser(login:$l,password:$p){
+  _id
+}
+}`
+
+    let qVariables = {
+      "l": login,
+      "p": password
+    }
+    let result = await gql(query,qVariables)
+    return result
+  }
+
+  let log = async(login , password) => {
+    let query = ` query log($l:String!,$p:String!) {
+      login(login:$l,password:$p)
+    }`
+let qVariables = {
+    "l": login,
+    "p": password 
+}
+let result = await gql(query,qVariables)
+console.log(result)
+localStorage.authToken = result.data.login
+}
+
+const actionPending = name =>            ({type: "PROMISE" ,status:"PENDING", name})
+const actionResolved = (name,payload) => ({type: "PROMISE" ,status:"RESOLVED", name,payload})
+const actionRejected = (name,error) =>   ({type: "PROMISE" ,status:"REJECTED", name,error})
+
+const actionPromise = (name, promise) => 
+  async dispatch => {
+      dispatch(actionPending(name))
+      try {
+          let payload = await promise
+          dispatch(actionResolved(name , payload))
+          return payload
+      }
+      catch(error){
+          dispatch(actionRejected(name , error))
+      }
+  }
+
+  function authReducer(state, action){ //....
+    if (state === undefined){
+        if (!localStorage.authToken){
+            return {}
+        }
+        action.token = localStorage.authToken
+        action.type = 'LOGIN'
+        // добавить в action token из localStorage, и проимитировать LOGIN 
+    }
+    if (action.type === 'LOGIN'){
+        console.log('ЛОГИН')
+        localStorage.authToken = action.token
+        console.log(action.token)
+        function jwt_decode (token) {
+            var start64Url = token.split('.')[1]
+            return JSON.parse(atob(start64Url))
+        }
+        return {token: action.token, payload: jwt_decode(action.token)}
+    }
+    if (action.type === 'LOGOUT'){
+        console.log('ЛОГАУТ')
+        localStorage.removeItem("authToken")
+        //вернуть пустой объект
+        return {}
+    }
+    return state
+}
+
+const actionAuthLogin = token => ({type:'LOGIN', token})
+const actionAuthLogout = () => ({type:'LOGOUT'})
+const actionFullLogin = (login , password) => async dispatch => {
+  let result = await dispatch(actionPromise("login",log(login,password)))
+  if (result.data.login !== null){
+  dispatch(actionAuthLogin(result.data.login))
+  }
+  else {
+      alert ('такого пользователя не существует')
+  }
+}
+const actionRegister = (login,password) => async dispatch => {
+  return await dispatch (actionPromise('register' , reg(login,password)))
+}
+
+const actionFullRegister = (login,password) => async dispatch => {
+  let result =  await dispatch (actionRegister(login,password))
+  if (result.errors === undefined) {
+      await dispatch (actionFullLogin(login,password))
+  }
+  else { 
+      alert("Такой пользователь уже есть")
+
+  }
+}
+
+
+let reducers = {
+    promise:promiseReducer,
+    auth:authReducer
+}
+
+const store = createStore(combineReducers(reducers), applyMiddleware(thunk))
+
+
+
+
+
+const LoginForm = ({ onLogin }) => {
+  const [login, setLogin] = useState("");
+  const [password, setPassword] = useState("");
+  //надо тип инпуту
+  //надо проверку на пустоту инпутов и запрет кнопки (disabled)
+  //надо при кнопке отправить в onLogin login и пароль. onLogin - это функция-колбэк
+  return (
+    <>
+      <input value={login} onChange={(e) => setLogin(e.target.value)} />
+      <input
+        type="password"
+        value={password}
+        onChange={(e) => setPassword(e.target.value)}
+      />
+      <button
+        onClick={() => onLogin(login, password)}
+        disabled={!login || !password}
+      >
+        Sign in
+      </button>
+      
+    </>
+  );
+};
+
+
+const ConnectedLoginForm = connect(null, {onLogin: actionAuthLogin})(LoginForm)
+
+const unsubscribe = store.subscribe(() => console.log('result here',store.getState()))
+
+
+
+const NickName =  ({nick}) => {
+  return (
+    <p></p>,
+    <a href = '#'>{nick || 'anon'}</a>
+    )
+  }
+  
+  
+  
+  const ConnectedNick = connect(state => ({nick:state?.auth?.payload?.sub?.login }))(NickName)
+  
+  const LogOut = connect ((state) => ({children:'Logout' , disabled:!state.auth.token }) , ({onClick:actionAuthLogout}))('button')
+
+
+function App() {
+  return (
+    <div className="App">
+      <Provider store = {store}>
+        <ConnectedNick/> <br/>
+      <ConnectedLoginForm/>
+        <LogOut/>
+        {/* <Form/> */}
+      </Provider>
+     
+    </div>
+  );
+}
+
+export default App;

+ 8 - 0
project/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 57 - 0
project/src/components/Form.js

@@ -0,0 +1,57 @@
+import React from "react";
+
+const Form = () => {
+    return (
+        <div className="container">
+ <div className="row">
+ <div className="col-md-offset-3 col-md-6">
+
+ <div className="tab" role="tabpanel">
+ <ul className="nav nav-tabs" role="tablist">
+ <li role="presentation" className="active"><a href="#Section1" aria-controls="home" role="tab" data-toggle="tab">sign in</a></li>
+ <li role="presentation"><a href="#Section2" aria-controls="profile" role="tab" data-toggle="tab">sign up</a></li>
+ </ul>
+ <div className="tab-content tabs">
+ <div role="tabpanel" className="tab-pane fade in active" id="Section1">
+ <form className="form-horizontal">
+ <div className="form-group">
+ <label htmlFor="LogLogin">Login</label>
+ <input type="email" className="form-control" id="exampleInputEmail1"/>
+ </div>
+ <div className="form-group">
+ <label htmlFor="LogPassword">Password</label>
+ <input type="password" className="form-control" id="exampleInputPassword1"/>
+ </div>
+ <div className="form-group">
+ </div>
+ <div className="form-group">
+ <button type="submit" className="btn btn-default">Sign in</button>
+ </div>
+ </form>
+ </div>
+ <div role="tabpanel" className="tab-pane fade" id="Section2">
+ <form className="form-horizontal">
+ <div className="form-group">
+ <label htmlFor="RegLogin">Login</label>
+ <input type="email" className="form-control" id="exampleInputEmail1"/>
+ </div>
+ <div className="form-group">
+ <label htmlFor="RegPassword">Password</label>
+ <input type="password" className="form-control" id="exampleInputPassword1"/>
+ </div>
+ <div className="form-group">
+ <button type="submit" className="btn btn-default">Sign up</button>
+ </div>
+ </form>
+ </div>
+ </div>
+ </div>
+
+</div>
+</div>
+</div>
+    )
+}
+
+export default Form;
+

+ 13 - 0
project/src/index.css

@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}

+ 17 - 0
project/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+ReactDOM.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>,
+  document.getElementById('root')
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

File diff suppressed because it is too large
+ 1 - 0
project/src/logo.svg


+ 13 - 0
project/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
project/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';