mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-06 02:36:49 +00:00
Switch web framework from Echo to Chi, removing Echo-related dependencies and adding chi and cors. Update Stripe to v83.1.0 and Sentry to v0.36.2. Remove unused and indirect dependencies for a cleaner go.mod/go.sum.
81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"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
|
|
store *sessions.CookieStore
|
|
}
|
|
|
|
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")
|
|
}
|
|
|
|
store := sessions.NewCookieStore([]byte(secret))
|
|
store.Options = &sessions.Options{
|
|
Path: constant.RouteLogin,
|
|
MaxAge: sessionAge,
|
|
HttpOnly: true,
|
|
}
|
|
|
|
return &Service{
|
|
secret: secret,
|
|
admin: admin,
|
|
adminSecret: adminSecret,
|
|
apiKey: apiKey,
|
|
store: store,
|
|
}, 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(r *http.Request) (*sessions.Session, error) {
|
|
sess, err := as.store.Get(r, sessionName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return sess, nil
|
|
}
|
|
|
|
func (as *Service) Authenticate(w http.ResponseWriter, r *http.Request, key string) error {
|
|
sess, err := as.getSession(r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
sess.Values["user"] = key
|
|
return sess.Save(r, w)
|
|
}
|
|
|
|
func (as *Service) Authenticated(r *http.Request) bool {
|
|
sess, err := as.getSession(r)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
user, ok := sess.Values["user"]
|
|
return ok && user == "foo"
|
|
}
|