Browse Source

integrated login and register

sunguroku 5 năm trước cách đây
mục cha
commit
4570983c12

+ 71 - 58
dashboard/src/App.tsx

@@ -3,75 +3,18 @@ import styled, { createGlobalStyle } from 'styled-components';
 
 import { ContextProvider } from './shared/Context';
 import Main from './main/Main';
-import Login from './main/Login';
-import Register from './main/Register';
-import Home from './main/home/Home';
-import api from './shared/api';
 
-import {
-  BrowserRouter,
-  Switch,
-  Route,
-  Link,
-  Redirect
-} from 'react-router-dom';
 type PropsType = {
 };
 
 type StateType = {
-  isLoggedIn: boolean
-  uninitialized: boolean,
 };
 
 export default class App extends Component<PropsType, StateType> {
-  
-  state = {
-    isLoggedIn: false,
-    uninitialized: false
-  }
-
-  componentDidMount() {
-    api.checkAuth('', {}, {}, (err: any, res: any) => {
-      console.log(res.data)
-      if (res.data) {
-        this.setState({ isLoggedIn: true, uninitialized: false})
-      } else {
-        this.setState({ isLoggedIn: false, uninitialized: true })
-      }
-
-      localStorage.getitem("init") ? this.setState({uninitialized: false}) : this.setState({uninitialized: true})
-      // err ? setCurrentError(JSON.stringify(err)) : authenticate();
-    });
-  }
-
-
   render() {
     return (
       <ContextProvider>
-        <BrowserRouter>
-          <Switch>
-            <Route path='/login' render={() => {
-              if (this.state.isLoggedIn) {
-                return <Redirect to='/dashboard' />
-              } else {
-                return <Login authenticate={() => this.setState({ isLoggedIn: true })} />
-              }
-            }} />
-
-            <Route path='/register' render={() => <Register authenticate={() => this.setState({ isLoggedIn: true })} />} />
-            <Route path='/dashboard' render={() => <Home logOut={() => this.setState({ isLoggedIn: false })} />}/>
-            <Route path='/' render={() => {
-              if (this.state.isLoggedIn) {
-                return <Redirect to='/dashboard'/>
-              } else if (!this.state.uninitialized) {
-                return <Redirect to='/login'/>
-              } else {
-                return <Redirect to='/register' />
-              }
-            }}/>
-          </Switch>
-        </BrowserRouter>
-        {/* <Main /> */}
+        <Main />
       </ContextProvider>
     );
   }
@@ -92,3 +35,73 @@ const StyledApp = styled.div`
   background: #24272a;
   color: white;
 `;
+
+const StyledMain = styled.div`
+  height: 100vh;
+  width: 100vw;
+  position: fixed;
+  top: 0;
+  left: 0;
+  background: #24272a;
+  color: white;
+`;
+
+
+const CloseButton = styled.div`
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  width: 30px;
+  height: 30px;
+  border-radius: 50%;
+  margin-left: 10px;
+  cursor: pointer;
+  :hover {
+    background-color: #ffffff11;
+  }
+`;
+
+const CloseButtonImg = styled.img`
+  width: 10px;
+`;
+
+const ErrorText = styled.div`
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  width: calc(100% - 50px);
+`;
+
+const CurrentError = styled.div`
+  position: fixed;
+  bottom: 20px;
+  width: 300px;
+  left: 17px;
+  padding: 15px;
+  padding-right: 0px;
+  font-family: 'Work Sans', sans-serif;
+  height: 50px;
+  font-size: 13px;
+  border-radius: 3px;
+  background: #383842dd;
+  border: 1px solid #ffffff55;
+  display: flex;
+  align-items: center;
+
+  > i {
+    font-size: 18px;
+    margin-right: 10px;
+  }
+
+  animation: floatIn 0.5s;
+  animation-fill-mode: forwards;
+
+  @keyframes floatIn {
+    from {
+      opacity: 0; transform: translateY(20px);
+    }
+    to {
+      opacity: 1; transform: translateY(0px);
+    }
+  }
+`;

+ 61 - 29
dashboard/src/main/Main.tsx

@@ -2,51 +2,47 @@ import React, { Component } from 'react';
 import styled, { createGlobalStyle } from 'styled-components';
 import close from '../assets/close.png';
 
+import api from '../shared/api';
 import { Context } from '../shared/Context';
 
 import Login from './Login';
 import Register from './Register';
 import Home from './home/Home';
+import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom';
 
 type PropsType = {
 };
 
 type StateType = {
   isLoading: boolean,
-  isLoggedIn: boolean
-  uninitialized: boolean,
+  isLoggedIn: boolean,
+  initialized: boolean,
 };
 
 export default class Main extends Component<PropsType, StateType> {
+  
   state = {
     isLoading: false,
-    isLoggedIn: true,
-    uninitialized: true,
-  };
+    isLoggedIn : false,
+    initialized: false
+  }
 
   componentDidMount() {
-    // let user = localStorage.getItem('user')
-    // console.log(user);
-    // // Check if Porter has already been initialized
-    // if (user) {
-    //   this.setState({ uninitialized: true })
-    //   // Check if user is logged in
-    //   if (user) {
-    //     this.setState({ isLoggedIn: true });
-    //   }
-    // }
+    localStorage.getItem("init") == 'true' ? this.setState({initialized: true}) : this.setState({initialized: false})
+    api.checkAuth('', {}, {}, (err: any, res: any) => {
+      if (res.data) {
+        this.setState({ isLoggedIn: true, initialized: true})
+      } else {
+        this.setState({ isLoggedIn: false })
+      }
+
+      // err ? setCurrentError(JSON.stringify(err)) : authenticate();
+    });
+  }
+  initialize = () => {
+    this.setState({isLoggedIn: true, initialized: true});
+    localStorage.setItem('init', 'true');
   }
-
-  renderContents = (): JSX.Element => {
-    if (this.state.isLoading) {
-      return <h1>Loading...</h1>
-    } else if (this.state.isLoggedIn) {
-      return <Home logOut={() => this.setState({ isLoggedIn: false })} />
-    } else if (this.state.uninitialized) {
-      return <Register authenticate={() => this.setState({ isLoggedIn: true })} />
-    }
-    return <Login authenticate={() => this.setState({ isLoggedIn: true })} />
-  };
 
   renderCurrentError = (): JSX.Element | undefined => {
     if (this.context.currentError) {
@@ -63,11 +59,47 @@ export default class Main extends Component<PropsType, StateType> {
 
   render() {
     return (
+
       <StyledMain>
         <GlobalStyle />
-        {/* {this.renderContents()} */}
-
-        {this.renderCurrentError()}
+        <BrowserRouter>
+          <Switch>
+            <Route path='/login' render={() => {
+              if (this.state.isLoggedIn) {
+                return <Redirect to='/' />
+              } else {
+                return <Login authenticate={() => this.setState({ isLoggedIn: true, initialized: true })} />
+              }
+            }} />
+
+            <Route path='/register' render={() => {
+              if (this.state.initialized) {
+                return <Redirect to='/' />
+              } else {
+                return <Register authenticate={this.initialize} />
+              }
+            }} />
+
+            <Route path='/dashboard' render={() => {
+              if (!this.state.isLoggedIn) {
+                return <Redirect to='/' />
+              } else {
+                return <Home logOut={() => this.setState({ isLoggedIn: false, initialized: true })} />
+              }
+            }}/>
+
+            <Route path='/' render={() => {
+              if (this.state.isLoggedIn) {
+                return <Redirect to='/dashboard'/>
+              } else if (this.state.initialized) {
+                return <Redirect to='/login'/>
+              } else {
+                return <Redirect to='/register' />
+              }
+            }}/>
+          </Switch>
+        </BrowserRouter>
+        {this.renderCurrentError()} */}
       </StyledMain>
     );
   }

+ 1 - 0
dashboard/src/main/Register.tsx

@@ -48,6 +48,7 @@ export default class Register extends Component<PropsType, StateType> {
         email: email,
         password: password
       }, {}, (err: any, res: any) => {
+        console.log('err',err)
         err ? setCurrentError(JSON.stringify(err)) : authenticate();
       });
     } 

+ 1 - 0
dashboard/src/shared/Context.tsx

@@ -30,6 +30,7 @@ class ContextProvider extends Component {
     },
     currentError: null as string | null,
     setCurrentError: (currentError: string): void => {
+      console.log('setting err', currentError)
       this.setState({ currentError });
     },
     currentCluster: null as string | null,

+ 4 - 0
dashboard/webpack.config.js

@@ -52,6 +52,10 @@ module.exports = () => {
     output: {
       filename: 'bundle.js',
       path: path.resolve(__dirname, 'build'),
+      publicPath: '/'
+    },
+    devServer: {
+      historyApiFallback: true,
     },
     plugins: [
       new HtmlWebpackPlugin({

+ 25 - 24
server/api/user_handler.go

@@ -9,6 +9,7 @@ import (
 	"strings"
 
 	"github.com/porter-dev/porter/internal/kubernetes"
+	"golang.org/x/crypto/bcrypt"
 
 	"gorm.io/gorm"
 
@@ -80,40 +81,40 @@ func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
 		app.handleErrorDataRead(err, ErrUserDataRead, w)
 	}
 
-	// form := &forms.LoginUserForm{}
-	// // decode from JSON to form value
-	// if err := json.NewDecoder(r.Body).Decode(form); err != nil {
-	// 	app.handleErrorFormDecoding(err, ErrUserDecode, w)
-	// 	return
-	// }
+	form := &forms.LoginUserForm{}
+	// decode from JSON to form value
+	if err := json.NewDecoder(r.Body).Decode(form); err != nil {
+		app.handleErrorFormDecoding(err, ErrUserDecode, w)
+		return
+	}
 
-	// storedUser, readErr := app.repo.User.ReadUserByEmail(form.Email)
+	storedUser, readErr := app.repo.User.ReadUserByEmail(form.Email)
 
-	// if readErr != nil {
-	// 	app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
-	// 		Errors: []string{"email not registered"},
-	// 		Code:   http.StatusUnauthorized,
-	// 	}, w)
+	if readErr != nil {
+		app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
+			Errors: []string{"email not registered"},
+			Code:   http.StatusUnauthorized,
+		}, w)
 
-	// 	return
-	// }
+		return
+	}
 
-	// if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
-	// 	app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
-	// 		Errors: []string{"incorrect password"},
-	// 		Code:   http.StatusUnauthorized,
-	// 	}, w)
+	if err := bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(form.Password)); err != nil {
+		app.sendExternalError(readErr, http.StatusUnauthorized, HTTPError{
+			Errors: []string{"incorrect password"},
+			Code:   http.StatusUnauthorized,
+		}, w)
 
-	// 	return
-	// }
+		return
+	}
 
 	// Set user as authenticated
 	session.Values["authenticated"] = true
-	// session.Values["user_id"] = storedUser.ID
+	session.Values["user_id"] = storedUser.ID
 	if err := session.Save(r, w); err != nil {
-		// app.logger.Warn().Msgf()
-		fmt.Println(err)
+		app.logger.Warn().Err(err)
 	}
+
 	w.WriteHeader(http.StatusOK)
 }
 

+ 0 - 10
server/router/router.go

@@ -2,7 +2,6 @@ package router
 
 import (
 	"github.com/go-chi/chi"
-	"github.com/go-chi/cors"
 	"github.com/porter-dev/porter/server/api"
 	"github.com/porter-dev/porter/server/requestlog"
 	"github.com/porter-dev/porter/server/router/middleware"
@@ -19,15 +18,6 @@ func New(a *api.App, store *sessionstore.PGStore, cookieName string) *chi.Mux {
 	r.Route("/api", func(r chi.Router) {
 		r.Use(middleware.ContentTypeJSON)
 
-		r.Use(cors.Handler(cors.Options{
-			AllowedOrigins:   []string{"http://localhost:5000"},
-			AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
-			AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
-			ExposedHeaders:   []string{"Link"},
-			AllowCredentials: true,
-			MaxAge:           300, // Maximum value not ignored by any of major browsers
-		}))
-
 		// /api/users routes
 		r.Method("GET", "/users/{id}", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleReadUser, l)))
 		r.Method("GET", "/users/{id}/clusters", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleReadUserClusters, l)))