sunguroku пре 5 година
родитељ
комит
943900a673

+ 2 - 0
.gitignore

@@ -1 +1,3 @@
 .DS_Store
+.env
+app

Разлика између датотеке није приказан због своје велике величине
+ 317 - 121
dashboard/package-lock.json


+ 1 - 1
dashboard/package.json

@@ -29,7 +29,7 @@
   },
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
-    "start": "webpack-dev-server --open",
+    "start": "webpack-dev-server --open --port 3000",
     "build": "webpack"
   },
   "devDependencies": {

+ 8 - 12
dashboard/server.js

@@ -8,20 +8,16 @@ app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(express.static(path.join(__dirname, 'build')))
 
-app.get('/auth/check', (req, res) => {
-    if (req.cookie) {
-        return true
-    } else {
-        return false
-    }
-})
+// app.get('/auth/check', (req, res) => {
+//     if (req.cookie) {
+//         return true
+//     } else {
+//         return false
+//     }
+// })
 
 app.get('/*', (req, res) => {
-    if (!req.cookie) {
-        res.redirect('/login')
-    } else {
-        res.sendFile(path.join(__dirname, 'build', 'index.html'))
-    }
+    res.sendFile(path.join(__dirname, 'build', 'index.html'))
 })
 
 app.listen(5000, () => {

+ 3 - 0
dashboard/src/App.tsx

@@ -38,6 +38,8 @@ export default class App extends Component<PropsType, StateType> {
       } else {
         this.setState({ isLoggedIn: false, uninitialized: true })
       }
+
+      localStorage.getitem("init") ? this.setState({uninitialized: false}) : this.setState({uninitialized: true})
       // err ? setCurrentError(JSON.stringify(err)) : authenticate();
     });
   }
@@ -55,6 +57,7 @@ export default class App extends Component<PropsType, StateType> {
                 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={() => {

+ 1 - 8
dashboard/src/main/Login.tsx

@@ -62,14 +62,7 @@ export default class Login extends Component<PropsType, StateType> {
       );
     }
   }
-
-  componentDidMount() {
-    api.checkAuth('', {}, {}, (err: any, res: any) => {
-      console.log(res.data)
-      // err ? setCurrentError(JSON.stringify(err)) : authenticate();
-    });
-  }
-
+  
   render() {
     let { email, password, credentialError, emailError } = this.state;
 

+ 4 - 6
dashboard/src/shared/baseApi.tsx

@@ -18,7 +18,7 @@ export const baseApi = <T extends {}, S = {}>(requestType: string, endpoint: ((p
 
     // Handle request type (can refactor)
     if (requestType === 'POST') {
-      axios.post(`http://localhost:8080${endpointString}`, params, {
+      axios.post(`http://${baseUrl + endpointString}`, params, {
       headers: {
           Authorization: `Bearer ${token}`
         }
@@ -30,7 +30,7 @@ export const baseApi = <T extends {}, S = {}>(requestType: string, endpoint: ((p
         callback && callback(err, null);
       });
     } else if (requestType === 'PUT') {
-      axios.put(`http://localhost:8080/${endpointString}`, params, {
+      axios.put(`http://${baseUrl + endpointString}`, params, {
         headers: {
           Authorization: `Bearer ${token}`
         }
@@ -42,10 +42,8 @@ export const baseApi = <T extends {}, S = {}>(requestType: string, endpoint: ((p
         callback && callback(err, null);
       });
     } else {
-      axios.get(`http://localhost:8080${endpointString}`, {
-        headers: {
-          Authorization: `Bearer ${token}`
-        },
+      axios.get(`http://${baseUrl + endpointString}`, {
+        withCredentials: true,
         params
       })
       .then(res => {

+ 16 - 16
docker-compose.yaml

@@ -29,22 +29,22 @@ services:
     volumes:
       - db:/var/lib/postgresql/data
 
-  metabase:
-    image: metabase/metabase
-    restart: always
-    ports: 
-      - 3000:3000
-    volumes: 
-      - metabase:/metabase-data
-    environment:
-      MB_DB_TYPE: postgres
-      MB_DB_DBNAME: porter
-      MB_DB_PORT: 5432
-      MB_DB_USER: porter
-      MB_DB_PASS: porter
-      MB_DB_HOST: postgres
-    depends_on:
-      - postgres
+  # metabase:
+  #   image: metabase/metabase
+  #   restart: always
+  #   ports: 
+  #     - 3000:3000
+  #   volumes: 
+  #     - metabase:/metabase-data
+  #   environment:
+  #     MB_DB_TYPE: postgres
+  #     MB_DB_DBNAME: porter
+  #     MB_DB_PORT: 5432
+  #     MB_DB_USER: porter
+  #     MB_DB_PASS: porter
+  #     MB_DB_HOST: postgres
+  #   depends_on:
+  #     - postgres
 
 volumes:
   db:

+ 2 - 1
docker/.env

@@ -9,4 +9,5 @@ DB_HOST=postgres
 DB_PORT=5432
 DB_USER=porter
 DB_PASS=porter
-DB_NAME=porter
+DB_NAME=porter
+COOKIE_SECRETS=secret

+ 1 - 0
go.mod

@@ -8,6 +8,7 @@ require (
 	github.com/creack/pty v1.1.11 // indirect
 	github.com/fatih/color v1.9.0 // indirect
 	github.com/go-chi/chi v4.1.2+incompatible
+	github.com/go-chi/cors v1.1.1
 	github.com/go-playground/locales v0.13.0
 	github.com/go-playground/universal-translator v0.17.0
 	github.com/go-playground/validator/v10 v10.3.0

+ 2 - 0
go.sum

@@ -90,6 +90,8 @@ github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2H
 github.com/go-chi/chi v1.0.0 h1:s/kv1cTXfivYjdKJdyUzNGyAWZ/2t7duW1gKn5ivu+c=
 github.com/go-chi/chi v4.1.2+incompatible h1:fGFk2Gmi/YKXk0OmGfBh0WgmN3XB8lVnEyNz34tQRec=
 github.com/go-chi/chi v4.1.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ=
+github.com/go-chi/cors v1.1.1 h1:eHuqxsIw89iXcWnWUN8R72JMibABJTN/4IOYI5WERvw=
+github.com/go-chi/cors v1.1.1/go.mod h1:K2Yje0VW/SJzxiyMYu6iPQYa7hMjQX2i/F491VChg1I=
 github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
 github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
 github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=

+ 3 - 1
internal/auth/sessionstore.go

@@ -111,7 +111,9 @@ func (store *PGStore) save(session *sessions.Session) error {
 
 // NewStore takes an initialized db and session key pairs to create a session-store in postgres db.
 func NewStore(repo *repository.Repository, conf config.ServerConf) (*PGStore, error) {
-	keyPairs := conf.CookieSecrets
+	keyPairs := [][]byte{
+		conf.CookieSecret,
+	}
 
 	dbStore := &PGStore{
 		Codecs: securecookie.CodecsFromPairs(keyPairs...),

+ 6 - 6
internal/config/config.go

@@ -16,12 +16,12 @@ type Conf struct {
 
 // ServerConf is the server configuration
 type ServerConf struct {
-	Port          int           `env:"SERVER_PORT,default=8080"`
-	CookieName    string        `env:"COOKIE_NAME,default=porter"`
-	CookieSecrets [][]byte      `env:"COOKIE_SECRETS,default=secret"`
-	TimeoutRead   time.Duration `env:"SERVER_TIMEOUT_READ,default=5s"`
-	TimeoutWrite  time.Duration `env:"SERVER_TIMEOUT_WRITE,default=10s"`
-	TimeoutIdle   time.Duration `env:"SERVER_TIMEOUT_IDLE,default=15s"`
+	Port         int           `env:"SERVER_PORT,default=8080"`
+	CookieName   string        `env:"COOKIE_NAME,default=porter"`
+	CookieSecret []byte        `env:"COOKIE_SECRETS,default=secret"`
+	TimeoutRead  time.Duration `env:"SERVER_TIMEOUT_READ,default=5s"`
+	TimeoutWrite time.Duration `env:"SERVER_TIMEOUT_WRITE,default=10s"`
+	TimeoutIdle  time.Duration `env:"SERVER_TIMEOUT_IDLE,default=15s"`
 }
 
 // DBConf is the database configuration: if generated from environment variables,

+ 31 - 27
server/api/user_handler.go

@@ -3,12 +3,12 @@ package api
 import (
 	"encoding/json"
 	"errors"
+	"fmt"
 	"net/http"
 	"strconv"
 	"strings"
 
 	"github.com/porter-dev/porter/internal/kubernetes"
-	"golang.org/x/crypto/bcrypt"
 
 	"gorm.io/gorm"
 
@@ -55,13 +55,15 @@ func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
 
 // HandleAuthCheck checks whether current session is authenticated.
 func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
-	session, err := app.store.Get(r, "cookie-name")
+	session, err := app.store.Get(r, app.cookieName)
+	cook, _ := r.Cookie("porter")
+	fmt.Println("cooki", cook)
 	if err != nil {
 		http.Error(w, err.Error(), http.StatusInternalServerError)
 	}
 
 	if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
-		app.logger.Info().Msgf("auth")
+		app.logger.Info().Msgf(strconv.FormatBool(auth))
 		w.WriteHeader(http.StatusOK)
 		w.Write([]byte("false"))
 		return
@@ -78,38 +80,40 @@ func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
 		app.handleErrorDataRead(err, ErrUserDataRead, w)
 	}
 
-	form := &forms.LoginUserForm{}
-	app.logger.Info().Msgf("Login")
-	// 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.Save(r, w)
+	// session.Values["user_id"] = storedUser.ID
+	if err := session.Save(r, w); err != nil {
+		// app.logger.Warn().Msgf()
+		fmt.Println(err)
+	}
 	w.WriteHeader(http.StatusOK)
 }
 

+ 2 - 2
server/router/router.go

@@ -20,11 +20,11 @@ func New(a *api.App, store *sessionstore.PGStore, cookieName string) *chi.Mux {
 		r.Use(middleware.ContentTypeJSON)
 
 		r.Use(cors.Handler(cors.Options{
-			AllowedOrigins:   []string{"*"},
+			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: false,
+			AllowCredentials: true,
 			MaxAge:           300, // Maximum value not ignored by any of major browsers
 		}))
 

Неке датотеке нису приказане због велике количине промена