Просмотр исходного кода

Merge branch 'frontend-integration' of https://github.com/porter-dev/porter into frontend-integration

jusrhee 5 лет назад
Родитель
Сommit
84b287a239

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

@@ -28,7 +28,7 @@ export default class Login extends Component<PropsType, StateType> {
   handleLogin = (): void => {
     let { email, password } = this.state;
     let { authenticate } = this.props;
-    let { setCurrentError } = this.context;
+    let { setCurrentError, setUserId } = this.context;
 
     // Check for valid input
     if (!emailRegex.test(email)) {
@@ -40,6 +40,7 @@ export default class Login extends Component<PropsType, StateType> {
         password: password
       }, {}, (err: any, res: any) => {
         // TODO: case and set credential error
+        setUserId(res?.data?.id)
         err ? setCurrentError(err.response.data.errors[0]) : authenticate();
       });
     }

+ 3 - 0
dashboard/src/main/Main.tsx

@@ -29,8 +29,11 @@ export default class Main extends Component<PropsType, StateType> {
   }
 
   componentDidMount() {
+    let { setUserId } = this.context;
+    console.log('how')
     api.checkAuth('', {}, {}, (err: any, res: any) => {
       if (res.data) {
+        setUserId(res.data.id)
         this.setState({ isLoggedIn: true, initialized: true})
       } else {
         this.setState({ isLoggedIn: false })

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

@@ -30,7 +30,7 @@ export default class Register extends Component<PropsType, StateType> {
   handleRegister = (): void => {
     let { email, password, confirmPassword } = this.state;
     let { authenticate } = this.props;
-    let { setCurrentError } = this.context;
+    let { setCurrentError, setUserId } = this.context;
 
     if (!emailRegex.test(email)) {
       this.setState({ emailError: true });
@@ -48,6 +48,7 @@ export default class Register extends Component<PropsType, StateType> {
         email: email,
         password: password
       }, {}, (err: any, res: any) => {
+        setUserId(res?.data?.id)
         err ? setCurrentError(err.response.data.errors[0]) : authenticate();
       });
     } 

+ 1 - 0
dashboard/src/main/home/Home.tsx

@@ -33,6 +33,7 @@ export default class Home extends Component<PropsType, StateType> {
   }
 
   render() {
+    console.log(this.context)
     return (
       <StyledHome>
         <ReactModal

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

@@ -49,11 +49,7 @@ class ContextProvider extends Component {
       this.setState({ devOpsMode });
     }
   };
-
-  componentDidMount() {
-    this.setState({ userId: 1 });
-  }
-
+  
   render() {
     return (
       <Provider value={this.state}>{this.props.children}</Provider>

+ 28 - 6
server/api/user_handler.go

@@ -49,11 +49,17 @@ func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
 		session.Values["authenticated"] = true
 		session.Values["user_id"] = user.ID
 		session.Save(r, w)
+
+		if err := app.sendUserID(w, user.ID); err != nil {
+			app.handleErrorFormDecoding(err, ErrUserDecode, w)
+			return
+		}
+
 		w.WriteHeader(http.StatusCreated)
 	}
 }
 
-// HandleAuthCheck checks whether current session is authenticated.
+// HandleAuthCheck checks whether current session is authenticated and returns user ID if so.
 func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
 	session, err := app.store.Get(r, app.cookieName)
 
@@ -61,14 +67,14 @@ func (app *App) HandleAuthCheck(w http.ResponseWriter, r *http.Request) {
 		http.Error(w, err.Error(), http.StatusInternalServerError)
 	}
 
-	if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
-		app.logger.Info().Msgf(strconv.FormatBool(auth))
-		w.WriteHeader(http.StatusOK)
-		w.Write([]byte("false"))
+	userID, _ := session.Values["user_id"].(uint)
+
+	if err := app.sendUserID(w, userID); err != nil {
+		app.handleErrorFormDecoding(err, ErrUserDecode, w)
 		return
 	}
+
 	w.WriteHeader(http.StatusOK)
-	w.Write([]byte("true"))
 }
 
 // HandleLoginUser checks the request header for cookie and validates the user.
@@ -113,6 +119,11 @@ func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
 		app.logger.Warn().Err(err)
 	}
 
+	if err := app.sendUserID(w, storedUser.ID); err != nil {
+		app.handleErrorFormDecoding(err, ErrUserDecode, w)
+		return
+	}
+
 	w.WriteHeader(http.StatusOK)
 }
 
@@ -327,3 +338,14 @@ func doesUserExist(repo *repository.Repository, user *models.User) *HTTPError {
 
 	return nil
 }
+
+func (app *App) sendUserID(w http.ResponseWriter, userID uint) error {
+	resUser := &models.UserExternal{
+		ID: userID,
+	}
+
+	if err := json.NewEncoder(w).Encode(resUser); err != nil {
+		return err
+	}
+	return nil
+}

+ 1 - 1
server/router/router.go

@@ -24,7 +24,7 @@ func New(a *api.App, store sessions.Store, cookieName string) *chi.Mux {
 		r.Method("PUT", "/users/{id}", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleUpdateUser, l), mw.URLParam))
 		r.Method("DELETE", "/users/{id}", auth.DoesUserIDMatch(requestlog.NewHandler(a.HandleDeleteUser, l), mw.URLParam))
 		r.Method("POST", "/login", requestlog.NewHandler(a.HandleLoginUser, l))
-		r.Method("GET", "/auth/check", requestlog.NewHandler(a.HandleAuthCheck, l))
+		r.Method("GET", "/auth/check", auth.BasicAuthenticate(requestlog.NewHandler(a.HandleAuthCheck, l)))
 		r.Method("POST", "/logout", auth.BasicAuthenticate(requestlog.NewHandler(a.HandleLogoutUser, l)))
 
 		// /api/charts routes