Selaa lähdekoodia

user id stored in context after login. closes #38

sunguroku 5 vuotta sitten
vanhempi
sitoutus
c64a250452

+ 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();
       });
     }

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

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

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

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

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

@@ -51,7 +51,6 @@ class ContextProvider extends Component {
   };
 
   componentDidMount() {
-    this.setState({ userId: 1 });
   }
 
   render() {

+ 19 - 6
server/api/user_handler.go

@@ -53,7 +53,7 @@ func (app *App) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
 	}
 }
 
-// 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 +61,18 @@ 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)
+
+	resUser := &models.UserExternal{
+		ID: userID,
+	}
+
+	if err := json.NewEncoder(w).Encode(resUser); 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 +117,15 @@ func (app *App) HandleLoginUser(w http.ResponseWriter, r *http.Request) {
 		app.logger.Warn().Err(err)
 	}
 
+	resUser := &models.UserExternal{
+		ID: storedUser.ID,
+	}
+
+	if err := json.NewEncoder(w).Encode(resUser); err != nil {
+		app.handleErrorFormDecoding(err, ErrUserDecode, w)
+		return
+	}
+
 	w.WriteHeader(http.StatusOK)
 }
 

+ 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