Overview
The auth package includes:- User registration and login
- Secure password hashing with bcrypt and salt
- Session-based authentication
- Middleware for protecting routes
- Password change and account deletion
- Context helpers for accessing the current user
Setting Up Authentication
1
Create database and session domains
2
Create auth repository and service
3
Run migrations
Service Methods
Theauth.Service provides methods for user management:
Register User
- Username: 5-20 characters
- Password: 8-100 characters
Login
Logout
Change Password
Delete Account
Middleware for Route Protection
TheAuthenticationMiddleware validates sessions and injects the user into the request context:
- Reads the session cookie
- Validates the session
- Retrieves the user from the database
- Injects the user into the context
- Returns 401 if authentication fails
Accessing the Current User
Useauth.UserFromContext to get the authenticated user:
HTTP Handlers
The auth package includes built-in HTTP handlers:Register Handler
201 Createdon success400 Bad Requestif validation fails500 Internal Server Erroron database errors
Login Handler
200 OKand sets session cookie on success401 Unauthorizedfor invalid credentials
Other Handlers
The package also provides:NewLogoutHandler- Deletes session and clears cookieNewChangePasswordHandler- Changes user password (requires auth)NewGetHandler- Returns current user info (requires auth)NewDeleteHandler- Deletes user account (requires auth)
auth/handler_*.go in the source code for implementation details.
Custom Validation
Provide custom validators when creating the service:Password Security
Platforma uses bcrypt with salt for secure password storage:User Model
TheUser struct represents a user:
Error Types
The auth package defines these error types:ErrUserNotFound- User doesn’t existErrInvalidUsername- Username validation failedErrInvalidPassword- Password validation failedErrWrongUserOrPassword- Login failedErrCurrentPasswordIncorrect- Password change failedErrShortUsername/ErrLongUsername- Length validationErrShortPassword/ErrLongPassword- Length validation
Complete Example
Repository Interface
TheRepository implements the migrator interface and provides database operations:
auth/migrations/*.sql and automatically applied when you call db.Migrate(ctx).
Best Practices
Use HTTPS
Always serve your application over HTTPS to protect session cookies from interception.
Set cookie flags
Use
HttpOnly and SameSite flags on session cookies to prevent XSS and CSRF attacks.Validate on both sides
Validate input on both client and server side for better UX and security.
Log auth events
Log login attempts, password changes, and account deletions for security auditing.