Documentation
¶
Overview ¶
Package utils provides utility functions and components for the users microservice.
Index ¶
- func CheckPassword(hashedPwd string, plainPwd string) error
- func ExtractSuccessData[T any](resp models.APIResponse) (T, error)
- func GenerateJWT(userID, role, email, userName, secretString string) (string, error)
- func GetRouter() *gin.Engine
- func HandleError(c *gin.Context, statusCode int, errorMessage string, path string)
- func HandleInternalServerError(c *gin.Context)
- func HandleSuccess(c *gin.Context, statusCode int, message string, data interface{})
- func HashPassword(password string) (string, error)
- func ParseJWT(tokenString string, jwtSecret string) (map[string]interface{}, error)
- func ReadEnvironmentVariables() (string, string, string, string, string, string)
- type MailSender
- type PinGenerator
- type RandomPinGenerator
- type Sender
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckPassword ¶
func ExtractSuccessData ¶ added in v0.1.1
func ExtractSuccessData[T any](resp models.APIResponse) (T, error)
func GenerateJWT ¶
GenerateJWT generates a JSON Web Token (JWT) for a user with the specified user ID and role. The token is signed using the provided secret string and is set to expire in 1 hour.
Parameters:
- userID: A string representing the unique identifier of the user.
- role: A string representing the role of the user.
- secretString: A string used as the secret key to sign the token.
Returns:
- A string containing the signed JWT.
- An error if there is an issue during the token generation or signing process.
func GetRouter ¶
getRouter initializes the Gin router with recovery middleware and debug logging. It returns a pointer to the router.
func HandleError ¶
HandleError is a utility function that handles HTTP errors by sending a JSON response with the appropriate status code and error message. It uses the Gin framework's context to format and send the response.
Parameters:
- c: *gin.Context - The Gin context used to send the JSON response.
- statusCode: int - The HTTP status code to be sent in the response.
- errorMessage: string - A descriptive error message to include in the response.
- path: string - The request path where the error occurred.
Behavior:
- Depending on the provided statusCode, the function sends a JSON response with a corresponding error model (e.g., BadRequest, Unauthorized, etc.).
- If the statusCode does not match any predefined cases, it defaults to sending an InternalServerError response.
func HandleInternalServerError ¶
HandleInternalServerError is a utility function that handles internal server errors by sending a JSON response with a 500 status code and a generic error message. It uses the Gin framework's context to format and send the response.
Parameters:
- c: *gin.Context - The Gin context used to send the JSON response.
Behavior:
- It sends a JSON response with a 500 status code and a generic error message.
- The response includes the request path where the error occurred.
- It uses the models.InternalServerError function to format the error response.
- The function does not return any value.
func HandleSuccess ¶
HandleSuccess sends a JSON response with the provided status code, message, and data. It uses the Gin framework's IndentedJSON method to format the response.
Parameters:
- c: The Gin context used to write the response.
- statusCode: The HTTP status code to be sent in the response.
- message: A string containing a message to include in the response.
- data: An interface{} containing the data to include in the response body.
func HashPassword ¶
HashPassword takes a plain text password as input and returns its hashed representation using the bcrypt algorithm. The function ensures that the password is securely hashed with a default cost factor.
Parameters:
- password: The plain text password to be hashed.
Returns:
- A string containing the hashed password.
- An error if the hashing process fails.
Note:
- The bcrypt algorithm is computationally expensive, which helps protect against brute-force attacks.
- Ensure that the returned error is handled appropriately to avoid security risks.
func ReadEnvironmentVariables ¶
readEnvironmentVariables retrieves necessary environment variables for the application. It returns the host, port, environment, log level, and secret key. If any variable is missing, it uses default values for host, port, and environment.
Types ¶
type MailSender ¶
type MailSender struct {
// contains filtered or unexported fields
}
MailSender implements the Sender interface by communicating with an external notification service to deliver emails.
func NewMailSender ¶
func NewMailSender(notification_service_url string) MailSender
NewMailSender creates and returns a new MailSender instance configured with the provided notification service URL.
Parameters: - notification_service_url: the URL endpoint for the notification service
func (*MailSender) SendVerificationEmail ¶
func (ms *MailSender) SendVerificationEmail(email, pin, name string, ctx *gin.Context) model.APIResponse
SendVerificationEmail implements the Sender interface by sending a verification email with PIN through an external notification service.
The method sends a POST request to the notification service with the email, PIN, and name in the request body. It requires a MAIL_KEY environment variable to be set for authentication with the notification service.
Parameters: - email: the recipient's email address - pin: the verification PIN to include in the email - name: the recipient's name to personalize the email - ctx: the Gin context for handling the response
Returns:
- model.APIResponse: a response object indicating success (200 OK) or containing error details if the operation failed
type PinGenerator ¶
type PinGenerator interface {
GeneratePin() string
}
PinGenerator interface defines the method for generating a PIN
type RandomPinGenerator ¶
type RandomPinGenerator struct{}
RandomPinGenerator is the struct that implements the PinGenerator interface
func NewRandomPinGenerator ¶
func NewRandomPinGenerator() RandomPinGenerator
func (*RandomPinGenerator) GeneratePin ¶
func (r *RandomPinGenerator) GeneratePin() string
GeneratePin generates a 6-digit random authentication PIN as a string. It uses a pseudo-random number generator seeded with the current Unix timestamp in nanoseconds. The generated PIN is zero-padded to ensure it is always 6 digits long. A debug log is created with the generated PIN for tracking purposes. Returns:
string: A 6-digit random PIN.
type Sender ¶
type Sender interface { // SendVerificationEmail sends a verification email with a PIN to the specified email address. // It returns an APIResponse indicating success or failure. // // Parameters: // - email: the recipient's email address // - pin: the verification PIN to include in the email // - name: the recipient's name to personalize the email // - ctx: the Gin context for handling the response SendVerificationEmail(email, pin, name string, ctx *gin.Context) model.APIResponse }
Sender defines the interface for email sending functionality. This interface allows for different implementations of email sending services and makes testing easier through mocking.