forked from techschool/simplebank
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add authorization to gRPC update user API (techschool#60)
Co-authored-by: phamlequang <phamlequang@gmail.com>
- Loading branch information
1 parent
c335fd5
commit 68ef8aa
Showing
3 changed files
with
58 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package gapi | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/techschool/simplebank/token" | ||
"google.golang.org/grpc/metadata" | ||
) | ||
|
||
const ( | ||
authorizationHeader = "authorization" | ||
authorizationBearer = "bearer" | ||
) | ||
|
||
func (server *Server) authorizeUser(ctx context.Context) (*token.Payload, error) { | ||
md, ok := metadata.FromIncomingContext(ctx) | ||
if !ok { | ||
return nil, fmt.Errorf("missing metadata") | ||
} | ||
|
||
values := md.Get(authorizationHeader) | ||
if len(values) == 0 { | ||
return nil, fmt.Errorf("missing authorization header") | ||
} | ||
|
||
authHeader := values[0] | ||
fields := strings.Fields(authHeader) | ||
if len(fields) < 2 { | ||
return nil, fmt.Errorf("invalid authorization header format") | ||
} | ||
|
||
authType := strings.ToLower(fields[0]) | ||
if authType != authorizationBearer { | ||
return nil, fmt.Errorf("unsupported authorization type: %s", authType) | ||
} | ||
|
||
accessToken := fields[1] | ||
payload, err := server.tokenMaker.VerifyToken(accessToken) | ||
if err != nil { | ||
return nil, fmt.Errorf("invalid access token: %s", err) | ||
} | ||
|
||
return payload, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters