Skip to content

Commit

Permalink
update: add empty checks for some routes
Browse files Browse the repository at this point in the history
  • Loading branch information
SpeedReach committed Jun 1, 2024
1 parent 7548146 commit f205f4f
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 73 deletions.
2 changes: 1 addition & 1 deletion cmd/restful_proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func allowCORS(h http.Handler) http.Handler {
func preflightHandler(w http.ResponseWriter, r *http.Request) {
headers := []string{"Content-Type", "Accept", "Authorization"}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
grpclog.Infof("Preflight request for %s", r.URL.Path)
}
4 changes: 4 additions & 0 deletions internal/services/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ func GenerateAccessToken(ctx context.Context, userId uuid.UUID, secret string) (
}

func (s Service) EmailLogin(ctx context.Context, req *monify.EmailLoginRequest) (*monify.EmailLoginResponse, error) {
if req.Email == "" || req.Password == "" {
return nil, status.Error(codes.InvalidArgument, "Email and password is required.")
}

logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)

Expand Down
137 changes: 70 additions & 67 deletions internal/services/auth/register.go
Original file line number Diff line number Diff line change
@@ -1,67 +1,70 @@
package auth

import (
"context"
"database/sql"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"monify/internal/middlewares"
monify "monify/protobuf/gen/go"
)

func emailExists(ctx context.Context, email string, db *sql.DB) (bool, error) {
rows, err := db.QueryContext(ctx, `
SELECT user_id
FROM email_login
WHERE email = $1
`, email)
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}

func CreateUser(ctx context.Context, db *sql.DB, email string, password string) (uuid.UUID, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return [16]byte{}, err
}

userId := uuid.New()
_, err = db.ExecContext(ctx, `
INSERT INTO user_identity (user_id) VALUES ($1)
`, userId)
if err != nil {
return uuid.Nil, err
}

_, err = db.ExecContext(ctx, `INSERT INTO email_login(email, user_id, password) VALUES ($1, $2, $3)`, email, userId, string(hashedPassword))
if err != nil {
return uuid.Nil, err
}
return userId, nil
}

func (s Service) EmailRegister(ctx context.Context, req *monify.EmailRegisterRequest) (*monify.EmailRegisterResponse, error) {
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
exists, err := emailExists(ctx, req.Email, db)
if err != nil {
logger.Error("failed to query email", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
}
if exists {
return nil, status.Error(codes.AlreadyExists, "Email already exists.")
}

userId, err := CreateUser(ctx, db, req.Email, req.Password)
if err != nil {
logger.Error("failed to create user", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
}
return &monify.EmailRegisterResponse{UserId: userId.String()}, nil
}
package auth

import (
"context"
"database/sql"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"monify/internal/middlewares"
monify "monify/protobuf/gen/go"
)

func emailExists(ctx context.Context, email string, db *sql.DB) (bool, error) {
rows, err := db.QueryContext(ctx, `
SELECT user_id
FROM email_login
WHERE email = $1
`, email)
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}

func CreateUser(ctx context.Context, db *sql.DB, email string, password string) (uuid.UUID, error) {
if email == "" || password == "" {
return uuid.Nil, status.Error(codes.InvalidArgument, "Email and password is required.")
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return [16]byte{}, err
}

userId := uuid.New()
_, err = db.ExecContext(ctx, `
INSERT INTO user_identity (user_id) VALUES ($1)
`, userId)
if err != nil {
return uuid.Nil, err
}

_, err = db.ExecContext(ctx, `INSERT INTO email_login(email, user_id, password) VALUES ($1, $2, $3)`, email, userId, string(hashedPassword))
if err != nil {
return uuid.Nil, err
}
return userId, nil
}

func (s Service) EmailRegister(ctx context.Context, req *monify.EmailRegisterRequest) (*monify.EmailRegisterResponse, error) {
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
exists, err := emailExists(ctx, req.Email, db)
if err != nil {
logger.Error("failed to query email", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
}
if exists {
return nil, status.Error(codes.AlreadyExists, "Email already exists.")
}

userId, err := CreateUser(ctx, db, req.Email, req.Password)
if err != nil {
logger.Error("failed to create user", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
}
return &monify.EmailRegisterResponse{UserId: userId.String()}, nil
}
3 changes: 3 additions & 0 deletions internal/services/group_bill/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (

// CreateGroupBill Handler
func (s Service) CreateGroupBill(ctx context.Context, req *monify.CreateGroupBillRequest) (*monify.CreateGroupBillResponse, error) {
if req.Title == "" {
return nil, status.Error(codes.InvalidArgument, "Title is required")
}
//Parse ids
userId, ok := ctx.Value(middlewares.UserIdContextKey{}).(uuid.UUID)
if !ok {
Expand Down
17 changes: 12 additions & 5 deletions internal/services/group_bill/delete_bill.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,28 @@ import (
)

func (s Service) DeleteGroupBill(ctx context.Context, req *monify.DeleteGroupBillRequest) (*monify.GroupGroupBillEmpty, error) {
if req.BillId == "" {
return nil, status.Error(codes.InvalidArgument, "Bill id is required")
}
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
userId, ok := ctx.Value(middlewares.UserIdContextKey{}).(uuid.UUID)
if !ok {
return nil, status.Error(codes.Unauthenticated, "Unauthorized.")
}
billId, err := uuid.Parse(req.BillId)
if err != nil {
return nil, status.Error(codes.InvalidArgument, "Invalid bill id")
}
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)

//Check permission
rows := db.QueryRowContext(ctx, `
SELECT COUNT(*) FROM group_bill
LEFT JOIN group_member gm ON group_bill.group_id = gm.group_id
WHERE group_bill.bill_id = $1 AND gm.user_id = $2
`, req.BillId, userId)
`, billId, userId)
var count int
err := rows.Scan(&count)
err = rows.Scan(&count)
if err != nil {
logger.Error("Failed to check permission", zap.Error(err))
}
Expand All @@ -45,23 +52,23 @@ func (s Service) DeleteGroupBill(ctx context.Context, req *monify.DeleteGroupBil

//Start delete
_, err = tx.ExecContext(ctx,
`DELETE FROM group_bill WHERE bill_id = $1`, req.BillId,
`DELETE FROM group_bill WHERE bill_id = $1`, billId,
)
if err != nil {
logger.Error("Failed to delete group from group_bill", zap.Error(err))
return nil, err
}

_, err = tx.ExecContext(ctx,
`DELETE FROM group_split_bill WHERE bill_id = $1`, req.BillId,
`DELETE FROM group_split_bill WHERE bill_id = $1`, billId,
)
if err != nil {
logger.Error("Failed to delete group from group_split_bill", zap.Error(err))
return nil, err
}

_, err = tx.ExecContext(ctx,
`DELETE FROM group_prepaid_bill WHERE bill_id = $1`, req.BillId,
`DELETE FROM group_prepaid_bill WHERE bill_id = $1`, billId,
)
if err != nil {
logger.Error("Failed to delete group from group_prepaid_bill", zap.Error(err))
Expand Down

0 comments on commit f205f4f

Please sign in to comment.