Browse Source

авторизуется , ну и хорошо

Maik 3 years ago
parent
commit
a8e56c3763
4 changed files with 105 additions and 49 deletions
  1. 1 0
      back/index.js
  2. 4 5
      back/router/authorization.js
  3. 51 44
      front/src/App.js
  4. 49 0
      front/src/actions/user.js

+ 1 - 0
back/index.js

@@ -6,6 +6,7 @@ const corsMiddleware = require("./middleware/cors")
 const PORT = config.get('serverPort')
 const app = express()
 
+app.use(corsMiddleware)
 app.use(express.json())
 app.use('/api/authorization',authRouter)
 app.use(corsMiddleware)

+ 4 - 5
back/router/authorization.js

@@ -1,7 +1,7 @@
 const Router = require("express");
 const User = require("../models/User");
 const config = require("config")
-const bcript = require("bcryptjs")
+const bcrypt = require("bcryptjs")
 const jwt = require('jsonwebtoken')
 const {check, validationResult} = require('express-validator')
 const routers = new Router();
@@ -27,7 +27,7 @@ routers.post(
             if(candidate){
                 return res.status(400).json({message:"this email already exists"})
             }
-            const hashPass = await bcript.hash(password,5)
+            const hashPass = await bcrypt.hash(password,5)
             const user = new User({email, password: hashPass})
             await user.save()
             return res.json({message:"User created"})
@@ -46,9 +46,9 @@ routers.post(
             if(!user){
                 return res.status(404).json({message:"Email not found"})
             }
-            const validPass= bcript.compareSync(password,user.password)
+            const validPass= bcrypt.compareSync(password,user.password)
             if(!validPass){
-                return res.status(400).json({massage:"invalid password"})
+                return res.status(400).json({message:"invalid password"})
             }
             const token = jwt.sign({id: user.id},config.get("jwtKey"),{expiresIn:"1h"})
             return res.json({
@@ -56,7 +56,6 @@ routers.post(
                 user:{
                     id: user.id,
                     email: user.email,
-
                 }
             })
         }catch(e){

+ 51 - 44
front/src/App.js

@@ -4,6 +4,7 @@ import { useState , useEffect , dispatch ,response} from 'react';
 import { useHttp  } from './hooks/httpReqest'
 import { setUser , logout } from './reducers/userR';
 import {useSelector , useDispatch} from 'react-redux'
+import {registration,login,auth } from "./actions/user"
 
 import AceEditor from "react-ace";
 import "ace-builds/src-noconflict/mode-html";
@@ -13,13 +14,20 @@ import "ace-builds/src-noconflict/theme-terminal";
 import "ace-builds/src-noconflict/ext-language_tools"
 
 const Sandbox =()=>{
+  const {request}=useHttp()
+  const dispatch = useDispatch()
+  let user 
 
+  let title
   let codeHTML 
   let codeCSS 
   let codeJS 
-  let title
 
-  let saveProject 
+  const  saveProject = async () => {
+    try {
+      const data = await request('/api/authorization/registration', 'POST', {user,title,codeHTML,codeCSS,codeJS})
+    } catch (e) {console.log(e)}
+  }
 
   const htmlCodeGenerator=(codeHTML)=>{
     const htmlOutput = document.getElementById("htmlOutput")
@@ -76,6 +84,7 @@ const AuthorizationLogin = () =>{
   const [passwordError,setPasswordError]=useState('password empty')
   const {request}=useHttp()
   const dispatch = useDispatch()
+
   const emailHandler = (e)=>{
     setEmail(e.target.value)
     const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
@@ -85,6 +94,7 @@ const AuthorizationLogin = () =>{
       setEmailError("")
     }
   }
+
   const passwordHandler = (e)=>{
     setPassword(e.target.value)
     if(e.target.value.length<=3){
@@ -93,6 +103,7 @@ const AuthorizationLogin = () =>{
       setPasswordError('')
     }
   }
+
   const outInput = (e) =>{
     switch(e.target.name){
       case 'email':
@@ -103,18 +114,8 @@ const AuthorizationLogin = () =>{
       break;
     }
   }
-  const loginHandler = (email,password)=>{
-    return async dispatch =>{
-      try{
-        const response = await request('/api/authorization/login', 'POST', {email,password})
-        dispatch(setUser(response.user))
-        localStorage.setItem('token',response.token)
-        console.log(response.user)
-      }catch (e){
-        console.log(e.message)
-      }
-    }
-  }
+
+
   return(
     <fieldset className="logForm">
       <legend className="lr_title">Login</legend>
@@ -127,7 +128,7 @@ const AuthorizationLogin = () =>{
           <legend>Password</legend>
           <input onChange={e => passwordHandler(e)}value={password} onBlur={e=>outInput(e)} name='password' className='password'  type="password" placeholder='Enter you password...'/>
         </fieldset>
-        <button className='submitLR' type='button' onClick={()=>dispatch(loginHandler(email,password))}>Login</button>
+        <button className='submitLR' type='button' onClick={()=>dispatch(login(email,password))}>Login</button>
         {(emailWrong&&emailError)&& <p style={{color:'orange'}}>{emailError}</p>}
         {(passwordWrong&&passwordError) && <p style={{color:'orange'}}>{passwordError}</p>}
       </form>
@@ -135,19 +136,15 @@ const AuthorizationLogin = () =>{
     </fieldset>
   )
 }
+
 const AuthorizationRegistration = () =>{
+
   const [email,setEmail]=useState('')
   const [password,setPassword]=useState('')
   const [emailWrong, setEmailWrong]=useState(false)
   const [passwordWrong, setPasswordWrong]=useState(false)
   const [emailError,setEmailError]=useState('email empty')
   const [passwordError,setPasswordError]=useState('password empty')
-  const {request}=useHttp()
-  const registrationHandler = async () => {
-    try {
-      const data = await request('/api/authorization/registration', 'POST', {email,password})
-    } catch (e) {setEmailError(e.message)}
-  }
 
   const emailHandler = (e)=>{
     setEmail(e.target.value)
@@ -188,7 +185,7 @@ const AuthorizationRegistration = () =>{
           <legend>Password</legend>
           <input onChange={e => passwordHandler(e)}value={password} onBlur={e=>outInput(e)} name='password' className='password'  type="password" placeholder='Enter you password...'/>
         </fieldset>
-        <button className='submitLR' type='button' onClick={registrationHandler}>Registration</button>
+        <button className='submitLR' type='button' onClick={()=> registration(email,password)}>Registration</button>
         {(emailWrong&&emailError)&& <p style={{color:'orange'}}>{emailError}</p>}
         {(passwordWrong&&passwordError) && <p style={{color:'orange'}}>{passwordError}</p>}
       </form>
@@ -198,38 +195,46 @@ const AuthorizationRegistration = () =>{
 }
 
 
+const MyProject=()=>{
+  return(
+    <fieldset className="project">
+        <legend>My Project</legend>
+        <ul className="myProject">
+          <li className="creatorProject"><a href="/">++++++++++CREATE+A+NEW+PROJECT++++++++++</a></li>
+        </ul>
+    </fieldset>
+  )
+}
+const Project=()=>{
+  return(
+    <fieldset className="project">
+        <legend>Project</legend>
+        <ul className="worldProject">
+          <li className="creatorProject"><a href="/">++++++++++CREATE+A+NEW+PROJECT++++++++++</a></li>
+        </ul>
+    </fieldset>
+  )
+}
 
 
 const App =()=>{
-  const isAuthorization = useSelector(state => state.user.isAuth)
-  const dispatch =useDispatch()
-  const {request}=useHttp()
+  const isAuth = useSelector(state => state.user.isAuth)
+  const dispatch = useDispatch()
 
-  const authorization =() =>{
-    return async dispatch =>{
-      try{
-        const response = await request('/api/authorization', 'GET',  {headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}})
-        dispatch(setUser(response.user))
-        localStorage.setItem('token', response.token)
-      }catch(e){
-        console.log(e)
-        localStorage.removeItem('token')
-      }
-    }
-  }
-  useEffect(()=>{
-    dispatch(authorization())
-  },[])
+  useEffect(() => {
+      dispatch(auth())
+  }, [])
   return(
         <BrowserRouter>
           <div className="navBar">
             <h1 className="logo"><a href="/">SandBox</a></h1>
-            <a href="/Project" className="links">Project</a>
-            <a href="/my_project" className="links">My project</a>
             <a href="/" className="links">Sandbox</a>
-            {isAuthorization && <a onClick={()=>dispatch(logout())} className="links" style={{cursor:"pointer"}}>Exit</a>}
+            {isAuth && <a href="/my_project" className="links">My project</a>}
+            <a href="/Project" className="links">Project</a>
+            {isAuth && <a onClick={()=>dispatch(logout())} className="links" style={{cursor:"pointer"}}>Exit</a>}
+            {!isAuth && <a href="/login" className="links" style={{cursor:"pointer"}}>Login</a>}
           </div>
-          {!isAuthorization &&
+          {!isAuth &&
           <Switch>
             <Route path="/login" component={AuthorizationLogin}/>
             <Route path="/registration" component={AuthorizationRegistration}/>
@@ -237,6 +242,8 @@ const App =()=>{
           }
           <Switch>
             <Route path="/" component={Sandbox} exact/>
+            <Route path="/MyProject" component={MyProject} exact/>
+            <Route path="/Project" component={Project} exact/>
           </Switch>
         </BrowserRouter>)
 }

+ 49 - 0
front/src/actions/user.js

@@ -0,0 +1,49 @@
+import axios from 'axios'
+import {setUser} from "../reducers/userR";
+
+export const registration = async (email, password) => {
+    try {
+        const response = await axios.post(`http://localhost:4000/api/authorization/registration`, { email,password})
+        console.log(response.data.message)
+    } catch (e) {
+        console.log(e.response.data.message)
+    }
+}
+
+export const login =  (email, password) => {
+    return async dispatch => {
+        try {
+            const response = await axios.post(`http://localhost:4000/api/authorization/login`, {email,password})
+            dispatch(setUser(response.data.user))
+            localStorage.setItem('token', response.data.token)
+        } catch (e) {
+            console.log(e.response.data.message)
+        }
+    }
+}
+
+export const auth =  () => {
+    return async dispatch => {
+        try {
+            const response = await axios.get(`http://localhost:4000/api/authorization/auth`,{headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}})
+            dispatch(setUser(response.data.user))
+            localStorage.setItem('token', response.data.token)
+        } catch (e) {
+            localStorage.removeItem('token')
+        }
+    }
+}
+// export const auth =  () => {
+//     return async dispatch => {
+//         try {
+//             const response = await axios.get(`http://localhost:5000/api/auth/auth`,
+//                 {headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}}
+//             )
+//             dispatch(setUser(response.data.user))
+//             localStorage.setItem('token', response.data.token)
+//         } catch (e) {
+//             alert(e.response.data.message)
+//             localStorage.removeItem('token')
+//         }
+//     }
+// }