damccorm commented on code in PR #23782:
URL: https://github.com/apache/beam/pull/23782#discussion_r1005836897


##########
learning/tour-of-beam/backend/auth.go:
##########
@@ -0,0 +1,92 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package tob
+
+import (
+       "context"
+       "log"
+       "net/http"
+       "strings"
+
+       tob "beam.apache.org/learning/tour-of-beam/backend/internal"
+       "beam.apache.org/learning/tour-of-beam/backend/internal/storage"
+       firebase "firebase.google.com/go/v4"
+)
+
+// HandleFunc enriched with sdk and authenticated user uid.
+type HandlerFuncAuthWithSdk func(w http.ResponseWriter, r *http.Request, sdk 
tob.Sdk, uid string)
+
+const BEARER_SCHEMA = "Bearer "
+
+type Authorizer struct {
+       fbApp *firebase.App
+       repo  storage.Iface
+}
+
+func MakeAuthorizer(ctx context.Context, repo storage.Iface) *Authorizer {
+       // setup authorizer
+       // consumes:
+       // GOOGLE_PROJECT_ID
+       // GOOGLE_APPLICATION_CREDENTIALS
+       // OR
+       // FIREBASE_AUTH_EMULATOR_HOST
+       fbApp, err := firebase.NewApp(ctx, nil)
+       if err != nil {
+               log.Fatalf("error initializing firebase: %v", err)
+       }
+       return &Authorizer{fbApp, repo}
+}
+
+// middleware to parse authorization header, verify the ID token and extract 
uid.
+func (a *Authorizer) ParseAuthHeader(next HandlerFuncAuthWithSdk) 
HandlerFuncWithSdk {
+       return func(w http.ResponseWriter, r *http.Request, sdk tob.Sdk) {
+               ctx := r.Context()
+               header := r.Header.Get("authorization") // returns "" if no 
header
+               if !strings.HasPrefix(header, BEARER_SCHEMA) {
+                       log.Printf("Bad authorization header")
+                       finalizeErrResponse(w, http.StatusUnauthorized, 
UNAUTHORIZED, "bad auth header")

Review Comment:
   Maybe we could add some extra info here like: `bad auth header: expected 
Bearer schema type`



##########
learning/tour-of-beam/backend/auth.go:
##########
@@ -0,0 +1,92 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package tob
+
+import (
+       "context"
+       "log"
+       "net/http"
+       "strings"
+
+       tob "beam.apache.org/learning/tour-of-beam/backend/internal"
+       "beam.apache.org/learning/tour-of-beam/backend/internal/storage"
+       firebase "firebase.google.com/go/v4"
+)
+
+// HandleFunc enriched with sdk and authenticated user uid.
+type HandlerFuncAuthWithSdk func(w http.ResponseWriter, r *http.Request, sdk 
tob.Sdk, uid string)
+
+const BEARER_SCHEMA = "Bearer "
+
+type Authorizer struct {
+       fbApp *firebase.App
+       repo  storage.Iface
+}
+
+func MakeAuthorizer(ctx context.Context, repo storage.Iface) *Authorizer {
+       // setup authorizer
+       // consumes:
+       // GOOGLE_PROJECT_ID
+       // GOOGLE_APPLICATION_CREDENTIALS
+       // OR
+       // FIREBASE_AUTH_EMULATOR_HOST
+       fbApp, err := firebase.NewApp(ctx, nil)
+       if err != nil {
+               log.Fatalf("error initializing firebase: %v", err)
+       }
+       return &Authorizer{fbApp, repo}
+}
+
+// middleware to parse authorization header, verify the ID token and extract 
uid.
+func (a *Authorizer) ParseAuthHeader(next HandlerFuncAuthWithSdk) 
HandlerFuncWithSdk {
+       return func(w http.ResponseWriter, r *http.Request, sdk tob.Sdk) {
+               ctx := r.Context()
+               header := r.Header.Get("authorization") // returns "" if no 
header
+               if !strings.HasPrefix(header, BEARER_SCHEMA) {
+                       log.Printf("Bad authorization header")
+                       finalizeErrResponse(w, http.StatusUnauthorized, 
UNAUTHORIZED, "bad auth header")
+                       return
+               }
+
+               client, err := a.fbApp.Auth(ctx)
+               if err != nil {
+                       log.Println("Failed to get auth client:", err)

Review Comment:
   Where do these logs go? Will they be accessible if we need to debug/do we 
have instructions on how to access them? If not, we should add instructions 
(doesn't need to be part of this PR)



##########
learning/tour-of-beam/backend/auth.go:
##########
@@ -0,0 +1,92 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package tob
+
+import (
+       "context"
+       "log"
+       "net/http"
+       "strings"
+
+       tob "beam.apache.org/learning/tour-of-beam/backend/internal"
+       "beam.apache.org/learning/tour-of-beam/backend/internal/storage"
+       firebase "firebase.google.com/go/v4"
+)
+
+// HandleFunc enriched with sdk and authenticated user uid.
+type HandlerFuncAuthWithSdk func(w http.ResponseWriter, r *http.Request, sdk 
tob.Sdk, uid string)
+
+const BEARER_SCHEMA = "Bearer "
+
+type Authorizer struct {
+       fbApp *firebase.App
+       repo  storage.Iface
+}
+
+func MakeAuthorizer(ctx context.Context, repo storage.Iface) *Authorizer {
+       // setup authorizer
+       // consumes:
+       // GOOGLE_PROJECT_ID
+       // GOOGLE_APPLICATION_CREDENTIALS
+       // OR
+       // FIREBASE_AUTH_EMULATOR_HOST
+       fbApp, err := firebase.NewApp(ctx, nil)
+       if err != nil {
+               log.Fatalf("error initializing firebase: %v", err)
+       }
+       return &Authorizer{fbApp, repo}
+}
+
+// middleware to parse authorization header, verify the ID token and extract 
uid.
+func (a *Authorizer) ParseAuthHeader(next HandlerFuncAuthWithSdk) 
HandlerFuncWithSdk {
+       return func(w http.ResponseWriter, r *http.Request, sdk tob.Sdk) {
+               ctx := r.Context()
+               header := r.Header.Get("authorization") // returns "" if no 
header
+               if !strings.HasPrefix(header, BEARER_SCHEMA) {
+                       log.Printf("Bad authorization header")
+                       finalizeErrResponse(w, http.StatusUnauthorized, 
UNAUTHORIZED, "bad auth header")
+                       return
+               }
+
+               client, err := a.fbApp.Auth(ctx)
+               if err != nil {
+                       log.Println("Failed to get auth client:", err)
+                       finalizeErrResponse(w, http.StatusInternalServerError, 
INTERNAL_ERROR, "auth client failed")
+                       return
+               }
+
+               tokenEncoded := header[len(BEARER_SCHEMA):]
+               token, err := client.VerifyIDTokenAndCheckRevoked(ctx, 
tokenEncoded)
+               if err != nil {
+                       log.Println("Failed to verify token:", err)
+                       finalizeErrResponse(w, http.StatusUnauthorized, 
UNAUTHORIZED, "failed to verify token")

Review Comment:
   Can we return a different error if the token has been revoked (e.g. see 
example here - https://firebase.google.com/docs/auth/admin/manage-sessions#go_1)



##########
learning/tour-of-beam/backend/internal/service/content.go:
##########
@@ -23,30 +23,48 @@ import (
        "beam.apache.org/learning/tour-of-beam/backend/internal/storage"
 )
 
-var ErrNoUnit = errors.New("unit not found")
-
 type IContent interface {
-       GetContentTree(ctx context.Context, sdk tob.Sdk, userId *string) 
(tob.ContentTree, error)
-       GetUnitContent(ctx context.Context, sdk tob.Sdk, unitId string, userId 
*string) (tob.Unit, error)
+       GetContentTree(ctx context.Context, sdk tob.Sdk) (tob.ContentTree, 
error)
+       GetUnitContent(ctx context.Context, sdk tob.Sdk, unitId string) 
(tob.Unit, error)
+       GetUserProgress(ctx context.Context, sdk tob.Sdk, userId string) 
(tob.SdkProgress, error)
+       SetUnitComplete(ctx context.Context, sdk tob.Sdk, unitId, uid string) 
error
 }
 
 type Svc struct {
        Repo storage.Iface
 }
 
-func (s *Svc) GetContentTree(ctx context.Context, sdk tob.Sdk, userId *string) 
(ct tob.ContentTree, err error) {
-       // TODO enrich tree with user-specific state (isCompleted)
+func (s *Svc) GetContentTree(ctx context.Context, sdk tob.Sdk) (ct 
tob.ContentTree, err error) {
        return s.Repo.GetContentTree(ctx, sdk)
 }
 
-func (s *Svc) GetUnitContent(ctx context.Context, sdk tob.Sdk, unitId string, 
userId *string) (tob.Unit, error) {
-       // TODO enrich unit with user-specific state: isCompleted, userSnippetId
+func (s *Svc) GetUnitContent(ctx context.Context, sdk tob.Sdk, unitId string) 
(tob.Unit, error) {
        unit, err := s.Repo.GetUnitContent(ctx, sdk, unitId)
        if err != nil {
                return tob.Unit{}, err
        }
        if unit == nil {
-               return tob.Unit{}, ErrNoUnit
+               return tob.Unit{}, tob.ErrNoUnit
        }
        return *unit, nil
 }
+
+func (s *Svc) GetUserProgress(ctx context.Context, sdk tob.Sdk, userId string) 
(tob.SdkProgress, error) {
+       progress, err := s.Repo.GetUserProgress(ctx, sdk, userId)
+       if errors.Is(err, tob.ErrNoUser) {
+               // make an empty list a default response
+               return tob.SdkProgress{Units: make([]tob.UnitProgress, 0)}, nil
+       }
+       if err != nil {
+               return tob.SdkProgress{}, err
+       }
+       if progress == nil {
+               panic("progress is nil, no err")

Review Comment:
   Do we really want to panic here, or should we just return this string as an 
error `tob.SdkProgress{}, <error>` (and log the error)? Panicing will bring 
everything down here when this could be a bug for this specific user, right?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to