Skip to content

Commit

Permalink
improv: removed resource signature from sub functions
Browse files Browse the repository at this point in the history
rely con context DI instead
  • Loading branch information
SpeedReach committed Jun 5, 2024
1 parent 82dee9c commit 8d22aa8
Show file tree
Hide file tree
Showing 18 changed files with 301 additions and 257 deletions.
46 changes: 23 additions & 23 deletions internal/infra/resources.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
package infra

import (
"database/sql"
"go.uber.org/zap"
)

type Resources struct {
DBConn *sql.DB
Logger *zap.Logger
}

func SetupResources(config Config) Resources {
dbConn := SetupConnection(config.PostgresURI)
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
return Resources{
DBConn: dbConn,
Logger: logger,
}
}
package infra

import (
"database/sql"
"go.uber.org/zap"
)

type Resources struct {
DBConn *sql.DB
Logger *zap.Logger
}

func SetupResources(config Config) Resources {
dbConn := SetupConnection(config.PostgresURI)
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
return Resources{
DBConn: dbConn,
Logger: logger,
}
}
13 changes: 5 additions & 8 deletions internal/middlewares/context_keys.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package middlewares

type UserIdContextKey struct{}
type ConfigContextKey struct{}
type StorageContextKey struct{}
type CacheContextKey struct{}
type RequestIdContextKey struct{}
type LoggerContextKey struct{}
package middlewares

type UserIdContextKey struct{}
type DatabaseContextKey struct{}
type LoggerContextKey struct{}
7 changes: 4 additions & 3 deletions internal/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc"
"monify/internal/infra"
"monify/internal/middlewares"
Expand Down Expand Up @@ -53,10 +54,10 @@ func setupInterceptor(resources infra.Resources, config ServerConfig) grpc.Serve
if userId != uuid.Nil {
ctx = context.WithValue(ctx, middlewares.UserIdContextKey{}, userId)
}
ctx = context.WithValue(ctx, middlewares.StorageContextKey{}, resources.DBConn)
ctx = context.WithValue(ctx, middlewares.LoggerContextKey{}, resources.Logger)
requestId := uuid.New()
ctx = context.WithValue(ctx, middlewares.DatabaseContextKey{}, resources.DBConn)
ctx = context.WithValue(ctx, middlewares.LoggerContextKey{}, resources.Logger.With(zap.String("request_id", requestId.String())))
m, err := handler(ctx, req)

return m, err
}
return grpc.UnaryInterceptor(interceptor)
Expand Down
12 changes: 6 additions & 6 deletions internal/services/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ import (
"time"
)

func matchEmailUser(ctx context.Context, email string, password string, db *sql.DB) (uuid.UUID, error) {
func matchEmailUser(ctx context.Context, email string, password string) (uuid.UUID, error) {
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
query, err := db.QueryContext(ctx, `
SELECT user_id, password
FROM email_login
Expand Down Expand Up @@ -45,7 +46,8 @@ func matchEmailUser(ctx context.Context, email string, password string, db *sql.
return userId, nil
}

func generateAndInsertRefreshToken(ctx context.Context, userId uuid.UUID, db *sql.DB) (string, error) {
func generateAndInsertRefreshToken(ctx context.Context, userId uuid.UUID) (string, error) {
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
var refreshToken string = uuid.New().String()
_, err := db.ExecContext(ctx, `
UPDATE user_identity SET refresh_token=$1 WHERE user_id = $2
Expand All @@ -65,11 +67,9 @@ func (s Service) EmailLogin(ctx context.Context, req *monify.EmailLoginRequest)
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)

userId, err := matchEmailUser(ctx, req.Email, req.Password, db)
userId, err := matchEmailUser(ctx, req.Email, req.Password)
if err != nil {
return nil, err
}
Expand All @@ -79,7 +79,7 @@ func (s Service) EmailLogin(ctx context.Context, req *monify.EmailLoginRequest)
}

//generate refresh token and insert into database
refreshToken, err := generateAndInsertRefreshToken(ctx, userId, db)
refreshToken, err := generateAndInsertRefreshToken(ctx, userId)
if err != nil {
logger.Error("", zap.Error(err))
return nil, status.Errorf(codes.Internal, "internal err.")
Expand Down
118 changes: 59 additions & 59 deletions internal/services/auth/refresh_token.go
Original file line number Diff line number Diff line change
@@ -1,59 +1,59 @@
package auth

import (
"context"
"database/sql"
"monify/internal/middlewares"
monify "monify/protobuf/gen/go"

"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func get_userID(ctx context.Context, db *sql.DB, refreshToken string) (uuid.UUID, error) {

query, err := db.QueryContext(ctx, `
SELECT user_id
FROM user_identity
WHERE refresh_token= $1`, refreshToken)
defer query.Close()
if err != nil {
return uuid.Nil, err
}
if !query.Next() {
return uuid.Nil, nil
}
var userId uuid.UUID
err = query.Scan(&userId)
if err != nil {
return uuid.Nil, err
}
return userId, nil

}

func (s Service) RefreshToken(ctx context.Context, req *monify.RefreshTokenRequest) (*monify.RefreshTokenResponse, error) {
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
userId, err := get_userID(ctx, db, req.RefreshToken)

//它給我refresh token,我要給refresh token + access token
refreshToken, err := generateAndInsertRefreshToken(ctx, userId, db)
if err != nil {
logger.Error("failed to get refresh token", zap.Error(err))
return nil, status.Error(codes.Internal, "internal err.")
}
accessToken, err := GenerateAccessToken(ctx, userId, s.Secret)

if err != nil {
logger.Error("failed to get access token", zap.Error(err))
return nil, status.Error(codes.Internal, "internal err.")

}
return &monify.RefreshTokenResponse{
AccessToken: accessToken,
RefreshToken: refreshToken,
}, nil
}
package auth

import (
"context"
"database/sql"
"monify/internal/middlewares"
monify "monify/protobuf/gen/go"

"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

func get_userID(ctx context.Context, refreshToken string) (uuid.UUID, error) {
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
query, err := db.QueryContext(ctx, `
SELECT user_id
FROM user_identity
WHERE refresh_token= $1`, refreshToken)
defer query.Close()
if err != nil {
return uuid.Nil, err
}
if !query.Next() {
return uuid.Nil, nil
}
var userId uuid.UUID
err = query.Scan(&userId)
if err != nil {
return uuid.Nil, err
}
return userId, nil

}

func (s Service) RefreshToken(ctx context.Context, req *monify.RefreshTokenRequest) (*monify.RefreshTokenResponse, error) {

logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
userId, err := get_userID(ctx, req.RefreshToken)

//它給我refresh token,我要給refresh token + access token
refreshToken, err := generateAndInsertRefreshToken(ctx, userId)
if err != nil {
logger.Error("failed to get refresh token", zap.Error(err))
return nil, status.Error(codes.Internal, "internal err.")
}
accessToken, err := GenerateAccessToken(ctx, userId, s.Secret)

if err != nil {
logger.Error("failed to get access token", zap.Error(err))
return nil, status.Error(codes.Internal, "internal err.")

}
return &monify.RefreshTokenResponse{
AccessToken: accessToken,
RefreshToken: refreshToken,
}, nil
}
11 changes: 6 additions & 5 deletions internal/services/auth/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import (
monify "monify/protobuf/gen/go"
)

func emailExists(ctx context.Context, email string, db *sql.DB) (bool, error) {
func emailExists(ctx context.Context, email string) (bool, error) {
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
rows, err := db.QueryContext(ctx, `
SELECT user_id
FROM email_login
Expand All @@ -25,7 +26,8 @@ func emailExists(ctx context.Context, email string, db *sql.DB) (bool, error) {
return rows.Next(), nil
}

func CreateUser(ctx context.Context, db *sql.DB, email string, password string) (uuid.UUID, error) {
func CreateUser(ctx context.Context, email string, password string) (uuid.UUID, error) {
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
if email == "" || password == "" {
return uuid.Nil, status.Error(codes.InvalidArgument, "Email and password is required.")
}
Expand All @@ -50,9 +52,8 @@ func CreateUser(ctx context.Context, db *sql.DB, email string, password string)
}

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)
exists, err := emailExists(ctx, req.Email)
if err != nil {
logger.Error("failed to query email", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
Expand All @@ -61,7 +62,7 @@ func (s Service) EmailRegister(ctx context.Context, req *monify.EmailRegisterReq
return nil, status.Error(codes.AlreadyExists, "Email already exists.")
}

userId, err := CreateUser(ctx, db, req.Email, req.Password)
userId, err := CreateUser(ctx, req.Email, req.Password)
if err != nil {
logger.Error("failed to create user", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal err.")
Expand Down
10 changes: 5 additions & 5 deletions internal/services/group/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import (
"google.golang.org/grpc/status"
)

func createGroup(ctx context.Context, db *sql.Tx, name string) (uuid.UUID, error) {
func createGroup(ctx context.Context, tx *sql.Tx, name string) (uuid.UUID, error) {
groupId := uuid.New()
_, err := db.Exec(`
_, err := tx.ExecContext(ctx, `
INSERT INTO "group" (group_id, name) VALUES ($1, $2)
`, groupId, name)
return groupId, err
Expand All @@ -27,7 +27,7 @@ func (s Service) CreateGroup(ctx context.Context, req *monify.CreateGroupRequest
return nil, status.Error(codes.Unauthenticated, "Unauthorized.")
}

db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadUncommitted})
if err != nil {
logger.Error("", zap.Error(err))
Expand Down Expand Up @@ -58,9 +58,9 @@ func (s Service) CreateGroup(ctx context.Context, req *monify.CreateGroupRequest
}, nil
}

func createGroupLeader(ctx context.Context, db *sql.Tx, groupId uuid.UUID, userId uuid.UUID) (uuid.UUID, error) {
func createGroupLeader(ctx context.Context, tx *sql.Tx, groupId uuid.UUID, userId uuid.UUID) (uuid.UUID, error) {
groupMemberId := uuid.New()
_, err := db.Exec(`
_, err := tx.ExecContext(ctx, `
INSERT INTO group_member (group_member_id,group_id, user_id) VALUES ($1,$2,$3)
`, groupMemberId, groupId, userId)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/services/group/generate_invite_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const (

func (s Service) GenerateInviteCode(ctx context.Context, req *monify.GenerateInviteCodeRequest) (*monify.GenerateInviteCodeResponse, error) {
userId, ok := ctx.Value(middlewares.UserIdContextKey{}).(uuid.UUID)
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
if !ok {
return nil, status.Error(codes.Unauthenticated, "Unauthorized.")
Expand All @@ -33,7 +33,7 @@ func (s Service) GenerateInviteCode(ctx context.Context, req *monify.GenerateInv
if err != nil {
return nil, status.Error(codes.InvalidArgument, "Invalid group ID")
}
hasPerm, err := CheckPermission(ctx, db, groupId, userId)
hasPerm, err := CheckPermission(ctx, groupId, userId)
if err != nil {
logger.Error("Failed to check permission", zap.Error(err))
return nil, status.Error(codes.Internal, "Internal")
Expand Down
4 changes: 2 additions & 2 deletions internal/services/group/get_members.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ func (s Service) GetGroupMembers(ctx context.Context, req *monify.GetGroupMember
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid group id")
}
db := ctx.Value(middlewares.StorageContextKey{}).(*sql.DB)
db := ctx.Value(middlewares.DatabaseContextKey{}).(*sql.DB)
logger := ctx.Value(middlewares.LoggerContextKey{}).(*zap.Logger)
permission, err := CheckPermission(ctx, db, groupId, userId)
permission, err := CheckPermission(ctx, groupId, userId)
if err != nil {
logger.Error("failed to check permission", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to check permission")
Expand Down
Loading

0 comments on commit 8d22aa8

Please sign in to comment.