-
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.
Merge pull request #12 from Delavalom/ft/add-grpc-gateway
Ft/add grpc gateway
- Loading branch information
Showing
28 changed files
with
2,375 additions
and
6 deletions.
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
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 |
---|---|---|
@@ -1,4 +1,6 @@ | ||
DB_SOURCE=postgresql://root:secret@localhost:5432/rdb?sslmode=disable | ||
HTTP_SERVER_ADDRESS=0.0.0.0:8080 | ||
GRPC_SERVER_ADDRESS=0.0.0.0:9090 | ||
TOKEN_SYMMETRIC_KEY=12345678901234567890123456789012 | ||
ACCESS_TOKEN_DURATION=15m | ||
REFRESH_TOKEN_DURATION=24h |
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,17 @@ | ||
package gapi | ||
|
||
import ( | ||
db "github.com/Delavalom/RBD/db/sqlc" | ||
"github.com/Delavalom/RBD/pb" | ||
"google.golang.org/protobuf/types/known/timestamppb" | ||
) | ||
|
||
func convertUser(user db.User) *pb.User { | ||
return &pb.User{ | ||
Username: user.Username, | ||
FullName: user.FullName, | ||
Email: user.Email, | ||
PasswordChangeAt: timestamppb.New(user.PasswordChangedAt), | ||
CreatedAt: timestamppb.New(user.CreatedAt), | ||
} | ||
} |
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,25 @@ | ||
package gapi | ||
|
||
import ( | ||
"google.golang.org/genproto/googleapis/rpc/errdetails" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
) | ||
|
||
func fieldViolation(field string, err error) *errdetails.BadRequest_FieldViolation { | ||
return &errdetails.BadRequest_FieldViolation{ | ||
Field: field, | ||
Description: err.Error(), | ||
} | ||
} | ||
|
||
func invalidArgumentError(violations []*errdetails.BadRequest_FieldViolation) error { | ||
badRequest := &errdetails.BadRequest{FieldViolations: violations} | ||
statusInvalid := status.New(codes.InvalidArgument, "invalid parameters") | ||
|
||
statusDetails, err := statusInvalid.WithDetails(badRequest) | ||
if err != nil { | ||
return statusInvalid.Err() | ||
} | ||
return statusDetails.Err() | ||
} |
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,41 @@ | ||
package gapi | ||
|
||
import ( | ||
"context" | ||
|
||
"google.golang.org/grpc/metadata" | ||
"google.golang.org/grpc/peer" | ||
) | ||
|
||
const ( | ||
grpcGatewayUserAgentHeader = "grpcgateway-user-agent" | ||
userAgentHeader = "user-agent" | ||
xForwardedForHeader = "x-forwarded-for" | ||
) | ||
|
||
type Metadata struct { | ||
UserAgent string | ||
ClientIP string | ||
} | ||
|
||
func (server *Server) extractMetaData(ctx context.Context) *Metadata { | ||
mtdt := &Metadata{} | ||
|
||
if data, ok := metadata.FromIncomingContext(ctx); ok { | ||
if userAgents := data.Get(grpcGatewayUserAgentHeader); len(userAgents) > 0 { | ||
mtdt.UserAgent = userAgents[0] | ||
} | ||
if userAgents := data.Get(userAgentHeader); len(userAgents) > 0 { | ||
mtdt.UserAgent = userAgents[0] | ||
} | ||
if clientIPs := data.Get(xForwardedForHeader); len(clientIPs) > 0 { | ||
mtdt.ClientIP = clientIPs[0] | ||
} | ||
} | ||
|
||
if peers, ok := peer.FromContext(ctx); ok { | ||
mtdt.ClientIP = peers.Addr.String() | ||
} | ||
|
||
return mtdt | ||
} |
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,61 @@ | ||
package gapi | ||
|
||
import ( | ||
"context" | ||
|
||
db "github.com/Delavalom/RBD/db/sqlc" | ||
"github.com/Delavalom/RBD/pb" | ||
"github.com/Delavalom/RBD/util" | ||
"google.golang.org/genproto/googleapis/rpc/errdetails" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
) | ||
|
||
func (server *Server) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) { | ||
violations := validateCreateUserRequest(req) | ||
if violations != nil { | ||
return nil, invalidArgumentError(violations) | ||
} | ||
hashedPassword, err := util.HashPassword(req.Password) | ||
if err != nil { | ||
return nil, status.Errorf(codes.Internal, "failed to hash password: %s", err) | ||
} | ||
|
||
arg := db.CreateUserParams{ | ||
Username: req.GetUsername(), | ||
HashedPassword: hashedPassword, | ||
FullName: req.GetFullName(), | ||
Email: req.GetEmail(), | ||
} | ||
|
||
user, err := server.store.CreateUser(ctx, arg) | ||
if err != nil { | ||
errCode := db.ErrorCode(err) | ||
if errCode == db.UniqueViolation { | ||
return nil, status.Errorf(codes.AlreadyExists, "username already exists: %s", err) | ||
} | ||
return nil, status.Errorf(codes.Internal, "failed to create user: %s", err) | ||
} | ||
|
||
rsp := &pb.CreateUserResponse{ | ||
User: convertUser(user), | ||
} | ||
return rsp, nil | ||
} | ||
|
||
func validateCreateUserRequest(req *pb.CreateUserRequest) (violations []*errdetails.BadRequest_FieldViolation) { | ||
validator := util.NewValidator() | ||
if err := validator.ValidateUsername(req.GetUsername()); err != nil { | ||
violations = append(violations, fieldViolation("username", err)) | ||
} | ||
if err := validator.ValidateFullName(req.GetFullName()); err != nil { | ||
violations = append(violations, fieldViolation("full_name", err)) | ||
} | ||
if err := validator.ValidateEmail(req.GetEmail()); err != nil { | ||
violations = append(violations, fieldViolation("email", err)) | ||
} | ||
if err := validator.ValidatePassword(req.GetPassword()); err != nil { | ||
violations = append(violations, fieldViolation("password", err)) | ||
} | ||
return | ||
} |
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,88 @@ | ||
package gapi | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
|
||
db "github.com/Delavalom/RBD/db/sqlc" | ||
"github.com/Delavalom/RBD/pb" | ||
"github.com/Delavalom/RBD/util" | ||
"google.golang.org/genproto/googleapis/rpc/errdetails" | ||
"google.golang.org/grpc/codes" | ||
"google.golang.org/grpc/status" | ||
"google.golang.org/protobuf/types/known/timestamppb" | ||
) | ||
|
||
func (server *Server) LoginUser(ctx context.Context, req *pb.LoginUserRequest) (*pb.LoginUserResponse, error) { | ||
violations := validateLoginUserRequest(req) | ||
if violations != nil { | ||
return nil, invalidArgumentError(violations) | ||
} | ||
user, err := server.store.GetUser(ctx, req.GetUsername()) | ||
if err != nil { | ||
if errors.Is(err, db.ErrRecordNotFound) { | ||
return nil, status.Errorf(codes.NotFound, "user not found: %s", err) | ||
} | ||
return nil, status.Errorf(codes.Internal, "failed to find user: %s", err) | ||
} | ||
|
||
err = util.CheckPassword(req.Password, user.HashedPassword) | ||
if err != nil { | ||
return nil, status.Errorf(codes.InvalidArgument, "incorrect password: %s", err) | ||
} | ||
|
||
accessToken, accessPayload, err := server.tokenMaker.CreateToken( | ||
user.Username, | ||
server.config.AccessTokenDuration, | ||
) | ||
if err != nil { | ||
return nil, status.Errorf(codes.Internal, "failed to create access token: %s", err) | ||
} | ||
|
||
refreshToken, refreshPayload, err := server.tokenMaker.CreateToken( | ||
user.Username, | ||
server.config.RefreshTokenDuration, | ||
) | ||
|
||
if err != nil { | ||
return nil, status.Errorf(codes.Internal, "failed to create refresh token: %s", err) | ||
} | ||
|
||
extractMetaData := server.extractMetaData(ctx) | ||
|
||
session, err := server.store.CreateSession(ctx, db.CreateSessionParams{ | ||
ID: refreshPayload.ID, | ||
Username: user.Username, | ||
RefreshToken: refreshToken, | ||
UserAgent: extractMetaData.UserAgent, | ||
ClientIp: extractMetaData.ClientIP, | ||
IsBlocked: false, | ||
ExpiresAt: refreshPayload.ExpiredAt, | ||
}) | ||
|
||
if err != nil { | ||
return nil, status.Errorf(codes.Internal, "failed to create session: %s", err) | ||
} | ||
|
||
rsp := &pb.LoginUserResponse{ | ||
User: convertUser(user), | ||
SessionId: session.ID.String(), | ||
AccessToken: accessToken, | ||
RefreshToken: refreshToken, | ||
AccessTokenExpiresAt: timestamppb.New(accessPayload.ExpiredAt), | ||
RefreshTokenExpiresAt: timestamppb.New(refreshPayload.ExpiredAt), | ||
} | ||
|
||
return rsp, nil | ||
} | ||
|
||
func validateLoginUserRequest(req *pb.LoginUserRequest) (violations []*errdetails.BadRequest_FieldViolation) { | ||
validator := util.NewValidator() | ||
if err := validator.ValidateUsername(req.GetUsername()); err != nil { | ||
violations = append(violations, fieldViolation("username", err)) | ||
} | ||
if err := validator.ValidatePassword(req.GetPassword()); err != nil { | ||
violations = append(violations, fieldViolation("password", err)) | ||
} | ||
return | ||
} |
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,33 @@ | ||
package gapi | ||
|
||
import ( | ||
"fmt" | ||
|
||
db "github.com/Delavalom/RBD/db/sqlc" | ||
"github.com/Delavalom/RBD/pb" | ||
"github.com/Delavalom/RBD/token" | ||
"github.com/Delavalom/RBD/util" | ||
) | ||
|
||
// Server serves gRPC requests for our banking service. | ||
type Server struct { | ||
pb.UnimplementedRBDServer | ||
config util.Config | ||
store db.Store | ||
tokenMaker token.Maker | ||
} | ||
|
||
// NewServer creates a new gRPC server. | ||
func NewServer(config util.Config, store db.Store) (*Server, error) { | ||
tokenMaker, err := token.NewPasetoMaker(config.TokenSymmetricKey) | ||
if err != nil { | ||
return nil, fmt.Errorf("cannot create token maker: %w", err) | ||
} | ||
server := &Server{ | ||
config: config, | ||
store: store, | ||
tokenMaker: tokenMaker, | ||
} | ||
|
||
return server, 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
Oops, something went wrong.