App Logo
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

  1. User submits email and password
  2. Account is created (unverified)
  3. Verification email is sent
  4. User clicks verification link
  5. Account is marked as verified
  6. User can sign in

Password Reset Flow

  1. User requests password reset
  2. Reset password email verification link is sent
  3. User clicks link and is redirected back to the app
  4. User submits new password
  5. Old password is changed to the new one
  6. User can sign in with new password

On this page