Add SAML support

Signed-off-by: Bryan Frimin <bryan@getprobo.com>
This commit is contained in:
Bryan Frimin
2025-10-29 18:42:12 +01:00
parent 3018a3e691
commit 2766f8e423
97 changed files with 14824 additions and 2812 deletions

View File

@@ -0,0 +1,95 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
)
type (
AcceptInvitationRequest struct {
InvitationID gid.GID `json:"invitationId"`
}
AcceptInvitationResponse struct {
InvitationID gid.GID `json:"invitationId"`
}
)
func AcceptInvitationHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("failed to list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
// Parse request body
var req AcceptInvitationRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("invalid request body"))
return
}
// Accept the invitation
_, err := authzSvc.AcceptInvitationByID(ctx, req.InvitationID, authResult.User.ID)
if err != nil {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
response := AcceptInvitationResponse{
InvitationID: req.InvitationID,
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

72
pkg/server/auth/auth.go Normal file
View File

@@ -0,0 +1,72 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/filemanager"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type Config struct {
Auth *authsvc.Service
Authz *authz.Service
SAML *authsvc.SAMLService
CookieName string
CookieDomain string
SessionDuration time.Duration
CookieSecret string
FileManager *filemanager.Service
PGClient *pg.Client
Logger *log.Logger
}
type Server struct {
router *chi.Mux
}
func NewServer(cfg Config) (*Server, error) {
router := chi.NewRouter()
MountRoutes(
router,
cfg.Auth,
cfg.Authz,
cfg.SAML,
RoutesConfig{
CookieName: cfg.CookieName,
CookieDomain: cfg.CookieDomain,
SessionDuration: cfg.SessionDuration,
CookieSecret: cfg.CookieSecret,
FileManager: cfg.FileManager,
PGClient: cfg.PGClient,
},
cfg.Logger,
)
return &Server{
router: router,
}, nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}

View File

@@ -0,0 +1,55 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"go.gearno.de/kit/httpserver"
)
type (
ForgetPasswordRequest struct {
Email string `json:"email"`
}
ForgetPasswordResponse struct {
Success bool `json:"success"`
}
)
func ForgetPasswordHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req ForgetPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
err := authSvc.ForgetPassword(r.Context(), req.Email)
if err != nil {
// For security reasons, we don't expose whether an email exists or not
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("cannot process request: %w", err))
return
}
httpserver.RenderJSON(w, http.StatusOK, ForgetPasswordResponse{
Success: true,
})
}
}

View File

@@ -0,0 +1,203 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/pg"
)
type (
ListInvitationsResponse struct {
Invitations []InvitationResponse `json:"invitations"`
}
InvitationResponse struct {
ID gid.GID `json:"id"`
Email string `json:"email"`
FullName string `json:"fullName"`
Role string `json:"role"`
ExpiresAt string `json:"expiresAt"`
AcceptedAt *string `json:"acceptedAt,omitempty"`
CreatedAt string `json:"createdAt"`
Organization OrganizationSummary `json:"organization"`
}
OrganizationSummary struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
}
)
// loadOrganizationByID loads an organization by ID without tenant scope
func loadOrganizationByID(
ctx context.Context,
conn pg.Conn,
orgID gid.GID,
) (*coredata.Organization, error) {
query := `
SELECT
id,
tenant_id,
name,
logo_file_id,
horizontal_logo_file_id,
description,
website_url,
email,
headquarter_address,
custom_domain_id,
created_at,
updated_at
FROM
authz_organizations
WHERE
id = $1
`
row := conn.QueryRow(ctx, query, orgID)
var org coredata.Organization
err := row.Scan(
&org.ID,
&org.TenantID,
&org.Name,
&org.LogoFileID,
&org.HorizontalLogoFileID,
&org.Description,
&org.WebsiteURL,
&org.Email,
&org.HeadquarterAddress,
&org.CustomDomainID,
&org.CreatedAt,
&org.UpdatedAt,
)
if err != nil {
return nil, fmt.Errorf("cannot load organization: %w", err)
}
return &org, nil
}
func ListInvitationsHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("failed to list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
// Get pending invitations for the user
cursor := page.NewCursor(
1000,
nil,
page.Head,
page.OrderBy[coredata.InvitationOrderField]{
Field: coredata.InvitationOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
},
)
invitationFilter := coredata.NewInvitationFilter([]coredata.InvitationStatus{coredata.InvitationStatusPending})
invitationsPage, err := authzSvc.GetUserInvitations(ctx, authResult.User.EmailAddress, cursor, invitationFilter)
if err != nil {
panic(fmt.Errorf("failed to list invitations for user: %w", err))
}
// Build response
response := ListInvitationsResponse{
Invitations: make([]InvitationResponse, 0, len(invitationsPage.Data)),
}
// Load organization data for each invitation
err = authCfg.PGClient.WithConn(ctx, func(conn pg.Conn) error {
for _, invitation := range invitationsPage.Data {
invitationResp := InvitationResponse{
ID: invitation.ID,
Email: invitation.Email,
FullName: invitation.FullName,
Role: invitation.Role,
ExpiresAt: invitation.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"),
CreatedAt: invitation.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
}
if invitation.AcceptedAt != nil {
acceptedAtStr := invitation.AcceptedAt.Format("2006-01-02T15:04:05Z07:00")
invitationResp.AcceptedAt = &acceptedAtStr
}
// Load organization details
org, err := loadOrganizationByID(ctx, conn, invitation.OrganizationID)
if err != nil {
// Log error but continue - organization might have been deleted
return nil
}
invitationResp.Organization = OrganizationSummary{
ID: org.ID,
Name: org.Name,
}
response.Invitations = append(response.Invitations, invitationResp)
}
return nil
})
if err != nil {
panic(fmt.Errorf("failed to load organization details: %w", err))
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

View File

@@ -0,0 +1,201 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"context"
"errors"
"fmt"
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/filemanager"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/server/session"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/pg"
)
type (
AuthenticationStatus string
ListOrganizationsResponse struct {
Organizations []OrganizationResponse `json:"organizations"`
}
OrganizationResponse struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
LogoURL *string `json:"logoUrl,omitempty"`
AuthenticationMethod string `json:"authenticationMethod"` // "password", "saml", or "any"
AuthStatus AuthenticationStatus `json:"authStatus"` // "authenticated", "unauthenticated", "expired"
LoginURL string `json:"loginUrl"` // URL to login (SAML or password login page)
}
)
const (
AuthStatusAuthenticated AuthenticationStatus = "authenticated"
AuthStatusUnauthenticated AuthenticationStatus = "unauthenticated"
AuthStatusExpired AuthenticationStatus = "expired"
)
// generateLogoURL generates a presigned URL for an organization's logo
func generateLogoURL(
ctx context.Context,
fileManager *filemanager.Service,
conn pg.Conn,
logoFileID *gid.GID,
) (*string, error) {
if logoFileID == nil {
return nil, nil
}
var file coredata.File
// Load file without scope since we're in auth context (cross-tenant)
q := `SELECT bucket_name, file_key, file_name, mime_type, file_size FROM files WHERE id = $1`
err := conn.QueryRow(ctx, q, logoFileID).Scan(
&file.BucketName,
&file.FileKey,
&file.FileName,
&file.MimeType,
&file.FileSize,
)
if err != nil {
return nil, fmt.Errorf("cannot load file: %w", err)
}
presignedURL, err := fileManager.GenerateFileUrl(ctx, &file, 1*time.Hour)
if err != nil {
return nil, fmt.Errorf("cannot generate file URL: %w", err)
}
return &presignedURL, nil
}
func ListOrganizationsHandler(authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionAuthCfg := session.AuthConfig{
CookieName: authCfg.CookieName,
CookieSecret: authCfg.CookieSecret,
}
errorHandler := session.ErrorHandler{
OnCookieError: func(err error) {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnParseError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("invalid session"))
},
OnSessionError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("session expired"))
},
OnUserError: func(w http.ResponseWriter, authCfg session.AuthConfig) {
session.ClearCookie(w, authCfg)
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("user not found"))
},
OnTenantError: func(err error) {
panic(fmt.Errorf("failed to list tenants for user: %w", err))
},
}
authResult := session.TryAuth(ctx, w, r, authSvc, authzSvc, sessionAuthCfg, errorHandler)
if authResult == nil {
httpserver.RenderError(w, http.StatusUnauthorized, fmt.Errorf("authentication required"))
return
}
// Get all organizations for the user (without filtering by authentication state)
organizations, err := authzSvc.GetAllUserOrganizations(ctx, authResult.User.ID)
if err != nil {
panic(fmt.Errorf("failed to list organizations for user: %w", err))
}
// Build response with authentication requirements for each organization
response := ListOrganizationsResponse{
Organizations: make([]OrganizationResponse, 0, len(organizations)),
}
for _, org := range organizations {
orgResponse := OrganizationResponse{
ID: org.ID,
Name: org.Name,
}
// Generate logo URL if available
if authCfg.FileManager != nil && authCfg.PGClient != nil {
err := authCfg.PGClient.WithConn(ctx, func(conn pg.Conn) error {
logoURL, err := generateLogoURL(ctx, authCfg.FileManager, conn, org.LogoFileID)
if err != nil {
// Log error but don't fail the request
return nil
}
orgResponse.LogoURL = logoURL
return nil
})
if err != nil {
// Log error but continue
}
}
// Check authentication requirements for this organization
err := authSvc.CheckOrganizationAccess(ctx, authResult.User, org.ID, authResult.Session)
if err != nil {
// User needs additional authentication
var errSAMLRequired authsvc.ErrSAMLAuthRequired
if errors.As(err, &errSAMLRequired) {
orgResponse.AuthenticationMethod = "saml"
orgResponse.AuthStatus = AuthStatusUnauthenticated
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", errSAMLRequired.ConfigID)
} else {
orgResponse.AuthenticationMethod = "password"
orgResponse.AuthStatus = AuthStatusUnauthenticated
orgResponse.LoginURL = "/authentication/login?method=password"
}
} else {
// User has proper authentication
orgResponse.AuthStatus = AuthStatusAuthenticated
// Determine which auth method they used
if authResult.Session.Data.PasswordAuthenticated {
orgResponse.AuthenticationMethod = "password"
orgResponse.LoginURL = "/authentication/login?method=password"
} else if len(authResult.Session.Data.SAMLAuthenticatedOrgs) > 0 {
// Find SAML config for this org
orgResponse.AuthenticationMethod = "saml"
// Try to find the SAML config ID for login URL
if samlInfo, ok := authResult.Session.Data.SAMLAuthenticatedOrgs[org.ID.String()]; ok {
orgResponse.LoginURL = fmt.Sprintf("/auth/saml/login/%s", samlInfo.SAMLConfigID)
} else {
orgResponse.LoginURL = "/authentication/login?method=password"
}
} else {
orgResponse.AuthenticationMethod = "any"
orgResponse.LoginURL = "/authentication/login?method=password"
}
}
response.Organizations = append(response.Organizations, orgResponse)
}
httpserver.RenderJSON(w, http.StatusOK, response)
}
}

View File

@@ -0,0 +1,70 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
"errors"
authsvc "github.com/getprobo/probo/pkg/auth"
"go.gearno.de/kit/httpserver"
)
type (
ResetPasswordRequest struct {
Token string `json:"token"`
Password string `json:"password"`
}
ResetPasswordResponse struct {
Success bool `json:"success"`
}
)
func ResetPasswordHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req ResetPasswordRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
err := authSvc.ResetPassword(r.Context(), req.Token, req.Password)
if err != nil {
var invalidPasswordErr *authsvc.ErrInvalidPassword
var invalidTokenErr *authsvc.ErrInvalidTokenType
if errors.As(err, &invalidPasswordErr) {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
if errors.As(err, &invalidTokenErr) {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("cannot reset password: %w", err))
return
}
httpserver.RenderJSON(w, http.StatusOK, ResetPasswordResponse{
Success: true,
})
}
}

60
pkg/server/auth/router.go Normal file
View File

@@ -0,0 +1,60 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/filemanager"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
"go.gearno.de/kit/pg"
)
type RoutesConfig struct {
CookieName string
CookieDomain string
SessionDuration time.Duration
CookieSecret string
FileManager *filemanager.Service
PGClient *pg.Client
}
func MountRoutes(
r chi.Router,
authSvc *authsvc.Service,
authzSvc *authz.Service,
samlSvc *authsvc.SAMLService,
authCfg RoutesConfig,
logger *log.Logger,
) {
r.Post("/register", SignUpHandler(authSvc, authCfg))
r.Post("/login", SignInHandler(authSvc, authCfg))
r.Delete("/logout", SignOutHandler(authSvc, authCfg))
r.Post("/signup-from-invitation", SignupFromInvitationHandler(authSvc, authCfg))
r.Post("/forget-password", ForgetPasswordHandler(authSvc, authCfg))
r.Post("/reset-password", ResetPasswordHandler(authSvc, authCfg))
r.Post("/check-sso", SAMLCheckSSOHandler(authSvc, logger))
r.Get("/organizations", ListOrganizationsHandler(authSvc, authzSvc, authCfg))
r.Get("/invitations", ListInvitationsHandler(authSvc, authzSvc, authCfg))
r.Post("/invitations/accept", AcceptInvitationHandler(authSvc, authzSvc, authCfg))
// SAML routes
r.Get("/saml/login/{samlConfigID}", SAMLLoginHandler(samlSvc, authSvc, logger))
r.Post("/saml/consume", SAMLACSHandler(samlSvc, authSvc, authzSvc, authCfg, logger))
r.Get("/saml/metadata", SAMLMetadataHandler(samlSvc))
}

View File

@@ -0,0 +1,131 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/authz"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/securecookie"
"go.gearno.de/kit/log"
)
func getSessionIDFromCookie(r *http.Request, authCfg RoutesConfig) (gid.GID, error) {
cookieValue, err := securecookie.Get(r, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
))
if err != nil {
return gid.GID{}, err
}
return gid.ParseGID(cookieValue)
}
func SAMLACSHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, authzSvc *authz.Service, authCfg RoutesConfig, logger *log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := r.ParseForm(); err != nil {
logger.ErrorCtx(ctx, "failed to parse form", log.Error(err))
http.Error(w, "failed to parse form", http.StatusBadRequest)
return
}
if r.FormValue("SAMLResponse") == "" {
logger.WarnCtx(ctx, "missing SAMLResponse")
http.Error(w, "missing SAMLResponse", http.StatusBadRequest)
return
}
if r.FormValue("RelayState") == "" {
logger.WarnCtx(ctx, "missing RelayState")
http.Error(w, "missing RelayState", http.StatusBadRequest)
return
}
userInfo, err := samlSvc.HandleSAMLAssertion(ctx, r)
if err != nil {
logger.ErrorCtx(ctx, "SAML authentication failed", log.Error(err))
http.Error(w, "SAML authentication failed", http.StatusUnauthorized)
return
}
user, err := authSvc.CreateOrGetSAMLUser(ctx, userInfo.Email, userInfo.FullName, userInfo.SAMLSubject)
if err != nil {
logger.ErrorCtx(ctx, "cannot create or get SAML user", log.Error(err), log.String("email", userInfo.Email))
http.Error(w, "failed to create user", http.StatusInternalServerError)
return
}
err = authzSvc.EnsureSAMLMembership(ctx, userInfo.TenantID, user.ID, userInfo.OrganizationID, userInfo.Role)
if err != nil {
logger.ErrorCtx(ctx, "cannot ensure membership", log.Error(err), log.String("user_id", user.ID.String()), log.String("org_id", userInfo.OrganizationID.String()))
http.Error(w, "failed to create membership", http.StatusInternalServerError)
return
}
var session *coredata.Session
if existingSessionID, err := getSessionIDFromCookie(r, authCfg); err == nil {
if existingSession, err := authSvc.GetSession(ctx, existingSessionID); err == nil && existingSession.UserID == user.ID {
session = existingSession
}
}
if session == nil {
session, err = authSvc.CreateSessionForUser(ctx, user.ID, authCfg.SessionDuration)
if err != nil {
logger.ErrorCtx(ctx, "cannot create session", log.Error(err), log.String("user_id", user.ID.String()))
http.Error(w, "failed to create session", http.StatusInternalServerError)
return
}
}
if session.Data.SAMLAuthenticatedOrgs == nil {
session.Data.SAMLAuthenticatedOrgs = make(map[string]coredata.SAMLAuthInfo)
}
session.Data.SAMLAuthenticatedOrgs[userInfo.OrganizationID.String()] = coredata.SAMLAuthInfo{
AuthenticatedAt: time.Now(),
SAMLConfigID: userInfo.SAMLConfigID,
SAMLSubject: userInfo.SAMLSubject,
}
err = authSvc.UpdateSessionData(ctx, session.ID, session.Data)
if err != nil {
logger.ErrorCtx(ctx, "cannot update session data", log.Error(err), log.String("session_id", session.ID.String()))
http.Error(w, "failed to update session", http.StatusInternalServerError)
return
}
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
),
session.ID.String(),
)
logger.InfoCtx(ctx, "SAML login successful", log.String("user_id", user.ID.String()), log.String("org_id", userInfo.OrganizationID.String()))
redirectURL := fmt.Sprintf("/organizations/%s", userInfo.OrganizationID)
http.Redirect(w, r, redirectURL, http.StatusFound)
}
}

View File

@@ -0,0 +1,90 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"go.gearno.de/kit/httpserver"
"go.gearno.de/kit/log"
)
type (
CheckSSORequest struct {
Email string `json:"email"`
}
CheckSSOResponse struct {
SSOAvailable bool `json:"ssoAvailable"`
SAMLConfigID *string `json:"samlConfigId,omitempty"`
OrganizationID *string `json:"organizationId,omitempty"`
EnforcementPolicy *string `json:"enforcementPolicy,omitempty"`
}
)
func SAMLCheckSSOHandler(authSvc *authsvc.Service, logger *log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var req CheckSSORequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
if req.Email == "" {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("email is required"))
return
}
configs, err := authSvc.CheckSSOAvailabilityByEmail(ctx, req.Email)
if err != nil {
logger.ErrorCtx(ctx, "cannot check SSO availability", log.Error(err), log.String("email", req.Email))
httpserver.RenderError(w, http.StatusInternalServerError, fmt.Errorf("cannot check SSO availability"))
return
}
// No SAML configs found for this domain
if len(configs) == 0 {
httpserver.RenderJSON(w, http.StatusOK, CheckSSOResponse{
SSOAvailable: false,
})
return
}
// Multiple SAML configs found - ambiguous, user must use organization-specific SSO URL
if len(configs) > 1 {
logger.WarnCtx(ctx, "multiple SAML configurations found for domain", log.String("email", req.Email), log.Int("count", len(configs)))
httpserver.RenderError(w, http.StatusConflict, fmt.Errorf("multiple SSO configurations found for this domain. Please use your organization-specific SSO login URL"))
return
}
// Single SAML config found - return it
config := configs[0]
configIDStr := config.ID.String()
orgIDStr := config.OrganizationID.String()
enforcementPolicy := string(config.EnforcementPolicy)
httpserver.RenderJSON(w, http.StatusOK, CheckSSOResponse{
SSOAvailable: true,
SAMLConfigID: &configIDStr,
OrganizationID: &orgIDStr,
EnforcementPolicy: &enforcementPolicy,
})
}
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/gid"
"github.com/go-chi/chi/v5"
"go.gearno.de/kit/log"
)
func SAMLLoginHandler(samlSvc *authsvc.SAMLService, authSvc *authsvc.Service, logger *log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
samlConfigIDStr := chi.URLParam(r, "samlConfigID")
if samlConfigIDStr == "" {
logger.WarnCtx(ctx, "missing SAML config ID in URL")
http.Error(w, "missing SAML config ID", http.StatusBadRequest)
return
}
samlConfigID, err := gid.ParseGID(samlConfigIDStr)
if err != nil {
logger.ErrorCtx(ctx, "invalid SAML config ID", log.Error(err), log.String("saml_config_id", samlConfigIDStr))
http.Error(w, "invalid SAML config ID", http.StatusBadRequest)
return
}
tenantID := samlConfigID.TenantID()
config, err := authSvc.WithTenant(tenantID).GetSAMLConfigurationByID(ctx, samlConfigID)
if err != nil {
logger.ErrorCtx(ctx, "cannot load SAML configuration", log.Error(err), log.String("saml_config_id", samlConfigID.String()))
http.Error(w, "SAML configuration not found", http.StatusNotFound)
return
}
redirectURL, err := samlSvc.InitiateSAMLLogin(ctx, config.OrganizationID, tenantID, config.EmailDomain)
if err != nil {
logger.ErrorCtx(ctx, "cannot initiate SAML login", log.Error(err), log.String("saml_config_id", samlConfigID.String()), log.String("org_id", config.OrganizationID.String()), log.String("email_domain", config.EmailDomain))
http.Error(w, fmt.Sprintf("SAML login failed: %v", err), http.StatusInternalServerError)
return
}
logger.InfoCtx(ctx, "SAML login initiated", log.String("saml_config_id", samlConfigID.String()), log.String("org_id", config.OrganizationID.String()), log.String("email_domain", config.EmailDomain))
http.Redirect(w, r, redirectURL, http.StatusFound)
}
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
)
// SAMLMetadataHandler returns an HTTP handler that serves the SAML Service Provider metadata XML
// Uses global SP certificate configured at service startup
func SAMLMetadataHandler(samlSvc *authsvc.SAMLService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
metadataXML, err := samlSvc.GenerateMetadata()
if err != nil {
http.Error(w, fmt.Sprintf("failed to generate metadata: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/samlmetadata+xml")
w.WriteHeader(http.StatusOK)
w.Write(metadataXML)
}
}

View File

@@ -0,0 +1,100 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/securecookie"
"go.gearno.de/kit/httpserver"
)
type (
SignInRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
SignInResponse struct {
User UserResponse `json:"user"`
}
UserResponse struct {
ID gid.GID `json:"id"`
Email string `json:"email"`
FullName string `json:"fullName"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
)
func SignInHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignInRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
var existingSession *coredata.Session
if existingSessionID, err := getSessionIDFromCookie(r, authCfg); err == nil {
if session, err := authSvc.GetSession(r.Context(), existingSessionID); err == nil {
existingSession = session
}
}
session, user, err := authSvc.SignInWithExistingSession(r.Context(), req.Email, req.Password, existingSession)
if err != nil {
var ErrInvalidCredentials *authsvc.ErrInvalidCredentials
if errors.As(err, &ErrInvalidCredentials) {
httpserver.RenderError(w, http.StatusUnauthorized, err)
return
}
panic(fmt.Errorf("cannot sign in: %w", err))
}
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
),
session.ID.String(),
)
httpserver.RenderJSON(
w,
http.StatusOK,
SignInResponse{
User: UserResponse{
ID: user.ID,
Email: user.EmailAddress,
FullName: user.FullName,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
},
},
)
}
}

View File

@@ -0,0 +1,59 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"fmt"
"net/http"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/securecookie"
authsvc "github.com/getprobo/probo/pkg/auth"
"go.gearno.de/kit/httpserver"
)
func SignOutHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sessionID, err := securecookie.Get(r, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
))
if err != nil {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
gid, err := gid.ParseGID(sessionID)
if err != nil {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
err = authSvc.SignOut(r.Context(), gid)
if err != nil {
panic(fmt.Errorf("cannot sign out: %w", err))
}
securecookie.Clear(w, securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
))
w.Header().Set("Clear-Site-Data", "*")
httpserver.RenderJSON(w, http.StatusOK, map[string]bool{"success": true})
}
}

View File

@@ -0,0 +1,93 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"errors"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/securecookie"
"go.gearno.de/kit/httpserver"
)
type (
SignUpRequest struct {
Email string `json:"email"`
Password string `json:"password"`
FullName string `json:"fullName"`
}
SignUpResponse struct {
User UserResponse `json:"user"`
}
)
func SignUpHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignUpRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
user, session, err := authSvc.SignUp(
r.Context(),
req.Email,
req.Password,
req.FullName,
)
if err != nil {
var errUserAlreadyExists *authsvc.ErrUserAlreadyExists
if errors.As(err, &errUserAlreadyExists) {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot register user: %w", err))
return
}
var errSignupDisabled *authsvc.ErrSignupDisabled
if errors.As(err, &errSignupDisabled) {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot register user: %w", err))
return
}
panic(fmt.Errorf("cannot register user: %w", err))
}
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
),
session.ID.String(),
)
httpserver.RenderJSON(
w,
http.StatusOK,
SignUpResponse{
User: UserResponse{
ID: user.ID,
Email: user.EmailAddress,
FullName: user.FullName,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
},
},
)
}
}

View File

@@ -0,0 +1,75 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package auth
import (
"encoding/json"
"fmt"
"net/http"
authsvc "github.com/getprobo/probo/pkg/auth"
"github.com/getprobo/probo/pkg/securecookie"
"go.gearno.de/kit/httpserver"
)
type (
SignupFromInvitationRequest struct {
Token string `json:"token"`
Password string `json:"password"`
FullName string `json:"fullName"`
}
SignupFromInvitationResponse struct {
}
)
func SignupFromInvitationHandler(authSvc *authsvc.Service, authCfg RoutesConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req SignupFromInvitationRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpserver.RenderError(w, http.StatusBadRequest, fmt.Errorf("cannot decode body: %w", err))
return
}
user, session, err := authSvc.SignupFromInvitation(r.Context(), req.Token, req.Password, req.FullName)
if err != nil {
httpserver.RenderError(w, http.StatusBadRequest, err)
return
}
securecookie.Set(
w,
securecookie.DefaultConfig(
authCfg.CookieName,
authCfg.CookieSecret,
),
session.ID.String(),
)
httpserver.RenderJSON(
w,
http.StatusOK,
SignUpResponse{
User: UserResponse{
ID: user.ID,
Email: user.EmailAddress,
FullName: user.FullName,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
},
},
)
}
}