Authentication
Email & Password
Complete email and password setup with verification
package main
import (
"context"
"log"
"net/http"
"os"
gobetterauth "github.com/GoBetterAuth/go-better-auth"
gobetterauthconfig "github.com/GoBetterAuth/go-better-auth/config"
gobetterauthmodels "github.com/GoBetterAuth/go-better-auth/models"
)
func main() {
config := gobetterauthconfig.NewConfig(
gobetterauthconfig.WithAppName("YourAppName"),
gobetterauthconfig.WithDatabase(gobetterauthmodels.DatabaseConfig{
Provider: "postgres",
ConnectionString: os.Getenv("DATABASE_URL"),
}),
gobetterauthconfig.WithEmailPassword(gobetterauthmodels.EmailPasswordConfig{
Enabled: true,
RequireEmailVerification: true,
}),
gobetterauthconfig.WithEmailVerification(gobetterauthmodels.EmailVerificationConfig{
SendOnSignUp: true,
SendVerificationEmail: func(user gobetterauthmodels.User, url string, token string) error {
// Implement your email sending logic here
return nil
},
}),
)
auth := gobetterauth.New(config)
http.Handle("/auth/", auth.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}Password Policies
Configure password requirements:
gobetterauthconfig.WithEmailPassword(gobetterauthmodels.EmailPasswordConfig{
MinPasswordLength: 8,
MaxPasswordLength: 32,
})Custom Password Hashing
Use custom password hashing (bcrypt example):
import "golang.org/x/crypto/bcrypt"
gobetterauthconfig.WithEmailPassword(gobetterauthmodels.EmailPasswordConfig{
Password: &gobetterauthmodels.PasswordConfig{
Hash: func(password string) (string, error) {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashed), nil
},
Verify: func(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
},
},
})User Registration Flow
- User submits email and password
- Account is created (unverified)
- Verification email is sent
- User clicks verification link
- Account is marked as verified
- User can sign in
Password Reset Flow
- User requests password reset
- Reset password email verification link is sent
- User clicks link and is redirected back to the app
- User submits new password
- Old password is changed to the new one
- User can sign in with new password
