Browse Source

Авторизация супер

Vladislav342 2 years ago
parent
commit
310c44229e
41 changed files with 406 additions and 347 deletions
  1. 19 0
      React/CodePen/src/App.css
  2. 14 39
      React/CodePen/src/App.js
  3. 0 16
      React/CodePen/src/App.scss
  4. 0 8
      React/CodePen/src/App.test.js
  5. 1 1
      React/CodePen/src/actions/actionAuthLogin.js
  6. 1 1
      React/CodePen/src/actions/actionAuthLogout.js
  7. 1 1
      React/CodePen/src/actions/actionFindUser.js
  8. 10 0
      React/CodePen/src/actions/actionFullAvatar.js
  9. 12 27
      React/CodePen/src/actions/actionFullLogin.js
  10. 8 9
      React/CodePen/src/actions/actionFullRegister.js
  11. 3 0
      React/CodePen/src/actions/actionImgFind.js
  12. 1 1
      React/CodePen/src/actions/actionPending.js
  13. 13 15
      React/CodePen/src/actions/actionPromise.js
  14. 5 6
      React/CodePen/src/actions/actionRegister.js
  15. 6 1
      React/CodePen/src/actions/actionRejected.js
  16. 1 1
      React/CodePen/src/actions/actionResolved.js
  17. 2 1
      React/CodePen/src/actions/actionSearch.js
  18. 6 0
      React/CodePen/src/actions/actionSnippetFindByOwner.js
  19. 4 23
      React/CodePen/src/actions/gql.js
  20. 0 60
      React/CodePen/src/actions/gqlRequests.js
  21. 0 10
      React/CodePen/src/actions/jwtDecode.js
  22. 131 0
      React/CodePen/src/actions/requests.js
  23. 9 4
      React/CodePen/src/components/ava.js
  24. 10 11
      React/CodePen/src/components/header.js
  25. 2 2
      React/CodePen/src/components/logo.js
  26. 16 0
      React/CodePen/src/components/nick.js
  27. 20 17
      React/CodePen/src/components/nickHeader.js
  28. 3 2
      React/CodePen/src/components/privateRout.js
  29. 3 3
      React/CodePen/src/components/profile.js.js
  30. 25 24
      React/CodePen/src/components/routes.js
  31. BIN
      React/CodePen/src/logo.png
  32. 26 9
      React/CodePen/src/pages/cabinet.js
  33. 13 0
      React/CodePen/src/pages/homePage.js
  34. 8 7
      React/CodePen/src/pages/login.js
  35. 0 12
      React/CodePen/src/pages/mainPage.js
  36. 2 1
      React/CodePen/src/pages/reg.js
  37. 1 1
      React/CodePen/src/pages/search.js
  38. 4 4
      React/CodePen/src/reducers/authReducer.js
  39. 13 11
      React/CodePen/src/reducers/promiseReducer.js
  40. 13 19
      React/CodePen/src/reducers/store.js
  41. BIN
      React/CodePen/src/user.png

+ 19 - 0
React/CodePen/src/App.css

@@ -0,0 +1,19 @@
+.App {
+  font: 400 14px "Open Sans", "Arial", "Helvetica Neue", "Helvetica", sans-serif;
+  overflow-x: hidden;
+  max-width: 100%;
+}
+
+
+
+.headerBlock{
+	border:1px solid black;	
+}
+
+.headerBlock2{
+	position: "relative";
+	left: 60%;
+	padding-top:10px;
+}
+
+

+ 14 - 39
React/CodePen/src/App.js

@@ -1,46 +1,21 @@
-import './App.scss';
-import {Provider, connect} from 'react-redux';
-import {createStore, combineReducers, applyMiddleware} from 'redux';
-import thunk from 'redux-thunk';
-import {useEffect, useState, useRef} from "react";
-import React, {useCallback} from 'react';
-import {Router, Route, Link, Redirect, Switch} from 'react-router-dom';
-import createHistory from "history/createBrowserHistory";
-import {store} from "./reducers/store";
+import React from "react";
+import "./App.css";
+import { Provider } from "react-redux";
 import Routes from "./components/routes";
-import 'bootstrap/dist/css/bootstrap.min.css';
-
-//import {useDropzone} from 'react-dropzone'
-/*const actionAboutMe = () => {
-	async(dispatch, getState)=>{
-		
-	}
-}
-const actioUploadFile = file =>{
-	return actionPromise('uploadFile', fetch().then(res=>res.json))
-}
-const actionSetAvatar = file =>{
-	async(dispatch, getState) => {
-		
-	}
-}*/
-//const store = createStore(combineReducers({promise: promiseReducer, auth: authReducer}),applyMiddleware(thunk))
-//store.subscribe(()=>console.log(store.getState()))
-//store.dispatch(actionCatById('5dc49f4d5df9d670df48cc64'))
-//store.dispatch(actionFullLogin('vladBraun4','123'))
-
-const history = createHistory();
+import { store } from "./reducers/store";
+import createHistory from "history/createBrowserHistory";
+import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
 
 function App() {
-  	return (
-  		<Router history={history}>
-  			<Provider store={store} >
-	      		<Routes />
-	    	</Provider>
+  return (
+    <>
+	    <Router history={createHistory()}>
+	      <Provider store={store}>
+	        <Routes />
+	      </Provider>
 	    </Router>
-  	);
+    </>
+  );
 }
 
 export default App;
-
-

+ 0 - 16
React/CodePen/src/App.scss

@@ -1,16 +0,0 @@
-
-body{
-	margin: 0;
-	width: 100%;
-	overflow: auto;
-	.App{
-	
-		.headerBlock{
-			display:flex;
-			flex-diraction:space-between;
-			border:1px solid black;
-			
-		}
-	}
-}
-

+ 0 - 8
React/CodePen/src/App.test.js

@@ -1,8 +0,0 @@
-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();
-});

+ 1 - 1
React/CodePen/src/actions/actionAuthLogin.js

@@ -1 +1 @@
-export const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token })
+export const actionAuthLogin = (token) => ({ type: "LOGIN", token });

+ 1 - 1
React/CodePen/src/actions/actionAuthLogout.js

@@ -1 +1 @@
-export const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' })
+export const actionAuthLogout = () => ({ type: "LOGOUT" });

+ 1 - 1
React/CodePen/src/actions/actionFindUser.js

@@ -1,5 +1,5 @@
 import { actionPromise } from "./actionPromise";
-import { userFind } from "./gqlRequests";
+import { userFind } from "./requests";
 
 export const actionFindUser = () => async (dispatch, getState) => {
     return await dispatch(

+ 10 - 0
React/CodePen/src/actions/actionFullAvatar.js

@@ -0,0 +1,10 @@
+import { actionUploadFile } from "./actionUploadFile";
+import { actionSetAvatar } from "./actionSetAvatar";
+import { actionFindUser } from "./actionFindUser";
+
+export const actionFullAvatar = (file) => async (dispatch) => {
+    let result = await dispatch(actionUploadFile(file));
+    await dispatch(actionSetAvatar(result._id));
+    await dispatch(actionFindUser());
+  };
+  

+ 12 - 27
React/CodePen/src/actions/actionFullLogin.js

@@ -1,33 +1,18 @@
 import {actionPromise} from "./actionPromise";
+import {log} from "./requests";
 import {actionAuthLogin} from "./actionAuthLogin";
-import {log} from "./gqlRequests";
+import {actionFindUser} from "./actionFindUser";
 
-import { actionFindUser } from "./actionFindUser";
+export const actionFullLogin = (login, password) => async (dispatch) => {
+	  let result = await dispatch(actionPromise("login", log(login, password)));
+	  if (result?.data?.login !== null) {
+		  	console.log(result);
+		    dispatch(actionAuthLogin(result.data.login));
+	  } else {
+	    	alert("Такого пользователя не существует!");
+	  }
+	  await dispatch(actionFindUser());
+};
 
-/*const actionLogin = (login, password) =>
-    actionPromise('login', gql(`query NameForMe1($login:String, $password:String){
-            login(login:$login, password:$password)
-        }`, { login, password }))*/
 
-/*export const actionFullLogin = (login,password) =>
-	async function i(dispatch){
-		let token = await dispatch(actionPromise("login", log(login, password)));
-		console.log(token);
-		if(token){
-			dispatch(actionAuthLogin(token));
-		}
-	}*/
 
-export const actionFullLogin = (login, password) => 
-  async (dispatch) => {
-      let result = await dispatch(actionPromise("login", log(login, password)));
-      console.log(result);
-      console.log('kuku')
-      if (result?.data?.login  !== null) {
-        console.log(actionAuthLogin(result))
-        dispatch(actionAuthLogin(result.data.login));
-      } else {
-        alert("Такого пользователя не существует!");
-      }
-      await dispatch(actionFindUser());
-  };

+ 8 - 9
React/CodePen/src/actions/actionFullRegister.js

@@ -1,12 +1,11 @@
 import { actionRegister } from "./actionRegister";
 import { actionFullLogin } from "./actionFullLogin";
 
-export const actionFullRegister = (login, password) => 
-	async (dispatch) => {
-	    let result = await dispatch(actionRegister(login, password));
-	    if (result?.data?.createUser !== null) {
-	      	await dispatch(actionFullLogin(login, password));
-	    } else {
-	      	alert("Такой пользователь уже есть!");
-	    }
-	};
+export const actionFullRegister = (login, password) => async (dispatch) => {
+    let result = await dispatch(actionRegister(login, password));
+    if (result?.data?.createUser !== null) {
+      await dispatch(actionFullLogin(login, password));
+    } else {
+      alert("Такой пользователь уже есть!");
+    }
+  };

+ 3 - 0
React/CodePen/src/actions/actionImgFind.js

@@ -0,0 +1,3 @@
+export const actionImgFind = () => async (dispatch) => {
+    return await dispatch(actionPromise("img", imgFind()));
+  };

+ 1 - 1
React/CodePen/src/actions/actionPending.js

@@ -1 +1 @@
-export const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
+export const actionPending = (name) => ({type: "PROMISE", status: "PENDING",name});

+ 13 - 15
React/CodePen/src/actions/actionPromise.js

@@ -1,16 +1,14 @@
-import {actionPending} from "./actionPending";
-import {actionResolved} from "./actionResolved";
-import {actionRejected} from "./actionRejected";
+import { actionPending } from "./actionPending";
+import { actionResolved } from "./actionResolved";
+import { actionRejected } from "./actionRejected";
 
-export const actionPromise = (name, promise) =>
-    async dispatch => {
-        dispatch(actionPending(name))
-        try {
-            let data = await promise
-            dispatch(actionResolved(name, data))
-            return data
-        }
-        catch (error) {
-            dispatch(actionRejected(name, error))
-        }
-    }
+export 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));
+  }
+};

+ 5 - 6
React/CodePen/src/actions/actionRegister.js

@@ -1,7 +1,6 @@
-import {reg} from "./gqlRequests";
-import {actionPromise} from "./actionPromise";
+import { actionPromise } from "./actionPromise";
+import { reg } from "./requests";
 
-export const actionRegister = (login,password) => 
-	async (dispatch) =>{
-		return await dispatch(actionPromise('register',reg(login,password)));
-	}
+export const actionRegister = (login, password) => async (dispatch) => {
+    return await dispatch(actionPromise("register", reg(login, password)));
+  };

+ 6 - 1
React/CodePen/src/actions/actionRejected.js

@@ -1 +1,6 @@
-export const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
+export const actionRejected = (name, error) => ({
+    type: "PROMISE",
+    status: "REJECTED",
+    name,
+    error,
+  });

+ 1 - 1
React/CodePen/src/actions/actionResolved.js

@@ -1 +1 @@
-export const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
+export const actionResolved = (name, payload) => ({type: "PROMISE", status: "RESOLVED", name, payload});

+ 2 - 1
React/CodePen/src/actions/actionSearch.js

@@ -1,6 +1,7 @@
-import { search } from "./gqlRequests";
+import { search } from "./requests";
 import { actionPromise } from "./actionPromise";
 
 export const actionSearch = (string) => async (dispatch) => {
     return await dispatch(actionPromise('searchSnippet', search(string)))
 }
+

+ 6 - 0
React/CodePen/src/actions/actionSnippetFindByOwner.js

@@ -0,0 +1,6 @@
+import { actionPromise } from "./actionPromise";
+import { snippetByOwner } from "./requests";
+
+export const actionSnippetFindByOwner = (id) => async (dispatch) => {
+    return await dispatch(actionPromise("findSnippet", snippetByOwner(id)));
+  };

+ 4 - 23
React/CodePen/src/actions/gql.js

@@ -1,21 +1,4 @@
-const getGQL = url =>
-    async (query, variables = {}) => {
-        let obj = await fetch(url, {
-            method: 'POST',
-            headers: {
-                "Content-Type": "application/json",
-                Authorization: localStorage.authToken ? 'Bearer ' + localStorage.authToken : {},
-            },
-            body: JSON.stringify({ query, variables })
-        })
-        let a = await obj.json()
-        if (!a.data && a.errors)
-            throw new Error(JSON.stringify(a.errors))
-        return a.data[Object.keys(a.data)[0]]
-    }
-    
-/*const getGQL =
-  (url) =>
+const getGQL = (url) =>
   (query, variables = {}) =>
     fetch(url, {
       method: "POST",
@@ -27,10 +10,8 @@ const getGQL = url =>
           : {}),
       },
       body: JSON.stringify({ query, variables }),
-    }).then((res) => res.json());*/
+    }).then((res) => res.json());
 
-const backURL = 'http://snippet.asmer.fs.a-level.com.ua';
-export const gql = getGQL(backURL + '/graphql')
+console.log(getGQL);
 
-/*console.log(getGQL);
-export const gql = getGQL("/graphql");*/
+export const gql = getGQL("/graphql");

+ 0 - 60
React/CodePen/src/actions/gqlRequests.js

@@ -1,60 +0,0 @@
-import {gql} from "./gql";
-
-export const reg = async (login, password) => {
-    let query = `mutation reg($login:String! , $password:String!) {
-        createUser(login:$login,password:$password){
-    _id login
-  }
-  }`;
-    let qVariables = {
-      l: login,
-      p: password,
-    };
-    let result = await gql(query, qVariables);
-    return result;
-  };
-
-  export const log = async (login, password) => {
-    let query = ` query log($login:String!,$password:String!) {
-        login(login:$login,password:$password)
-      }`;
-    let qVariables = {
-      l: login,
-      p: password,
-    };
-    let result = await gql(query, qVariables);
-    return result;
-  };
-
-  export const search = async (string) => {
-    return gql(
-      `query snippetFind($query:String){
-        SnippetFind(query:$query){
-          owner {
-            _id login
-          }
-              title description _id files {
-               type text name
-             }
-          }
-    }`,
-      { query: JSON.stringify([
-        {
-            $or: [{title: `/${string.trim().split(" ").join('|')}/`},{description: `/${string.trim().split(" ").join('|')}/`}] 
-        },
-        {
-          sort: [{title: 1}]}]) }
-    );
-  };
-  export const userFind = (_id) => {
-    return gql(
-      `query userOne($query:String) {
-        UserFindOne(query:$query){
-          _id avatar{
-            url
-          }
-        }
-      }`,
-      { query: JSON.stringify([{ _id }]) }
-    );
-  };

+ 0 - 10
React/CodePen/src/actions/jwtDecode.js

@@ -1,10 +0,0 @@
-const jwtDecode = token => {
-    try {
-        let arrToken = token.split('.')
-        let base64Token = atob(arrToken[1])
-        return JSON.parse(base64Token)
-    }
-    catch (e) {
-        console.log('Лажа, Бро ' + e);
-    }
-}

+ 131 - 0
React/CodePen/src/actions/requests.js

@@ -0,0 +1,131 @@
+import { gql } from "./gql";
+
+export const snippetById = async(id) => {
+    let query = `query snippetFind($query:String){
+      SnippetFind(query:$query){
+                        owner{
+                          _id 
+                        }
+            title description _id files {
+             type text name
+           }
+        }
+  }`;
+  let variables = {
+    query: JSON.stringify([{_id: id }])
+  };
+  
+  let res = gql(query, variables);
+  return res;
+  }
+  export const snippetByOwner = async (id) => {
+    let query = `query snippetFind($query:String){
+        SnippetFind(query:$query){
+                          owner{
+                            _id 
+                          }
+              title description _id files {
+               type text name
+             }
+          }
+  }`;
+    let variables = {
+      query: JSON.stringify([{___owner: id } , {sort:[{_id: -1}]}])
+    };
+  
+    let res = gql(query, variables);
+    return res;
+  }
+  export const userFind = (_id) => {
+    return gql(
+      `query userOne($query:String) {
+                                       UserFindOne(query:$query){
+                                         _id avatar{
+                                           url
+                                         }
+                                       }
+  }`,
+      { query: JSON.stringify([{ _id }]) }
+    );
+  };
+  export const reg = async (login, password) => {
+    let query = `mutation reg($l:String! , $p:String!) {
+        createUser(login:$l,password:$p){
+    _id login
+  }
+  }`;
+    let qVariables = {
+      l: login,
+      p: password,
+    };
+    let result = await gql(query, qVariables);
+    return result;
+  };
+  export const 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);
+    return result;
+  };
+  export const imgFind = async () => {
+    return await gql(`query fhbg{
+      ImageFind(query:"[{}]"){
+        url owner{
+          nick
+        }
+      }
+    }`);
+  };
+  export const ava = async (idUser, id) => {
+    let query = `mutation setAvatar($idUser:String , $idAvatar:ID){ 
+      UserUpsert(user:{_id: $idUser, avatar: {_id: $idAvatar}}){
+          _id, avatar{
+              url
+          }
+      }
+  }`;
+    let qVariables = { idUser: idUser, idAvatar: id };
+  
+    let res = await gql(query, qVariables);
+    return res;
+  };
+  export const snippetAdd = async (title, description, files , idSnippet) => {
+    let query = `mutation newSnippet($snippet:SnippetInput) {
+      SnippetUpsert(snippet:$snippet){
+        _id
+      }
+    }`;
+  
+    let qVariables = { snippet: { title, description, files, _id: idSnippet }  };
+  
+    let res = await gql(query, qVariables);
+    return res;
+  };
+
+  export const search = async (string) => {
+    return gql(
+      `query snippetFind($query:String){
+        SnippetFind(query:$query){
+          owner {
+            _id login
+          }
+              title description _id files {
+               type text name
+             }
+          }
+    }`,
+      { query: JSON.stringify([
+        {
+            $or: [{title: `/${string.trim().split(" ").join('|')}/`},{description: `/${string.trim().split(" ").join('|')}/`}] 
+        },
+        {
+          sort: [{title: 1}]}]) }
+    );
+  };
+
+  

+ 9 - 4
React/CodePen/src/components/ava.js

@@ -2,15 +2,20 @@ import React from "react";
 import { connect } from "react-redux";
 import icon from "../icon.jpg";
 
-function AvaLogo({px, mrgn, link}) {
+function AvaLogo({ px, mrgn, link }) {
+  // Import result is the URL of your image
   return (
-    <img src={link ? "http://localhost:3000/" + link : icon} className="ava" 
-    	style={{ width: px, marginRight: mrgn, borderRadius: "50%" }}/>
+    <img
+      src={link ? "http://localhost:3000/" + link : icon}
+      className="ava"
+      style={{ width: px, marginRight: mrgn, borderRadius: "50%" }}
+    />
   );
 }
 
 const ConnectedAvaLogo = connect((state) => ({
   link: state?.promise?.findUser?.payload?.data?.UserFindOne?.avatar?.url,
 }))(AvaLogo);
+//'http://localhost:3000/images/5d6600e2254cff050d32c6967bcf3104'
 
-export default ConnectedAvaLogo;
+export default ConnectedAvaLogo;

+ 10 - 11
React/CodePen/src/components/header.js

@@ -1,19 +1,18 @@
 import React from "react";
-import { connect } from "react-redux";
-import { useState } from "react";
 import ConnectedNick from "./nickHeader";
 import ImgLogo from "./logo";
+import { connect } from "react-redux";
+import { useState } from "react";
 import { actionSearch } from "../actions/actionSearch";
 
-
 const Header = ({onSearch}) => {
-  	const [request, setRequest] = useState('');
-  	return (
-    	<nav className="headerBlock">
-    		<ImgLogo props={{width:"100px"}} className="headerSubBlock1" />
-      		<ConnectedNick className="headerSubBlock2" />
-    	</nav>
-  	);
+  const [request, setRequest] = useState('');
+  return (
+    <nav className="headerBlock">
+      <ImgLogo props={{width:"30%"}} className="headerSubBlock1"/>
+      <ConnectedNick className="headerSubBlock2"/>
+    </nav>
+  );
 };
 
-export default Header;
+export default Header;

+ 2 - 2
React/CodePen/src/components/logo.js

@@ -1,5 +1,5 @@
 import React from "react";
-import logo from "../logo.svg";
+import logo from "../logo.png";
 
 function ImgLogo({props}) {
   return (
@@ -10,4 +10,4 @@ function ImgLogo({props}) {
   );
 }
 
-export default ImgLogo;
+export default ImgLogo;

+ 16 - 0
React/CodePen/src/components/nick.js

@@ -0,0 +1,16 @@
+import { connect } from "react-redux";
+
+const Nick = ({ nick }) => {
+  return (
+    <>
+      <div>
+        <p>{nick}</p>
+      </div>
+    </>
+  );
+};
+
+const ConnectNickName = connect((state) => ({
+  nick: state?.auth?.payload?.sub?.login || 0,
+}))(Nick);
+export default ConnectNickName;

+ 20 - 17
React/CodePen/src/components/nickHeader.js

@@ -7,22 +7,25 @@ import { Link } from "react-router-dom";
 const NickName = ({nick, onLogOut}) => {
   return (
     <>
-      <div style={{position: "relative", left: "50%", paddingTop:"10px"}}>
-          <div>
-              <span style={{color: "black"}}>Your nickname </span>
-              <a href="/cabinet" style={{textDecoration: "none", color: "#5F9EA0"}}>
-                  {nick} &nbsp;&nbsp;
-                  <ConnectedAvaLogo px={"50px"} mrgn={"10px"} />
-              </a>
-              <button className="btn btn-secondary btn-sm" onClick={() => onLogOut()}>
-                  Log out
-              </button>
-          </div>
-          <div style={{}}>
-              <Link to = "/search"> 
-                  <button className="btn btn-info btn-sm">Search</button> 
-              </Link>
-          </div>
+      <div className="container">
+        <div className="">
+           <div>
+                <span style={{color: "black"}}>Your nickname </span>
+                <a href="/cabinet" style={{textDecoration: "none", color: "dark"}}>
+                    {nick} &nbsp;&nbsp;
+                    <ConnectedAvaLogo px={"50px"} mrgn={"10px"} />
+                </a>
+                <button className="btn btn-secondary btn-sm" onClick={() => onLogOut()}>
+                    Log out
+                </button>
+            </div>
+            <div style={{}}>
+                <Link to = "/search"> 
+                    <button className="btn btn-info btn-sm">Search</button> 
+                </Link>
+            </div>
+        </div>
+         
       </div>
     </>
   );
@@ -32,4 +35,4 @@ const ConnectedNick = connect(
   (state) => ({ nick: state?.auth?.payload?.sub?.login , logedIn: state.auth.token}),
   { onLogOut: actionAuthLogout }
 )(NickName);
-export default ConnectedNick;
+export default ConnectedNick;

+ 3 - 2
React/CodePen/src/components/privateRout.js

@@ -5,7 +5,7 @@ import { Redirect,Route } from "react-router"
 const PrivateRoute = ({component,roles,auth, ...originProps}) => {
     const PageWrapper = (pageProps) => {
         const OriginalPage = component
-        if(roles.includes('noname')){
+        if(roles.includes('unknown')){
             return <OriginalPage {...pageProps} />
         }
         if(auth === undefined) {
@@ -18,8 +18,9 @@ const PrivateRoute = ({component,roles,auth, ...originProps}) => {
         return <Redirect to='/login' />
     }
     return (
-        <Route component={PageWrapper} {...originProps} />
+      <Route component={PageWrapper} {...originProps} />
     )
 }
+
 const ConnectedPrivateRoute = connect(state => ({auth: state?.auth?.token}))(PrivateRoute)
 export default ConnectedPrivateRoute

+ 3 - 3
React/CodePen/src/components/profile.js.js

@@ -1,13 +1,13 @@
 import React from "react";
 import wall from "../profileWall.jpeg";
 
-function ImgProfile({ px }) {
+function ImgProfile({props}) {
   return (
     <a href="/">
       {" "}
-      <img src={wall} alt="wall" style={{width: px}} />{" "}
+      <img src={wall} alt="wall" style={{props}} />{" "}
     </a>
   );
 }
 
-export default ImgProfile;
+export default ImgProfile;

+ 25 - 24
React/CodePen/src/components/routes.js

@@ -1,15 +1,16 @@
-import Home from "../pages/mainPage";
-import {LogForm} from "../pages/login";
-import {RegForm} from "../pages/reg";
 import React from "react";
 import createHistory from "history/createBrowserHistory";
 import { connect } from "react-redux";
-import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
-import ConnectedPrivateRoute from "./privateRout";
-import { Redirect } from "react-router";
-import {useEffect, useState, useRef} from "react";
+import RegForm from "../pages/reg";
+import { LogForm } from "../pages/login";
+import Home from "../pages/homePage";
 import ConnectCabinet from "../pages/cabinet";
 import Search from "../pages/search";
+import ConnectedPrivateRoute from "./privateRoute";
+import { Redirect } from "react-router";
+import {useEffect, useState, useRef} from "react";
+import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
+
 
 const LoginForm = ({onLogin}) =>{
   const [login, setLogin] = useState(''); //braunvlad4
@@ -26,22 +27,22 @@ const LoginForm = ({onLogin}) =>{
 }
 
 const Routes = ({ isAuth }) => {
-  console.log(isAuth)
-  console.log('isAuth')
-    return (
-        <div className="App">
-            <div className="contentDiv">
-            <LoginForm onLogin={(l,p)=>console.log(l,p)} />
-                <Switch>
-                    <ConnectedPrivateRoute exact path="/" roles = {['user']} component={Home} />
-                    <ConnectedPrivateRoute path="/cabinet" roles = {['user']} component={ConnectCabinet} />
-                    <ConnectedPrivateRoute path="/search" roles = {['user']} component={Search} />
-                    <ConnectedPrivateRoute path="/login" roles = {['noname']} component={LogForm} /> 
-                    <ConnectedPrivateRoute path="/registration" roles = {['noname']} component={RegForm} />
-                </Switch>
-            </div>
-        </div>
-    );
+  return (
+    <div className="App">
+      <div className="contentDiv">
+          // <LoginForm onLogin={(l,p)=>console.log(l,p)} />
+            <Switch>
+              <ConnectedPrivateRoute exact path="/" roles = {['user']} component={Home} />
+              <ConnectedPrivateRoute path="/cabinet" roles = {['user']} component={ConnectCabinet} />
+              <ConnectedPrivateRoute path="/search" roles = {['user']} component={Search} />
+              <ConnectedPrivateRoute path="/login" roles = {['unknown']} component={LogForm} /> 
+              <ConnectedPrivateRoute path="/registration" roles = {['unknown']} component={RegForm} />
+              </Switch>
+      </div>
+    </div>
+  );
 };
 
-export default Routes
+export default Routes
+
+

BIN
React/CodePen/src/logo.png


+ 26 - 9
React/CodePen/src/pages/cabinet.js

@@ -1,19 +1,36 @@
-import { actionAuthLogout } from "../actions/actionAuthLogout";
 import React from "react";
 import { connect } from "react-redux";
+import ConnectNickName from "../components/nick";
+import ImgProfile from "../components/profile";
+import { actionAuthLogout } from "../actions/actionAuthLogout";
 
-const Cabinet = ({ onLogOut }) => {
+const Cabinet = ({onLogOut}) => {
   return (
     <>
-      <div>
-        <div>
-          <div >
+      <div className="container" >
+        <div className="card">
+          <div className="upper">
+            <ImgProfile px={"300px"} />{" "}
+          </div>
+          <div>
+            <div>
+              {" "}
+            </div>
+          </div>
+          <div>
+            <h4>
+              <ConnectNickName />
+            </h4>
             <a href="/projects">
-              <button type="button">My Projects</button>
+              <button type="button">
+                My Projects
+              </button>
             </a>
             <div>
               <a href="/">
-                <button>Main Page</button>
+                <button>
+                  Main Page
+                </button>
               </a>
             </div>
             <button onClick={() => onLogOut()}>Log out</button>
@@ -24,6 +41,6 @@ const Cabinet = ({ onLogOut }) => {
   );
 };
 
-const ConnectCabinet = connect(null, { onLogOut: actionAuthLogout })(Cabinet);
+const ConnectCabinet = connect(null, {onLogOut: actionAuthLogout})(Cabinet);
 
-export default ConnectCabinet;
+export default ConnectCabinet;

+ 13 - 0
React/CodePen/src/pages/homePage.js

@@ -0,0 +1,13 @@
+import React from "react";
+import Header from "../components/header";
+
+
+const Home = () => {
+  	return (
+    	<div>
+      		<Header />
+    	</div>
+  	);
+};
+
+export default Home;

+ 8 - 7
React/CodePen/src/pages/login.js

@@ -1,6 +1,6 @@
-import { actionFullLogin } from "../actions/actionFullLogin";
 import { connect } from "react-redux";
 import { useState } from "react";
+import { actionFullLogin } from "../actions/actionFullLogin";
 import { Redirect } from "react-router";
 
 const Log = ({ onLog, LogedIn }) => {
@@ -26,12 +26,12 @@ const Log = ({ onLog, LogedIn }) => {
                     <i className=""></i>
                   </span>
                   <input id="login-username" type="text" className="form-control" 
-                  		name="username" value={login} placeholder="Login"
-                    	onChange={ e =>{
+                      name="username" value={login} placeholder="Login"
+                      onChange={ e =>{
                           console.log(e.target.value)
                           setLogin(e.target.value) && <Redirect to ="/"/>
                         } 
-                      }	
+                      } 
                   />
                 </div>
                 <div style={{ marginBottom: "25px" }} className="input-group">
@@ -40,7 +40,7 @@ const Log = ({ onLog, LogedIn }) => {
                   </span>
                   <input id="login-password" type="password" className="form-control"
                     name="password" placeholder="Password" value={password}
-                 	onChange={(e) => setPassword(e.target.value)}
+                  onChange={(e) => setPassword(e.target.value)}
                   />
                 </div>
                 <div style={{ marginTop: "10px" }} className="form-group">
@@ -66,5 +66,6 @@ const Log = ({ onLog, LogedIn }) => {
   );
 };
 
-export const LogForm = connect((state) => ({ LogedIn: state?.auth?.token }), {onLog: actionFullLogin})(Log);
-
+export const LogForm = connect((state) => ({ LogedIn: state?.auth?.token }), {
+  onLog: actionFullLogin,
+})(Log);

+ 0 - 12
React/CodePen/src/pages/mainPage.js

@@ -1,12 +0,0 @@
-import Header from "../components/header";
-import React from "react";
-
-const Main = () =>{
-	return (
-		<div>
-			<Header />
-		</div>
-	)
-}
-
-export default Main;

+ 2 - 1
React/CodePen/src/pages/reg.js

@@ -53,7 +53,8 @@ const Reg = ({ onReg, LogedIn }) => {
   );
 };
 
-export const RegForm = connect((state) => ({ LogedIn: state?.auth?.token }), {
+const RegForm = connect((state) => ({ LogedIn: state?.auth?.token }), {
   onReg: actionFullRegister,
 })(Reg);
 
+export default RegForm;

+ 1 - 1
React/CodePen/src/pages/search.js

@@ -56,4 +56,4 @@ const Search = ({onSearch , snippets}) => {
 
 const CSearch = connect(state => ({snippets:state?.promise?.searchSnippet?.payload?.data?.SnippetFind}) , {onSearch:actionSearch})(Search)
 
-export default CSearch;
+export default CSearch;

+ 4 - 4
React/CodePen/src/reducers/authReducer.js

@@ -11,11 +11,11 @@ const jwtDecode = token => {
 function authReducer(state, { type, token }) {
     if (!state) {
         if (localStorage.authToken) {
-            type = 'AUTH_LOGIN'
+            type = 'LOGIN'
             token = localStorage.authToken
         } else state = {}
     }
-    if (type === 'AUTH_LOGIN') {
+    if (type === 'LOGIN') {
         localStorage.setItem('authToken', token)
         let payload = jwtDecode(token)
         if (typeof payload === 'object') {
@@ -26,11 +26,11 @@ function authReducer(state, { type, token }) {
             }
         } else return state
     }
-    if (type === 'AUTH_LOGOUT') {
+    if (type === 'LOGOUT') {
         localStorage.removeItem('authToken')
         return {}
     }
     return state
 }
 
-export default authReducer
+export default authReducer;

+ 13 - 11
React/CodePen/src/reducers/promiseReducer.js

@@ -1,11 +1,13 @@
-function promiseReducer(state = {}, {type, status, payload, error, name}) {
-    if (type === 'PROMISE') {
-        return {
-            ...state,
-            [name]: { status, payload, error }
-        }
-    }
-    return state;
-};
-
-export default promiseReducer
+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;
+}
+export default promiseReducer;

+ 13 - 19
React/CodePen/src/reducers/store.js

@@ -1,28 +1,22 @@
+import { createStore, combineReducers, applyMiddleware } from "redux";
+import thunk from "redux-thunk";
 import promiseReducer from "./promiseReducer";
 import authReducer from "./authReducer";
-import {createStore, combineReducers, applyMiddleware} from "redux";
-import thunk from "redux-thunk";
 import { actionFindUser } from "../actions/actionFindUser";
-
-
-// function promiseReducer(state = {}, { type, status, payload, error, name }) {
-//     if (type === 'PROMISE') {
-//         return {
-//             ...state,
-//             [name]: { status, payload, error }
-//         }
-//     }
-//     return state;
-// }
-
+import { actionSnippetFindByOwner } from "../actions/actionSnippetFindByOwner";
 
 export const store = createStore(
-	combineReducers({promise: promiseReducer, auth: authReducer}),
-	applyMiddleware(thunk)
+  combineReducers({promise: promiseReducer,auth: authReducer}),
+  applyMiddleware(thunk)
 );
 
-store.subscribe(() => console.log("result here", store.getState()));
+store.subscribe(() =>
+  console.log(store.getState())
+);
 
 if (localStorage.authToken) {
-  	store.dispatch(actionFindUser());
-}
+  store.dispatch(actionFindUser());
+  store.dispatch(
+    actionSnippetFindByOwner(store.getState().auth.payload.sub.id)
+  );
+}

BIN
React/CodePen/src/user.png