126: auth Package Documentation

Introduction:

The auth package provides functionalities for encrypting passwords and generating JWT (JSON Web Tokens) for user authentication and authorization purposes. The encryption is done using the bcrypt algorithm, and JWT generation uses the jwt-go package. It's a minimalistic library meant to provide developers with a quick way to secure their applications.

Features:

  1. Password Encryption: Encrypt plain text passwords for secure storage.
  2. Password Comparison: Check if a given plain text password matches its encrypted form.
  3. JWT Generation: Issue a new JWT token with specific claims.

Dependencies:

  • github.com/dgrijalva/jwt-go: Used for JWT generation and signing.
  • golang.org/x/crypto/bcrypt: Used for encrypting and comparing passwords using bcrypt.

Functions:

  1. Encrypt(source string) (string, error):
    • Encrypts the provided plain text string using bcrypt.
    • Arguments:
      • source: The plain text string to encrypt.
    • Returns:
      • Encrypted string.
      • Error (if any).
  2. Compare(hashedPassword, password string) error:
    • Compares an encrypted password string with a plain text password.
    • Arguments:
      • hashedPassword: The encrypted password.
      • password: The plain text password to compare.
    • Returns:
      • Error if the two passwords don't match or any other issue arises. Otherwise, nil.
  3. Sign(secretID, secretKey, iss, aud string) string:
    • Issues a new JWT token with specified claims.
    • Arguments:
      • secretID: The Key ID for JWT.
      • secretKey: The secret key used for signing the JWT.
      • iss: Issuer of the JWT.
      • aud: Audience for which the JWT is intended.
    • Returns:
      • JWT string.

Usage Example:

Password Encryption & Comparison:

password := "mySecurePassword"

// Encrypt the password
hashedPassword, err := auth.Encrypt(password)
if err != nil {
    log.Fatalf("Error encrypting password: %v", err)
}

// Compare encrypted password with the plain one
err = auth.Compare(hashedPassword, password)
if err != nil {
    log.Fatalf("Passwords do not match or error occurred: %v", err)
}

JWT Token Generation:

secretID := "mySecretID"
secretKey := "mySuperSecretKey"
issuer := "myApp"
audience := "user123"

// Generate JWT
token := auth.Sign(secretID, secretKey, issuer, audience)
fmt.Println("Generated JWT:", token)

Conclusion:

This package is a foundational building block for developers to integrate robust authentication and authorization mechanisms into their Golang applications. Always ensure to keep your secretKey confidential and periodically rotate it for enhanced security.