rentease/internal/service/auth/service.go
Ruidy ac94faedb0
refactor: unify ID and API key naming conventions
This commit standardizes the naming of identifier and API key fields
across the codebase to use consistent camel case (e.g., `ID`, `APIKey`,
`DatabaseURL`). This includes updates to struct fields, method names,
function parameters, and environment variable references. The changes
improve code clarity and maintainability by reducing ambiguity and
aligning with Go naming conventions. No functional behavior is changed.
2025-10-03 19:47:41 +02:00

79 lines
1.5 KiB
Go

package auth
import (
"errors"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/rjNemo/rentease/internal/constant"
)
const (
sessionName = "rentease"
sessionAge = 86400 * 7 // 7 days
)
type Service struct {
secret string
admin string
adminSecret string
apiKey string
}
func NewService(secret, admin, adminSecret, apiKey string) (*Service, error) {
if secret == "" || admin == "" || adminSecret == "" || apiKey == "" {
return nil, errors.New("error building Auth service. Verify your env variables")
}
return &Service{
secret,
admin,
adminSecret,
apiKey,
}, nil
}
func (as *Service) ValidCredentials(email, password string) bool {
return email == as.admin && password == as.adminSecret
}
func (as *Service) ValidateAPIKey(key string) bool {
return key == as.apiKey
}
func (as *Service) getSession(c echo.Context) (*sessions.Session, error) {
sess, err := session.Get(sessionName, c)
if err != nil {
return nil, err
}
sess.Options = &sessions.Options{
Path: constant.RouteLogin,
MaxAge: sessionAge,
HttpOnly: true,
}
return sess, nil
}
func (as *Service) Authenticate(c echo.Context, key string) error {
sess, err := as.getSession(c)
if err != nil {
return err
}
sess.Values["user"] = key
return sess.Save(c.Request(), c.Response())
}
func (as *Service) Authenticated(c echo.Context) bool {
sess, err := as.getSession(c)
if err != nil {
return false
}
user, ok := sess.Values["user"]
return ok && user == "foo"
}