jetstream

package module
v0.0.0-...-ecd3492 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2026 License: MIT Imports: 28 Imported by: 0

README

Goravel Jetstream - Ready to Use 🚀

Authentication & App Scaffolding for Goravel — inspired by Laravel Jetstream

Release License

✨ Features

  • 🔐 Authentication — Register, Login, Logout with JWT
  • 🌐 Beautiful Web UI — Clean, professional login, register, dashboard, and profile pages
  • 🛡️ Two-Factor Authentication (2FA) — TOTP QR code generation, confirmation, and 8 recovery codes
  • 👤 Profile Management — Update name, email, password, and account deletion
  • 🖼️ Profile Photo Upload — Upload & delete avatars
  • 🔑 API Personal Access Tokens — Sanctum-style API token management
  • 👥 Team Management — Create teams, invite members by email, manage member roles
  • 🖥️ Browser Session Management — Track active sessions, logout other devices
  • 📧 Email Verification — Verify user email addresses
  • 🔑 Password Reset — Forgot password and reset password functionality
  • 🛡️ CSRF Protection — Middleware for CSRF token validation
  • ⚡ Rate Limiting — Middleware to limit request rates
  • 🌐 RTL Support — Right-to-left language support (Arabic, Hebrew)
  • 🌏 Localization — Multi-language support (English, Arabic, Indonesian)

🚀 Quick Start

1. Install the Package
go get github.com/ferdysetia/goravel-jetstream
2. Register Service Provider

Add to bootstrap/providers.go:

import "github.com/ferdysetia/goravel-jetstream"

func Providers() []foundation.ServiceProvider {
    return []foundation.ServiceProvider{
        &jetstream.ServiceProvider{},
    }
}
3. Add Configuration

Create config/jetstream.go:

package config

import (
    "github.com/ferdysetia/goravel-jetstream"
    "your-project/app/facades"
)

func init() {
    config := facades.Config()
    config.Add("jetstream", jetstream.DefaultConfig())
}
4. Register Migrations

Add to bootstrap/migrations.go:

import "github.com/ferdysetia/goravel-jetstream"

func Migrations() []schema.Migration {
    return []schema.Migration{
        &jetstream.CreateUsersTable{},
        &jetstream.CreatePersonalAccessTokensTable{},
        &jetstream.CreateTeamsTable{},
        &jetstream.CreateTeamUserTable{},
        &jetstream.CreateTeamInvitationsTable{},
        &jetstream.JetstreamPasswordResetTokensTable{},
        &jetstream.JetstreamSessionsTable{},
    }
}
5. Register Web Routes

Add to routes/web.go:

import "github.com/ferdysetia/goravel-jetstream"

func Web() {
    r := route.Routes()
    jetstream.RegisterWebRoutes(r)
}
6. Copy Views

Copy stubs/views/jetstream/ to resources/views/jetstream/ in your project.

7. Run Migrations
go run . artisan migrate

📱 Available Pages

URL Description
/login Login page
/register Registration page
/dashboard Main dashboard
/profile Profile settings
/forgot-password Forgot password page
/reset-password/{token} Reset password page
/user/sessions Browser sessions management

🎨 UI Design

The package includes beautiful, clean, and professional UI with:

  • Inter font family for excellent readability
  • Modern gradient branding with consistent purple theme
  • Responsive design that works on all devices
  • Clean card-based layouts
  • Consistent spacing and typography
  • User dropdown menu with avatar, name, and email
  • Quick actions on dashboard
  • Professional forms with proper validation states

⚙️ Configuration

Edit config/jetstream.go to customize:

config.Add("jetstream", map[string]any{
    "features": []string{
        jetstream.FeatureRegistration,
        jetstream.FeatureProfilePhotos,
        jetstream.FeatureApiTokens,
        jetstream.FeatureDeleteAccount,
        jetstream.FeatureTwoFactorAuthentication,
        jetstream.FeatureTeams,
        jetstream.FeatureBrowserSessions,
    },
    "route_prefix": "/api",
    "auth_guard":   "user",
    "rate_limit": map[string]any{
        "max_requests":   60,
        "window_seconds": 60,
    },
})

🔐 API Endpoints

Authentication
Method Endpoint Description
POST /api/auth/register Register new user
POST /api/auth/login Login & get JWT
POST /api/auth/logout Logout
GET /api/user Get current user
PUT /api/user/profile Update profile
PUT /api/user/password Change password
DELETE /api/user Delete account
2FA
Method Endpoint Description
POST /api/user/two-factor-authentication Enable 2FA
POST /api/user/confirmed-two-factor-authentication Confirm 2FA
DELETE /api/user/two-factor-authentication Disable 2FA
GET /api/user/two-factor-qr-code Get QR Code

📦 What's Included

  • Beautiful HTML templates (Edge)
  • Professional CSS with custom properties
  • Responsive layouts
  • Flash message handling
  • Session management
  • RTL language support
  • Localization files (EN, AR, ID)
  • Migration files
  • Middleware (CSRF, Rate Limiting)
  • Complete API endpoints
  • Web controllers

📄 License

Open-sourced software licensed under the MIT license.

Documentation

Index

Constants

View Source
const (
	// FeatureRegistration enables the user registration endpoint.
	FeatureRegistration = "registration"

	// FeatureProfilePhotos enables profile photo upload support.
	FeatureProfilePhotos = "profile-photos"

	// FeatureApiTokens enables personal access token management.
	FeatureApiTokens = "api-tokens"

	// FeatureDeleteAccount enables the account deletion endpoint.
	FeatureDeleteAccount = "delete-account"

	// FeatureTwoFactorAuthentication enables two-factor authentication (TOTP).
	FeatureTwoFactorAuthentication = "two-factor-authentication"

	// FeatureTeams enables team management and multi-tenancy support.
	FeatureTeams = "teams"

	// FeatureBrowserSessions enables tracking and logging out active browser sessions.
	FeatureBrowserSessions = "browser-sessions"
)

Feature constants define toggleable features in Jetstream.

View Source
const BindingJetstream = "goravel.jetstream"

BindingJetstream is the container binding key for the Jetstream manager.

Variables

View Source
var (
	// App holds the Goravel application instance.
	App foundation.Application

	// ConfigFacade provides access to application configuration.
	ConfigFacade config.Config

	// OrmFacade provides access to the ORM for database operations.
	OrmFacade orm.Orm

	// HashFacade provides access to password hashing.
	HashFacade hash.Hash

	// AuthFacade provides access to authentication.
	// It is a function because auth requires the HTTP context.
	AuthFacade func(ctx ...http.Context) auth.Auth
)

Package-level facade variables, resolved during Boot.

View Source
var Translations = map[string]map[string]string{
	"en": {

		"auth.login":                "Login",
		"auth.register":             "Register",
		"auth.logout":               "Logout",
		"auth.forgot_password":      "Forgot Password",
		"auth.reset_password":       "Reset Password",
		"auth.confirm_password":     "Confirm Password",
		"auth.email":                "Email Address",
		"auth.password":             "Password",
		"auth.remember_me":          "Remember Me",
		"auth.dont_have_account":    "Don't have an account?",
		"auth.already_have_account": "Already have an account?",
		"auth.create_account":       "Create Account",
		"auth.sign_in":              "Sign In",
		"auth.welcome_back":         "Welcome Back",

		"validation.required":          "This field is required.",
		"validation.email":             "Please enter a valid email address.",
		"validation.min_length":        "Password must be at least 8 characters.",
		"validation.confirmed":         "Password confirmation does not match.",
		"validation.these_credentials": "These credentials do not match our records.",

		"dashboard.title":    "Dashboard",
		"dashboard.welcome":  "Welcome back, :name!",
		"dashboard.here_you": "Here's what's happening with your account.",

		"profile.title":   "Profile Information",
		"profile.update":  "Update Profile",
		"profile.name":    "Full Name",
		"profile.save":    "Save Changes",
		"profile.updated": "Profile updated successfully.",

		"password.title":      "Update Password",
		"password.current":    "Current Password",
		"password.new":        "New Password",
		"password.updated":    "Password updated successfully.",
		"password.dont_match": "The provided password does not match your current password.",

		"verification.title":    "Verify Email",
		"verification.message":  "Thanks for signing up! Before getting started, could you verify your email address.",
		"verification.resend":   "Resend Verification Email",
		"verification.sent":     "A new verification link has been sent to your email address.",
		"verification.verified": "Email verified successfully.",

		"reset.title":      "Reset Password",
		"reset.no_problem": "No problem. Just enter your email and we'll send you a reset link.",
		"reset.email_link": "Email Password Reset Link",
		"reset.sent":       "We have emailed your password reset link.",

		"sessions.title":        "Browser Sessions",
		"sessions.manage":       "Manage and logout your active sessions on other browsers and devices.",
		"sessions.active":       "Active Sessions",
		"sessions.current":      "Current Session",
		"sessions.logout_other": "Logout Other Browser Sessions",
		"sessions.deleted":      "Session deleted successfully.",

		"danger.title":            "Delete Account",
		"danger.warning":          "Permanently delete your account and all associated data.",
		"danger.warning_download": "Before deleting your account, please download any data or information that you wish to retain.",
		"danger.delete":           "Delete Account",
		"danger.deleted":          "Account deleted successfully.",

		"button.cancel": "Cancel",
		"button.save":   "Save",
		"button.update": "Update",
		"button.delete": "Delete",
		"button.edit":   "Edit",
		"button.create": "Create",
		"button.submit": "Submit",

		"error.title":        "Error",
		"error.403":          "Forbidden",
		"error.404":          "Page Not Found",
		"error.500":          "Server Error",
		"error.unauthorized": "Unauthenticated.",
		"error.forbidden":    "You do not have permission to access this page.",
	},
	"ar": {

		"auth.login":                "تسجيل الدخول",
		"auth.register":             "التسجيل",
		"auth.logout":               "تسجيل الخروج",
		"auth.forgot_password":      "نسيت كلمة المرور",
		"auth.reset_password":       "إعادة تعيين كلمة المرور",
		"auth.confirm_password":     "تأكيد كلمة المرور",
		"auth.email":                "البريد الإلكتروني",
		"auth.password":             "كلمة المرور",
		"auth.remember_me":          "تذكرني",
		"auth.dont_have_account":    "ليس لديك حساب؟",
		"auth.already_have_account": "لديك حساب بالفعل؟",
		"auth.create_account":       "إنشاء حساب",
		"auth.sign_in":              "تسجيل الدخول",
		"auth.welcome_back":         "مرحباً بعودتك",

		"validation.required":          "هذا الحقل مطلوب.",
		"validation.email":             "الرجاء إدخال بريد إلكتروني صحيح.",
		"validation.min_length":        "يجب أن تكون كلمة المرور 8 أحرف على الأقل.",
		"validation.confirmed":         "تأكيد كلمة المرور غير متطابق.",
		"validation.these_credentials": "هذه البيانات لا تتطابق مع سجلاتنا.",

		"dashboard.title":    "لوحة التحكم",
		"dashboard.welcome":  "مرحباً بعودتك، :name!",
		"dashboard.here_you": "إليك ما يحدث مع حسابك.",

		"profile.title":   "معلومات الملف الشخصي",
		"profile.update":  "تحديث الملف الشخصي",
		"profile.name":    "الاسم الكامل",
		"profile.save":    "حفظ التغييرات",
		"profile.updated": "تم تحديث الملف الشخصي بنجاح.",

		"password.title":      "تحديث كلمة المرور",
		"password.current":    "كلمة المرور الحالية",
		"password.new":        "كلمة المرور الجديدة",
		"password.updated":    "تم تحديث كلمة المرور بنجاح.",
		"password.dont_match": "كلمة المرور المقدمة لا تتطابق مع كلمة المرور الحالية.",

		"verification.title":    "التحقق من البريد الإلكتروني",
		"verification.message":  "شكراً لتسجيلك! قبل البدء، هل يمكنك التحقق من عنوان بريدك الإلكتروني.",
		"verification.resend":   "إعادة إرسال رابط التحقق",
		"verification.sent":     "تم إرسال رابط تحقق جديد إلى عنوان بريدك الإلكتروني.",
		"verification.verified": "تم التحقق من البريد الإلكتروني بنجاح.",

		"reset.title":      "إعادة تعيين كلمة المرور",
		"reset.no_problem": "لا مشكلة. فقط أدخل بريدك الإلكتروني وسنرسل لك رابط إعادة التعيين.",
		"reset.email_link": "إرسال رابط إعادة تعيين كلمة المرور",
		"reset.sent":       "لقد أرسلنا رابط إعادة تعيين كلمة المرور إلى بريدك الإلكتروني.",

		"sessions.title":        "جلسات المتصفح",
		"sessions.manage":       "إدارة وتسجيل الخروج من جلساتك النشطة على المتصفحات والأجهزة الأخرى.",
		"sessions.active":       "الجلسات النشطة",
		"sessions.current":      "الجلسة الحالية",
		"sessions.logout_other": "تسجيل الخروج من المتصفحات الأخرى",
		"sessions.deleted":      "تم حذف الجلسة بنجاح.",

		"danger.title":            "حذف الحساب",
		"danger.warning":          "حذف حسابك وجميع البيانات المرتبطة بشكل دائم.",
		"danger.warning_download": "قبل حذف حسابك، يرجى تنزيل أي بيانات أو معلومات ترغب في الاحتفاظ بها.",
		"danger.delete":           "حذف الحساب",
		"danger.deleted":          "تم حذف الحساب بنجاح.",

		"button.cancel": "إلغاء",
		"button.save":   "حفظ",
		"button.update": "تحديث",
		"button.delete": "حذف",
		"button.edit":   "تعديل",
		"button.create": "إنشاء",
		"button.submit": "إرسال",

		"error.title":        "خطأ",
		"error.403":          "محظور",
		"error.404":          "الصفحة غير موجودة",
		"error.500":          "خطأ في الخادم",
		"error.unauthorized": "غير مصدق.",
		"error.forbidden":    "ليس لديك إذن للوصول إلى هذه الصفحة.",
	},
	"id": {

		"auth.login":                "Masuk",
		"auth.register":             "Daftar",
		"auth.logout":               "Keluar",
		"auth.forgot_password":      "Lupa Kata Sandi",
		"auth.reset_password":       "Reset Kata Sandi",
		"auth.confirm_password":     "Konfirmasi Kata Sandi",
		"auth.email":                "Alamat Email",
		"auth.password":             "Kata Sandi",
		"auth.remember_me":          "Ingat Saya",
		"auth.dont_have_account":    "Tidak punya akun?",
		"auth.already_have_account": "Sudah punya akun?",
		"auth.create_account":       "Buat Akun",
		"auth.sign_in":              "Masuk",
		"auth.welcome_back":         "Selamat Datang Kembali",

		"validation.required":          "Kolom ini wajib diisi.",
		"validation.email":             "Silakan masukkan alamat email yang valid.",
		"validation.min_length":        "Kata sandi harus minimal 8 karakter.",
		"validation.confirmed":         "Konfirmasi kata sandi tidak cocok.",
		"validation.these_credentials": "Kredensial ini tidak cocok dengan catatan kami.",

		"dashboard.title":    "Dasbor",
		"dashboard.welcome":  "Selamat datang kembali, :name!",
		"dashboard.here_you": "Berikut yang terjadi dengan akun Anda.",

		"profile.title":   "Informasi Profil",
		"profile.update":  "Perbarui Profil",
		"profile.name":    "Nama Lengkap",
		"profile.save":    "Simpan Perubahan",
		"profile.updated": "Profil berhasil diperbarui.",

		"password.title":      "Ubah Kata Sandi",
		"password.current":    "Kata Sandi Saat Ini",
		"password.new":        "Kata Sandi Baru",
		"password.updated":    "Kata sandi berhasil diperbarui.",
		"password.dont_match": "Kata sandi yang diberikan tidak cocok dengan kata sandi Anda saat ini.",

		"verification.title":    "Verifikasi Email",
		"verification.message":  "Terima kasih telah mendaftar! Sebelum memulai, bisakah Anda memverifikasi alamat email Anda.",
		"verification.resend":   "Kirim Ulang Link Verifikasi",
		"verification.sent":     "Link verifikasi baru telah dikirim ke alamat email Anda.",
		"verification.verified": "Email berhasil diverifikasi.",

		"reset.title":      "Reset Kata Sandi",
		"reset.no_problem": "Tidak masalah. Cukup masukkan email Anda dan kami akan mengirim link reset.",
		"reset.email_link": "Kirim Link Reset Kata Sandi",
		"reset.sent":       "Kami telah mengirim link reset kata sandi ke email Anda.",

		"sessions.title":        "Sesi Peramban",
		"sessions.manage":       "Kelola dan keluar dari sesi aktif Anda di peramban dan perangkat lain.",
		"sessions.active":       "Sesi Aktif",
		"sessions.current":      "Sesi Saat Ini",
		"sessions.logout_other": "Keluar dari Peramban Lain",
		"sessions.deleted":      "Sesi berhasil dihapus.",

		"danger.title":            "Hapus Akun",
		"danger.warning":          "Hapus akun Anda dan semua data terkait secara permanen.",
		"danger.warning_download": "Sebelum menghapus akun Anda, silakan unduh data atau informasi yang ingin Anda simpan.",
		"danger.delete":           "Hapus Akun",
		"danger.deleted":          "Akun berhasil dihapus.",

		"button.cancel": "Batal",
		"button.save":   "Simpan",
		"button.update": "Perbarui",
		"button.delete": "Hapus",
		"button.edit":   "Edit",
		"button.create": "Buat",
		"button.submit": "Kirim",

		"error.title":        "Kesalahan",
		"error.403":          "Dilarang",
		"error.404":          "Halaman Tidak Ditemukan",
		"error.500":          "Kesalahan Server",
		"error.unauthorized": "Tidak terautentikasi.",
		"error.forbidden":    "Anda tidak memiliki izin untuk mengakses halaman ini.",
	},
}

Translations contains all Jetstream localization strings

Functions

func AddTeamMember

func AddTeamMember(ctx http.Context) http.Response

AddTeamMember invites a user to a team by email. POST /api/teams/{id}/members

func ConfirmTwoFactor

func ConfirmTwoFactor(ctx http.Context) http.Response

ConfirmTwoFactor confirms 2FA setup by verifying a 6-digit code. POST /api/user/confirmed-two-factor-authentication

func CreateTeam

func CreateTeam(ctx http.Context) http.Response

CreateTeam creates a new team owned by the authenticated user. POST /api/teams

Request body:

{
  "name": "string"
}

func CreateToken

func CreateToken(ctx http.Context) http.Response

CreateToken creates a new personal access token for the authenticated user. POST /api/user/tokens

Request body:

{
  "name": "string",
  "abilities": ["string"]  // optional, defaults to ["*"]
}

func CurrentUser

func CurrentUser(ctx http.Context) http.Response

CurrentUser returns the currently authenticated user's information. GET /api/user

func Dashboard

func Dashboard(ctx http.Context) http.Response

Dashboard displays the main dashboard page for authenticated users. GET /dashboard

func DefaultConfig

func DefaultConfig() map[string]any

DefaultConfig returns the default Jetstream configuration map. Users should copy this into their config/jetstream.go file, or use it directly: config.Add("jetstream", jetstream.DefaultConfig())

func DeleteAccount

func DeleteAccount(ctx http.Context) http.Response

DeleteAccount deletes the authenticated user's account after password confirmation. DELETE /api/user

Request body:

{
  "password": "string"
}

func DeleteProfilePhoto

func DeleteProfilePhoto(ctx http.Context) http.Response

DeleteProfilePhoto removes the user's profile photo from storage and clears the DB field. DELETE /api/user/profile-photo

func DeleteTeam

func DeleteTeam(ctx http.Context) http.Response

DeleteTeam deletes a team. DELETE /api/teams/{id}

func DeleteToken

func DeleteToken(ctx http.Context) http.Response

DeleteToken deletes a personal access token for the authenticated user. DELETE /api/user/tokens/{id}

func DisableTwoFactor

func DisableTwoFactor(ctx http.Context) http.Response

DisableTwoFactor disables 2FA for the user. DELETE /api/user/two-factor-authentication

func EnableTwoFactor

func EnableTwoFactor(ctx http.Context) http.Response

EnableTwoFactor generates a new TOTP secret & recovery codes for the user. POST /api/user/two-factor-authentication

func ForgotPassword

func ForgotPassword(ctx http.Context) http.Response

ForgotPassword handles the forgot password request. POST /api/forgot-password

func GetDirection

func GetDirection(locale string) string

GetDirection returns the text direction for the given locale

func GetRecoveryCodes

func GetRecoveryCodes(ctx http.Context) http.Response

GetRecoveryCodes returns the user's recovery codes. GET /api/user/two-factor-recovery-codes

func GetSupportedLocales

func GetSupportedLocales() []string

GetSupportedLocales returns a list of supported locales

func GetTeam

func GetTeam(ctx http.Context) http.Response

GetTeam returns team details, owner, members, and pending invitations. GET /api/teams/{id}

func GetTwoFactorQrCode

func GetTwoFactorQrCode(ctx http.Context) http.Response

GetTwoFactorQrCode returns the QR code Data URI for scanning in Authenticator apps. GET /api/user/two-factor-qr-code

func Home

func Home(ctx http.Context) http.Response

Home redirects to dashboard if authenticated, otherwise to login. GET /

func IsRTL

func IsRTL(locale string) bool

IsRTL checks if the given locale is RTL

func ListSessions

func ListSessions(ctx http.Context) http.Response

ListSessions returns all active tokens/sessions for the authenticated user, including IP addresses and User-Agent strings. GET /api/user/sessions

func ListTeams

func ListTeams(ctx http.Context) http.Response

ListTeams returns all teams where the user is an owner or member. GET /api/teams

func ListTokens

func ListTokens(ctx http.Context) http.Response

ListTokens returns all personal access tokens for the authenticated user. GET /api/user/tokens

func Login

func Login(ctx http.Context) http.Response

Login handles user authentication. POST /api/auth/login

Request body:

{
  "email": "string",
  "password": "string"
}

func Logout

func Logout(ctx http.Context) http.Response

Logout handles user logout by invalidating the current JWT token. POST /api/auth/logout

func LogoutOtherBrowserSessions

func LogoutOtherBrowserSessions(ctx http.Context) http.Response

LogoutOtherBrowserSessions revokes all tokens/sessions for the user EXCEPT the current token. DELETE /api/user/other-browser-sessions

Request body:

{
  "password": "string"
}

func NewCsrfMiddleware

func NewCsrfMiddleware() http.Middleware

NewCsrfMiddleware returns a new CsrfMiddleware instance.

func NewJwtAuthMiddleware

func NewJwtAuthMiddleware() http.Middleware

NewJwtAuthMiddleware returns a new JwtAuth middleware instance.

func NewRateLimiterMiddleware

func NewRateLimiterMiddleware() http.Middleware

NewRateLimiterMiddleware returns a new RateLimiter middleware instance.

func RegenerateRecoveryCodes

func RegenerateRecoveryCodes(ctx http.Context) http.Response

RegenerateRecoveryCodes generates new recovery codes for the user. POST /api/user/two-factor-recovery-codes

func Register

func Register(ctx http.Context) http.Response

Register handles user registration. POST /api/auth/register

Request body:

{
  "name": "string",
  "email": "string",
  "password": "string",
  "password_confirmation": "string"
}

func RegisterRoutes

func RegisterRoutes(router route.Route)

RegisterRoutes registers all Jetstream API routes on the given route instance. This is called automatically by the ServiceProvider during Boot.

func RegisterWebRoutes

func RegisterWebRoutes(router route.Route)

RegisterWebRoutes registers all Jetstream web routes (HTML views). These routes provide the UI pages for login, register, dashboard, and profile. Call this function in your routes/web.go file.

func RemoveTeamMember

func RemoveTeamMember(ctx http.Context) http.Response

RemoveTeamMember removes a member from a team. DELETE /api/teams/{id}/members/{user_id}

func Replace

func Replace(s, old, new string) string

Replace replaces all occurrences of old with new in s

func ResendEmailVerificationLink(ctx http.Context) http.Response

ResendEmailVerificationLink resends the verification email. POST /email/verification-notification

func ResendVerificationEmail

func ResendVerificationEmail(ctx http.Context) http.Response

ResendVerificationEmail resends the verification email. POST /api/email/resend

func ResetPassword

func ResetPassword(ctx http.Context) http.Response

ResetPassword handles the password reset request. POST /api/reset-password

func SendVerificationEmail

func SendVerificationEmail(ctx http.Context) http.Response

SendVerificationEmail sends a verification email to the authenticated user. POST /api/email/verification-notification

func ShowEmailVerificationNotice

func ShowEmailVerificationNotice(ctx http.Context) http.Response

ShowEmailVerificationNotice displays the email verification notice page. GET /email/verification-notification

func ShowForgotPasswordForm

func ShowForgotPasswordForm(ctx http.Context) http.Response

ShowForgotPasswordForm displays the forgot password page. GET /forgot-password

func ShowLoginForm

func ShowLoginForm(ctx http.Context) http.Response

ShowLoginForm displays the login page. GET /login

func ShowProfile

func ShowProfile(ctx http.Context) http.Response

ShowProfile displays the profile editing page. GET /profile

func ShowRegisterForm

func ShowRegisterForm(ctx http.Context) http.Response

ShowRegisterForm displays the registration page. GET /register

func ShowResetPasswordForm

func ShowResetPasswordForm(ctx http.Context) http.Response

ShowResetPasswordForm displays the reset password page. GET /reset-password/{token}

func ShowSessionsPage

func ShowSessionsPage(ctx http.Context) http.Response

ShowSessionsPage displays the browser sessions management page. GET /user/sessions

func Translate

func Translate(key string, locale string) string

Translate returns the translation for the given key and locale

func TranslateWithParams

func TranslateWithParams(key string, locale string, params map[string]string) string

TranslateWithParams returns the translation with parameter replacement

func UpdatePassword

func UpdatePassword(ctx http.Context) http.Response

UpdatePassword updates the authenticated user's password. PUT /api/user/password

Request body:

{
  "current_password": "string",
  "password": "string",
  "password_confirmation": "string"
}

func UpdateProfile

func UpdateProfile(ctx http.Context) http.Response

UpdateProfile updates the authenticated user's profile information. PUT /api/user/profile

Request body:

{
  "name": "string",
  "email": "string"
}

func UpdateTeam

func UpdateTeam(ctx http.Context) http.Response

UpdateTeam updates a team's name. PUT /api/teams/{id}

func UploadProfilePhoto

func UploadProfilePhoto(ctx http.Context) http.Response

UploadProfilePhoto uploads a profile photo image to storage and updates the user's profile. POST /api/user/profile-photo

func VerifyEmail

func VerifyEmail(ctx http.Context) http.Response

VerifyEmail verifies a user's email address. GET /api/email/verify/{id}/{hash}

func WebDeleteAccount

func WebDeleteAccount(ctx http.Context) http.Response

WebDeleteAccount handles account deletion via web form. DELETE /user

func WebDestroySession

func WebDestroySession(ctx http.Context) http.Response

WebDestroySession destroys a specific session. DELETE /user/sessions/{session_id}

func WebForgotPassword

func WebForgotPassword(ctx http.Context) http.Response

WebForgotPassword handles the forgot password form submission. POST /forgot-password

func WebLogin

func WebLogin(ctx http.Context) http.Response

WebLogin handles user authentication via web form. POST /login

func WebLogout

func WebLogout(ctx http.Context) http.Response

WebLogout handles user logout via web. POST /logout

func WebRegister

func WebRegister(ctx http.Context) http.Response

WebRegister handles user registration via web form. POST /register

func WebResetPassword

func WebResetPassword(ctx http.Context) http.Response

WebResetPassword handles the reset password form submission. POST /reset-password

func WebUpdatePassword

func WebUpdatePassword(ctx http.Context) http.Response

WebUpdatePassword handles password update via web form. PUT /user/password

func WebUpdateProfile

func WebUpdateProfile(ctx http.Context) http.Response

WebUpdateProfile handles profile update via web form. PUT /user/profile-information

func WebVerifyEmail

func WebVerifyEmail(ctx http.Context) http.Response

WebVerifyEmail verifies email via web link. GET /email/verify/{id}/{hash}

Types

type AuthHandler

type AuthHandler interface {
	// Register handles user registration.
	Register(ctx http.Context) http.Response
	// Login handles user authentication.
	Login(ctx http.Context) http.Response
	// Logout handles user logout.
	Logout(ctx http.Context) http.Response
}

AuthHandler defines custom authentication behavior. Implement this interface to override default auth logic.

type Authenticatable

type Authenticatable interface {
	// GetID returns the unique identifier for the user.
	GetID() uint
	// GetEmail returns the user's email address.
	GetEmail() string
	// GetPassword returns the user's hashed password.
	GetPassword() string
}

Authenticatable defines the interface that your User model must implement to work with Jetstream authentication.

type CreatePersonalAccessTokensTable

type CreatePersonalAccessTokensTable struct{}

CreatePersonalAccessTokensTable is the migration that creates the personal_access_tokens table.

func (*CreatePersonalAccessTokensTable) Down

func (*CreatePersonalAccessTokensTable) Signature

func (r *CreatePersonalAccessTokensTable) Signature() string

func (*CreatePersonalAccessTokensTable) Up

type CreateTeamInvitationsTable

type CreateTeamInvitationsTable struct{}

CreateTeamInvitationsTable is the migration that creates the team_invitations table.

func (*CreateTeamInvitationsTable) Down

func (*CreateTeamInvitationsTable) Signature

func (r *CreateTeamInvitationsTable) Signature() string

func (*CreateTeamInvitationsTable) Up

type CreateTeamUserTable

type CreateTeamUserTable struct{}

CreateTeamUserTable is the migration that creates the team_user pivot table.

func (*CreateTeamUserTable) Down

func (r *CreateTeamUserTable) Down() error

func (*CreateTeamUserTable) Signature

func (r *CreateTeamUserTable) Signature() string

func (*CreateTeamUserTable) Up

func (r *CreateTeamUserTable) Up() error

type CreateTeamsTable

type CreateTeamsTable struct{}

CreateTeamsTable is the migration that creates the teams table.

func (*CreateTeamsTable) Down

func (r *CreateTeamsTable) Down() error

func (*CreateTeamsTable) Signature

func (r *CreateTeamsTable) Signature() string

func (*CreateTeamsTable) Up

func (r *CreateTeamsTable) Up() error

type CreateUsersTable

type CreateUsersTable struct{}

CreateUsersTable is the migration that creates the users table.

func (*CreateUsersTable) Down

func (r *CreateUsersTable) Down() error

func (*CreateUsersTable) Signature

func (r *CreateUsersTable) Signature() string

func (*CreateUsersTable) Up

func (r *CreateUsersTable) Up() error

type CsrfMiddleware

type CsrfMiddleware struct{}

CsrfMiddleware provides CSRF protection for web routes. This middleware validates the CSRF token sent in requests to prevent cross-site request forgery attacks.

func (*CsrfMiddleware) Handle

func (m *CsrfMiddleware) Handle(ctx http.Context)

Handle processes the incoming HTTP request and validates the CSRF token.

func (*CsrfMiddleware) Signature

func (m *CsrfMiddleware) Signature() string

Signature returns the unique identifier for this middleware.

type Jetstream

type Jetstream struct {
	// contains filtered or unexported fields
}

Jetstream is the core manager that holds configuration and provides feature checking capabilities.

func NewJetstream

func NewJetstream(cfg config.Config) *Jetstream

NewJetstream creates a new Jetstream instance with the given config.

func (*Jetstream) GetAuthGuard

func (j *Jetstream) GetAuthGuard() string

GetAuthGuard returns the configured authentication guard name.

func (*Jetstream) GetRoutePrefix

func (j *Jetstream) GetRoutePrefix() string

GetRoutePrefix returns the configured route prefix.

func (*Jetstream) HasFeature

func (j *Jetstream) HasFeature(feature string) bool

HasFeature checks if a given feature is enabled in the Jetstream configuration.

type JetstreamPasswordResetTokensTable

type JetstreamPasswordResetTokensTable struct{}

CreatePasswordResetTokensTable creates the password_reset_tokens table.

func (*JetstreamPasswordResetTokensTable) Down

func (*JetstreamPasswordResetTokensTable) Signature

func (*JetstreamPasswordResetTokensTable) Up

type JetstreamSessionsTable

type JetstreamSessionsTable struct{}

CreateSessionsTable creates the sessions table for web session tracking.

func (*JetstreamSessionsTable) Down

func (r *JetstreamSessionsTable) Down() error

func (*JetstreamSessionsTable) Signature

func (r *JetstreamSessionsTable) Signature() string

func (*JetstreamSessionsTable) Up

func (r *JetstreamSessionsTable) Up() error

type JwtAuth

type JwtAuth struct{}

JwtAuth is an HTTP middleware that verifies JWT tokens from the Authorization header. If the token is invalid or missing, it returns a 401 Unauthorized response.

func (*JwtAuth) Handle

func (m *JwtAuth) Handle(ctx http.Context)

Handle processes the incoming HTTP request and validates the JWT token.

func (*JwtAuth) Signature

func (m *JwtAuth) Signature() string

Signature returns the unique identifier for this middleware.

type NewAccessToken

type NewAccessToken struct {
	AccessToken    *PersonalAccessToken `json:"access_token"`
	PlainTextToken string               `json:"plain_text_token"`
}

NewAccessToken holds the result of creating a new personal access token. PlainTextToken is only available at creation time and is never stored.

type PersonalAccessToken

type PersonalAccessToken struct {
	orm.Model
	UserID     uint   `gorm:"not null;index" json:"user_id"`
	Name       string `gorm:"not null" json:"name"`
	Token      string `gorm:"uniqueIndex;not null;size:64" json:"-"`
	Abilities  string `gorm:"type:text;default:'[\"*\"]'" json:"abilities"`
	IPAddress  string `gorm:"default:null" json:"ip_address,omitempty"`
	UserAgent  string `gorm:"default:null" json:"user_agent,omitempty"`
	LastUsedAt string `gorm:"default:null" json:"last_used_at,omitempty"`
	ExpiresAt  string `gorm:"default:null" json:"expires_at,omitempty"`
}

PersonalAccessToken represents an API token or browser session issued to a user. Tokens are stored as SHA-256 hashes; the plain-text token is only returned once at creation time.

type ProfileHandler

type ProfileHandler interface {
	// UpdateProfile handles profile information updates.
	UpdateProfile(ctx http.Context) http.Response
	// UpdatePassword handles password changes.
	UpdatePassword(ctx http.Context) http.Response
	// DeleteAccount handles account deletion.
	DeleteAccount(ctx http.Context) http.Response
}

ProfileHandler defines custom profile management behavior.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides rate limiting functionality to prevent abuse.

func NewRateLimiterWithConfig

func NewRateLimiterWithConfig(config RateLimiterConfig) *RateLimiter

NewRateLimiterWithConfig creates a new RateLimiter with the given configuration.

func (*RateLimiter) Cleanup

func (r *RateLimiter) Cleanup()

Cleanup removes expired entries from the rate limiter.

func (*RateLimiter) GetRemaining

func (r *RateLimiter) GetRemaining(identifier string) int

GetRemaining returns the number of remaining requests for the identifier.

func (*RateLimiter) Handle

func (m *RateLimiter) Handle(ctx http.Context)

Handle processes the incoming HTTP request and enforces rate limiting.

func (*RateLimiter) IsLimited

func (r *RateLimiter) IsLimited(identifier string) bool

IsLimited checks if the identifier has exceeded the rate limit.

func (*RateLimiter) RecordRequest

func (r *RateLimiter) RecordRequest(identifier string)

RecordRequest records a request for the given identifier.

func (*RateLimiter) Signature

func (m *RateLimiter) Signature() string

Signature returns the unique identifier for this middleware.

type RateLimiterConfig

type RateLimiterConfig struct {
	MaxRequests int           // Maximum requests allowed in the window
	Window      time.Duration // Time window for rate limiting
}

RateLimiterConfig holds the configuration for the rate limiter.

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() RateLimiterConfig

DefaultRateLimiterConfig returns the default rate limiter configuration.

type ServiceProvider

type ServiceProvider struct{}

ServiceProvider registers Jetstream's services and routes into the Goravel application container.

Usage in bootstrap/providers.go:

&jetstream.ServiceProvider{}

func (*ServiceProvider) Boot

func (r *ServiceProvider) Boot(app foundation.Application)

Boot resolves facade dependencies and registers routes. This is called after all service providers have been registered, ensuring that Auth, Hash, ORM, and Route are available.

func (*ServiceProvider) Register

func (r *ServiceProvider) Register(app foundation.Application)

Register binds the Jetstream manager into the service container.

type Session

type Session struct {
	ID        string
	IPAddress string
	UserAgent string
	IsCurrent bool
}

Session represents a browser session

type Team

type Team struct {
	orm.Model
	UserID       uint   `gorm:"not null;index" json:"user_id"` // Owner ID
	Name         string `gorm:"not null" json:"name"`
	PersonalTeam bool   `gorm:"default:false" json:"personal_team"`
}

Team represents a team/organization in Jetstream.

type TeamInvitation

type TeamInvitation struct {
	orm.Model
	TeamID uint   `gorm:"not null;index" json:"team_id"`
	Email  string `gorm:"not null" json:"email"`
	Role   string `gorm:"default:'editor'" json:"role"`
}

TeamInvitation represents a pending invitation to join a team.

type TeamMemberResponse

type TeamMemberResponse struct {
	ID       uint   `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Role     string `json:"role"`
	JoinedAt string `json:"joined_at"`
}

TeamMemberResponse represents a team member returned in API responses.

type TeamUser

type TeamUser struct {
	orm.Model
	TeamID uint   `gorm:"not null;index" json:"team_id"`
	UserID uint   `gorm:"not null;index" json:"user_id"`
	Role   string `gorm:"default:'editor'" json:"role"`
}

TeamUser is the pivot model linking users to teams with specific roles.

type TokenableUser

type TokenableUser interface {
	Authenticatable
}

TokenableUser extends Authenticatable with API token capabilities.

type User

type User struct {
	orm.Model
	Name                   string     `gorm:"not null" json:"name"`
	Email                  string     `gorm:"uniqueIndex;not null" json:"email"`
	Password               string     `gorm:"not null" json:"-"`
	EmailVerifiedAt        *time.Time `gorm:"default:null" json:"email_verified_at,omitempty"`
	ProfilePhotoPath       string     `gorm:"default:null" json:"profile_photo_path,omitempty"`
	TwoFactorSecret        string     `gorm:"default:null" json:"-"`
	TwoFactorRecoveryCodes string     `gorm:"type:text;default:null" json:"-"`
	TwoFactorConfirmedAt   string     `gorm:"default:null" json:"two_factor_confirmed_at,omitempty"`
	CurrentTeamID          uint       `gorm:"default:null" json:"current_team_id,omitempty"`
}

User is the default user model provided by Jetstream. It embeds orm.Model which provides ID, CreatedAt, and UpdatedAt fields.

func (*User) GetEmail

func (u *User) GetEmail() string

GetEmail returns the user's email address.

func (*User) GetID

func (u *User) GetID() uint

GetID returns the user's unique identifier.

func (*User) GetPassword

func (u *User) GetPassword() string

GetPassword returns the user's hashed password.

func (*User) HasTwoFactorEnabled

func (u *User) HasTwoFactorEnabled() bool

HasTwoFactorEnabled checks if the user has 2FA enabled and confirmed.

func (*User) HasVerifiedEmail

func (u *User) HasVerifiedEmail() bool

HasVerifiedEmail checks if the user has verified their email.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL