mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2025-10-30 05:35:44 +00:00
Compare commits
3 Commits
refactor/a
...
refactor/e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3745394c8c | ||
|
|
f3471880ee | ||
|
|
52f189563b |
6
.github/workflows/release.yml
vendored
6
.github/workflows/release.yml
vendored
@@ -125,9 +125,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||||
tags: |
|
tags: |
|
||||||
type=semver,pattern=v{{version}}
|
type=semver,pattern={{version}},prefix=v
|
||||||
type=semver,pattern=v{{major}}
|
type=semver,pattern={{major}},prefix=v
|
||||||
type=semver,pattern=v{{major}}.{{minor}}
|
type=semver,pattern={{major}}.{{minor}},prefix=v
|
||||||
|
|
||||||
- name: Create manifest list and push
|
- name: Create manifest list and push
|
||||||
working-directory: ${{ runner.temp }}/digests
|
working-directory: ${{ runner.temp }}/digests
|
||||||
|
|||||||
63
cmd/root.go
63
cmd/root.go
@@ -2,6 +2,7 @@ package cmd
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -11,6 +12,7 @@ import (
|
|||||||
"tinyauth/internal/assets"
|
"tinyauth/internal/assets"
|
||||||
"tinyauth/internal/auth"
|
"tinyauth/internal/auth"
|
||||||
"tinyauth/internal/docker"
|
"tinyauth/internal/docker"
|
||||||
|
"tinyauth/internal/handlers"
|
||||||
"tinyauth/internal/hooks"
|
"tinyauth/internal/hooks"
|
||||||
"tinyauth/internal/providers"
|
"tinyauth/internal/providers"
|
||||||
"tinyauth/internal/types"
|
"tinyauth/internal/types"
|
||||||
@@ -33,8 +35,8 @@ var rootCmd = &cobra.Command{
|
|||||||
|
|
||||||
// Get config
|
// Get config
|
||||||
var config types.Config
|
var config types.Config
|
||||||
parseErr := viper.Unmarshal(&config)
|
err := viper.Unmarshal(&config)
|
||||||
HandleError(parseErr, "Failed to parse config")
|
HandleError(err, "Failed to parse config")
|
||||||
|
|
||||||
// Secrets
|
// Secrets
|
||||||
config.Secret = utils.GetSecret(config.Secret, config.SecretFile)
|
config.Secret = utils.GetSecret(config.Secret, config.SecretFile)
|
||||||
@@ -45,8 +47,8 @@ var rootCmd = &cobra.Command{
|
|||||||
|
|
||||||
// Validate config
|
// Validate config
|
||||||
validator := validator.New()
|
validator := validator.New()
|
||||||
validateErr := validator.Struct(config)
|
err = validator.Struct(config)
|
||||||
HandleError(validateErr, "Failed to validate config")
|
HandleError(err, "Failed to validate config")
|
||||||
|
|
||||||
// Logger
|
// Logger
|
||||||
log.Logger = log.Level(zerolog.Level(config.LogLevel))
|
log.Logger = log.Level(zerolog.Level(config.LogLevel))
|
||||||
@@ -54,9 +56,8 @@ var rootCmd = &cobra.Command{
|
|||||||
|
|
||||||
// Users
|
// Users
|
||||||
log.Info().Msg("Parsing users")
|
log.Info().Msg("Parsing users")
|
||||||
users, usersErr := utils.GetUsers(config.Users, config.UsersFile)
|
users, err := utils.GetUsers(config.Users, config.UsersFile)
|
||||||
|
HandleError(err, "Failed to parse users")
|
||||||
HandleError(usersErr, "Failed to parse users")
|
|
||||||
|
|
||||||
if len(users) == 0 && !utils.OAuthConfigured(config) {
|
if len(users) == 0 && !utils.OAuthConfigured(config) {
|
||||||
HandleError(errors.New("no users or OAuth configured"), "No users or OAuth configured")
|
HandleError(errors.New("no users or OAuth configured"), "No users or OAuth configured")
|
||||||
@@ -66,8 +67,15 @@ var rootCmd = &cobra.Command{
|
|||||||
oauthWhitelist := utils.Filter(strings.Split(config.OAuthWhitelist, ","), func(val string) bool {
|
oauthWhitelist := utils.Filter(strings.Split(config.OAuthWhitelist, ","), func(val string) bool {
|
||||||
return val != ""
|
return val != ""
|
||||||
})
|
})
|
||||||
|
|
||||||
log.Debug().Msg("Parsed OAuth whitelist")
|
log.Debug().Msg("Parsed OAuth whitelist")
|
||||||
|
|
||||||
|
// Get domain
|
||||||
|
log.Debug().Msg("Getting domain")
|
||||||
|
domain, err := utils.GetUpperDomain(config.AppURL)
|
||||||
|
HandleError(err, "Failed to get upper domain")
|
||||||
|
log.Info().Str("domain", domain).Msg("Using domain for cookie store")
|
||||||
|
|
||||||
// Create OAuth config
|
// Create OAuth config
|
||||||
oauthConfig := types.OAuthConfig{
|
oauthConfig := types.OAuthConfig{
|
||||||
GithubClientId: config.GithubClientId,
|
GithubClientId: config.GithubClientId,
|
||||||
@@ -85,14 +93,32 @@ var rootCmd = &cobra.Command{
|
|||||||
AppURL: config.AppURL,
|
AppURL: config.AppURL,
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Parsed OAuth config")
|
// Create handlers config
|
||||||
|
serverConfig := types.HandlersConfig{
|
||||||
|
AppURL: config.AppURL,
|
||||||
|
Domain: fmt.Sprintf(".%s", domain),
|
||||||
|
CookieSecure: config.CookieSecure,
|
||||||
|
DisableContinue: config.DisableContinue,
|
||||||
|
Title: config.Title,
|
||||||
|
GenericName: config.GenericName,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create api config
|
||||||
|
apiConfig := types.APIConfig{
|
||||||
|
Port: config.Port,
|
||||||
|
Address: config.Address,
|
||||||
|
Secret: config.Secret,
|
||||||
|
CookieSecure: config.CookieSecure,
|
||||||
|
SessionExpiry: config.SessionExpiry,
|
||||||
|
Domain: domain,
|
||||||
|
}
|
||||||
|
|
||||||
// Create docker service
|
// Create docker service
|
||||||
docker := docker.NewDocker()
|
docker := docker.NewDocker()
|
||||||
|
|
||||||
// Initialize docker
|
// Initialize docker
|
||||||
dockerErr := docker.Init()
|
err = docker.Init()
|
||||||
HandleError(dockerErr, "Failed to initialize docker")
|
HandleError(err, "Failed to initialize docker")
|
||||||
|
|
||||||
// Create auth service
|
// Create auth service
|
||||||
auth := auth.NewAuth(docker, users, oauthWhitelist, config.SessionExpiry)
|
auth := auth.NewAuth(docker, users, oauthWhitelist, config.SessionExpiry)
|
||||||
@@ -106,18 +132,11 @@ var rootCmd = &cobra.Command{
|
|||||||
// Create hooks service
|
// Create hooks service
|
||||||
hooks := hooks.NewHooks(auth, providers)
|
hooks := hooks.NewHooks(auth, providers)
|
||||||
|
|
||||||
|
// Create handlers
|
||||||
|
handlers := handlers.NewHandlers(serverConfig, auth, hooks, providers)
|
||||||
|
|
||||||
// Create API
|
// Create API
|
||||||
api := api.NewAPI(types.APIConfig{
|
api := api.NewAPI(apiConfig, handlers)
|
||||||
Port: config.Port,
|
|
||||||
Address: config.Address,
|
|
||||||
Secret: config.Secret,
|
|
||||||
AppURL: config.AppURL,
|
|
||||||
CookieSecure: config.CookieSecure,
|
|
||||||
DisableContinue: config.DisableContinue,
|
|
||||||
SessionExpiry: config.SessionExpiry,
|
|
||||||
Title: config.Title,
|
|
||||||
GenericName: config.GenericName,
|
|
||||||
}, hooks, auth, providers)
|
|
||||||
|
|
||||||
// Setup routes
|
// Setup routes
|
||||||
api.Init()
|
api.Init()
|
||||||
@@ -134,7 +153,7 @@ func Execute() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func HandleError(err error, msg string) {
|
func HandleError(err error, msg string) {
|
||||||
// If error log it and exit
|
// If error, log it and exit
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err).Msg(msg)
|
log.Fatal().Err(err).Msg(msg)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
// Interactive flag
|
// Interactive flag
|
||||||
var interactive bool
|
var interactive bool
|
||||||
|
|
||||||
// i stands for input
|
// Input user
|
||||||
var iUser string
|
var iUser string
|
||||||
|
|
||||||
var GenerateCmd = &cobra.Command{
|
var GenerateCmd = &cobra.Command{
|
||||||
@@ -46,18 +46,18 @@ var GenerateCmd = &cobra.Command{
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Run form
|
// Run form
|
||||||
formErr := form.WithTheme(baseTheme).Run()
|
err := form.WithTheme(baseTheme).Run()
|
||||||
|
|
||||||
if formErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(formErr).Msg("Form failed")
|
log.Fatal().Err(err).Msg("Form failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse user
|
// Parse user
|
||||||
user, parseErr := utils.ParseUser(iUser)
|
user, err := utils.ParseUser(iUser)
|
||||||
|
|
||||||
if parseErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(parseErr).Msg("Failed to parse user")
|
log.Fatal().Err(err).Msg("Failed to parse user")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user was using docker escape
|
// Check if user was using docker escape
|
||||||
@@ -73,13 +73,13 @@ var GenerateCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generate totp secret
|
// Generate totp secret
|
||||||
key, keyErr := totp.Generate(totp.GenerateOpts{
|
key, err := totp.Generate(totp.GenerateOpts{
|
||||||
Issuer: "Tinyauth",
|
Issuer: "Tinyauth",
|
||||||
AccountName: user.Username,
|
AccountName: user.Username,
|
||||||
})
|
})
|
||||||
|
|
||||||
if keyErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(keyErr).Msg("Failed to generate totp secret")
|
log.Fatal().Err(err).Msg("Failed to generate totp secret")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create secret
|
// Create secret
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Interactive flag
|
||||||
var interactive bool
|
var interactive bool
|
||||||
|
|
||||||
|
// Docker flag
|
||||||
var docker bool
|
var docker bool
|
||||||
|
|
||||||
// i stands for input
|
// i stands for input
|
||||||
@@ -51,10 +54,10 @@ var CreateCmd = &cobra.Command{
|
|||||||
// Use simple theme
|
// Use simple theme
|
||||||
var baseTheme *huh.Theme = huh.ThemeBase()
|
var baseTheme *huh.Theme = huh.ThemeBase()
|
||||||
|
|
||||||
formErr := form.WithTheme(baseTheme).Run()
|
err := form.WithTheme(baseTheme).Run()
|
||||||
|
|
||||||
if formErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(formErr).Msg("Form failed")
|
log.Fatal().Err(err).Msg("Form failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,10 +69,10 @@ var CreateCmd = &cobra.Command{
|
|||||||
log.Info().Str("username", iUsername).Str("password", iPassword).Bool("docker", docker).Msg("Creating user")
|
log.Info().Str("username", iUsername).Str("password", iPassword).Bool("docker", docker).Msg("Creating user")
|
||||||
|
|
||||||
// Hash password
|
// Hash password
|
||||||
password, passwordErr := bcrypt.GenerateFromPassword([]byte(iPassword), bcrypt.DefaultCost)
|
password, err := bcrypt.GenerateFromPassword([]byte(iPassword), bcrypt.DefaultCost)
|
||||||
|
|
||||||
if passwordErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(passwordErr).Msg("Failed to hash password")
|
log.Fatal().Err(err).Msg("Failed to hash password")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert password to string
|
// Convert password to string
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Interactive flag
|
||||||
var interactive bool
|
var interactive bool
|
||||||
|
|
||||||
|
// Docker flag
|
||||||
var docker bool
|
var docker bool
|
||||||
|
|
||||||
// i stands for input
|
// i stands for input
|
||||||
@@ -60,18 +63,18 @@ var VerifyCmd = &cobra.Command{
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Run form
|
// Run form
|
||||||
formErr := form.WithTheme(baseTheme).Run()
|
err := form.WithTheme(baseTheme).Run()
|
||||||
|
|
||||||
if formErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(formErr).Msg("Form failed")
|
log.Fatal().Err(err).Msg("Form failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse user
|
// Parse user
|
||||||
user, userErr := utils.ParseUser(iUser)
|
user, err := utils.ParseUser(iUser)
|
||||||
|
|
||||||
if userErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(userErr).Msg("Failed to parse user")
|
log.Fatal().Err(err).Msg("Failed to parse user")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compare username
|
// Compare username
|
||||||
@@ -80,9 +83,9 @@ var VerifyCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Compare password
|
// Compare password
|
||||||
verifyErr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(iPassword))
|
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(iPassword))
|
||||||
|
|
||||||
if verifyErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Msg("Ppassword is incorrect")
|
log.Fatal().Msg("Ppassword is incorrect")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,9 +99,9 @@ var VerifyCmd = &cobra.Command{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check totp code
|
// Check totp code
|
||||||
totpOk := totp.Validate(iTotp, user.TotpSecret)
|
ok := totp.Validate(iTotp, user.TotpSecret)
|
||||||
|
|
||||||
if !totpOk {
|
if !ok {
|
||||||
log.Fatal().Msg("Totp code incorrect")
|
log.Fatal().Msg("Totp code incorrect")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,42 +3,30 @@ package api
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"math/rand/v2"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"tinyauth/internal/assets"
|
"tinyauth/internal/assets"
|
||||||
"tinyauth/internal/auth"
|
"tinyauth/internal/handlers"
|
||||||
"tinyauth/internal/hooks"
|
|
||||||
"tinyauth/internal/providers"
|
|
||||||
"tinyauth/internal/types"
|
"tinyauth/internal/types"
|
||||||
"tinyauth/internal/utils"
|
|
||||||
|
|
||||||
"github.com/gin-contrib/sessions"
|
"github.com/gin-contrib/sessions"
|
||||||
"github.com/gin-contrib/sessions/cookie"
|
"github.com/gin-contrib/sessions/cookie"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/go-querystring/query"
|
|
||||||
"github.com/pquerna/otp/totp"
|
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewAPI(config types.APIConfig, hooks *hooks.Hooks, auth *auth.Auth, providers *providers.Providers) *API {
|
func NewAPI(config types.APIConfig, handlers *handlers.Handlers) *API {
|
||||||
return &API{
|
return &API{
|
||||||
Config: config,
|
Config: config,
|
||||||
Hooks: hooks,
|
Handlers: handlers,
|
||||||
Auth: auth,
|
|
||||||
Providers: providers,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type API struct {
|
type API struct {
|
||||||
Config types.APIConfig
|
Config types.APIConfig
|
||||||
Router *gin.Engine
|
Router *gin.Engine
|
||||||
Hooks *hooks.Hooks
|
Handlers *handlers.Handlers
|
||||||
Auth *auth.Auth
|
|
||||||
Providers *providers.Providers
|
|
||||||
Domain string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (api *API) Init() {
|
func (api *API) Init() {
|
||||||
@@ -52,10 +40,10 @@ func (api *API) Init() {
|
|||||||
|
|
||||||
// Read UI assets
|
// Read UI assets
|
||||||
log.Debug().Msg("Setting up assets")
|
log.Debug().Msg("Setting up assets")
|
||||||
dist, distErr := fs.Sub(assets.Assets, "dist")
|
dist, err := fs.Sub(assets.Assets, "dist")
|
||||||
|
|
||||||
if distErr != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(distErr).Msg("Failed to get UI assets")
|
log.Fatal().Err(err).Msg("Failed to get UI assets")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create file server
|
// Create file server
|
||||||
@@ -66,22 +54,9 @@ func (api *API) Init() {
|
|||||||
log.Debug().Msg("Setting up cookie store")
|
log.Debug().Msg("Setting up cookie store")
|
||||||
store := cookie.NewStore([]byte(api.Config.Secret))
|
store := cookie.NewStore([]byte(api.Config.Secret))
|
||||||
|
|
||||||
// Get domain to use for session cookies
|
|
||||||
log.Debug().Msg("Getting domain")
|
|
||||||
domain, domainErr := utils.GetRootURL(api.Config.AppURL)
|
|
||||||
|
|
||||||
if domainErr != nil {
|
|
||||||
log.Fatal().Err(domainErr).Msg("Failed to get domain")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info().Str("domain", domain).Msg("Using domain for cookies")
|
|
||||||
|
|
||||||
api.Domain = fmt.Sprintf(".%s", domain)
|
|
||||||
|
|
||||||
// Use session middleware
|
// Use session middleware
|
||||||
store.Options(sessions.Options{
|
store.Options(sessions.Options{
|
||||||
Domain: api.Domain,
|
Domain: api.Config.Domain,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: api.Config.CookieSecure,
|
Secure: api.Config.CookieSecure,
|
||||||
@@ -94,17 +69,7 @@ func (api *API) Init() {
|
|||||||
router.Use(func(c *gin.Context) {
|
router.Use(func(c *gin.Context) {
|
||||||
// If not an API request, serve the UI
|
// If not an API request, serve the UI
|
||||||
if !strings.HasPrefix(c.Request.URL.Path, "/api") {
|
if !strings.HasPrefix(c.Request.URL.Path, "/api") {
|
||||||
_, err := fs.Stat(dist, strings.TrimPrefix(c.Request.URL.Path, "/"))
|
|
||||||
|
|
||||||
// If the file doesn't exist, serve the index.html
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
c.Request.URL.Path = "/"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serve the file
|
|
||||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||||
|
|
||||||
// Stop further processing
|
|
||||||
c.Abort()
|
c.Abort()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -114,608 +79,24 @@ func (api *API) Init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (api *API) SetupRoutes() {
|
func (api *API) SetupRoutes() {
|
||||||
api.Router.GET("/api/auth/:proxy", func(c *gin.Context) {
|
// Proxy
|
||||||
// Create struct for proxy
|
api.Router.GET("/api/auth/:proxy", api.Handlers.AuthHandler)
|
||||||
var proxy types.Proxy
|
|
||||||
|
|
||||||
// Bind URI
|
// Auth
|
||||||
bindErr := c.BindUri(&proxy)
|
api.Router.POST("/api/login", api.Handlers.LoginHandler)
|
||||||
|
api.Router.POST("/api/totp", api.Handlers.TotpHandler)
|
||||||
|
api.Router.POST("/api/logout", api.Handlers.LogoutHandler)
|
||||||
|
|
||||||
// Handle error
|
// Context
|
||||||
if bindErr != nil {
|
api.Router.GET("/api/app", api.Handlers.AppHandler)
|
||||||
log.Error().Err(bindErr).Msg("Failed to bind URI")
|
api.Router.GET("/api/user", api.Handlers.UserHandler)
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"status": 400,
|
|
||||||
"message": "Bad Request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the request is coming from a browser (tools like curl/bruno use */* and they don't include the text/html)
|
// OAuth
|
||||||
isBrowser := strings.Contains(c.Request.Header.Get("Accept"), "text/html")
|
api.Router.GET("/api/oauth/url/:provider", api.Handlers.OauthUrlHandler)
|
||||||
|
api.Router.GET("/api/oauth/callback/:provider", api.Handlers.OauthCallbackHandler)
|
||||||
|
|
||||||
if isBrowser {
|
// App
|
||||||
log.Debug().Msg("Request is most likely coming from a browser")
|
api.Router.GET("/api/healthcheck", api.Handlers.HealthcheckHandler)
|
||||||
} else {
|
|
||||||
log.Debug().Msg("Request is most likely not coming from a browser")
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Interface("proxy", proxy.Proxy).Msg("Got proxy")
|
|
||||||
|
|
||||||
// Check if auth is enabled
|
|
||||||
authEnabled, authEnabledErr := api.Auth.AuthEnabled(c)
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if authEnabledErr != nil {
|
|
||||||
// Return 500 if nginx is the proxy or if the request is not coming from a browser
|
|
||||||
if proxy.Proxy == "nginx" || !isBrowser {
|
|
||||||
log.Error().Err(authEnabledErr).Msg("Failed to check if auth is enabled")
|
|
||||||
c.JSON(500, gin.H{
|
|
||||||
"status": 500,
|
|
||||||
"message": "Internal Server Error",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the internal server error page
|
|
||||||
if api.handleError(c, "Failed to check if auth is enabled", authEnabledErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If auth is not enabled, return 200
|
|
||||||
if !authEnabled {
|
|
||||||
// The user is allowed to access the app
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Authenticated",
|
|
||||||
})
|
|
||||||
|
|
||||||
// Stop further processing
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get user context
|
|
||||||
userContext := api.Hooks.UseUserContext(c)
|
|
||||||
|
|
||||||
// Get headers
|
|
||||||
uri := c.Request.Header.Get("X-Forwarded-Uri")
|
|
||||||
proto := c.Request.Header.Get("X-Forwarded-Proto")
|
|
||||||
host := c.Request.Header.Get("X-Forwarded-Host")
|
|
||||||
|
|
||||||
// Check if user is logged in
|
|
||||||
if userContext.IsLoggedIn {
|
|
||||||
log.Debug().Msg("Authenticated")
|
|
||||||
|
|
||||||
// Check if user is allowed to access subdomain, if request is nginx.example.com the subdomain (resource) is nginx
|
|
||||||
appAllowed, appAllowedErr := api.Auth.ResourceAllowed(c, userContext)
|
|
||||||
|
|
||||||
// Check if there was an error
|
|
||||||
if appAllowedErr != nil {
|
|
||||||
// Return 500 if nginx is the proxy or if the request is not coming from a browser
|
|
||||||
if proxy.Proxy == "nginx" || !isBrowser {
|
|
||||||
log.Error().Err(appAllowedErr).Msg("Failed to check if app is allowed")
|
|
||||||
c.JSON(500, gin.H{
|
|
||||||
"status": 500,
|
|
||||||
"message": "Internal Server Error",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the internal server error page
|
|
||||||
if api.handleError(c, "Failed to check if app is allowed", appAllowedErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Bool("appAllowed", appAllowed).Msg("Checking if app is allowed")
|
|
||||||
|
|
||||||
// The user is not allowed to access the app
|
|
||||||
if !appAllowed {
|
|
||||||
log.Warn().Str("username", userContext.Username).Str("host", host).Msg("User not allowed")
|
|
||||||
|
|
||||||
// Set WWW-Authenticate header
|
|
||||||
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
|
||||||
|
|
||||||
// Return 401 if nginx is the proxy or if the request is not coming from a browser
|
|
||||||
if proxy.Proxy == "nginx" || !isBrowser {
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build query
|
|
||||||
queries, queryErr := query.Values(types.UnauthorizedQuery{
|
|
||||||
Username: userContext.Username,
|
|
||||||
Resource: strings.Split(host, ".")[0],
|
|
||||||
})
|
|
||||||
|
|
||||||
// Handle error (no need to check for nginx/headers since we are sure we are using caddy/traefik)
|
|
||||||
if api.handleError(c, "Failed to build query", queryErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// We are using caddy/traefik so redirect
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", api.Config.AppURL, queries.Encode()))
|
|
||||||
|
|
||||||
// Stop further processing
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the user header
|
|
||||||
c.Header("Remote-User", userContext.Username)
|
|
||||||
|
|
||||||
// The user is allowed to access the app
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Authenticated",
|
|
||||||
})
|
|
||||||
|
|
||||||
// Stop further processing
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// The user is not logged in
|
|
||||||
log.Debug().Msg("Unauthorized")
|
|
||||||
|
|
||||||
// Set www-authenticate header
|
|
||||||
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
|
||||||
|
|
||||||
// Return 401 if nginx is the proxy or if the request is not coming from a browser
|
|
||||||
if proxy.Proxy == "nginx" || !isBrowser {
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build query
|
|
||||||
queries, queryErr := query.Values(types.LoginQuery{
|
|
||||||
RedirectURI: fmt.Sprintf("%s://%s%s", proto, host, uri),
|
|
||||||
})
|
|
||||||
|
|
||||||
// Handle error (no need to check for nginx/headers since we are sure we are using caddy/traefik)
|
|
||||||
if api.handleError(c, "Failed to build query", queryErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Interface("redirect_uri", fmt.Sprintf("%s://%s%s", proto, host, uri)).Msg("Redirecting to login")
|
|
||||||
|
|
||||||
// Redirect to login
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/?%s", api.Config.AppURL, queries.Encode()))
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.POST("/api/login", func(c *gin.Context) {
|
|
||||||
// Create login struct
|
|
||||||
var login types.LoginRequest
|
|
||||||
|
|
||||||
// Bind JSON
|
|
||||||
err := c.BindJSON(&login)
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if err != nil {
|
|
||||||
log.Error().Err(err).Msg("Failed to bind JSON")
|
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"status": 400,
|
|
||||||
"message": "Bad Request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Got login request")
|
|
||||||
|
|
||||||
// Get user based on username
|
|
||||||
user := api.Auth.GetUser(login.Username)
|
|
||||||
|
|
||||||
// User does not exist
|
|
||||||
if user == nil {
|
|
||||||
log.Debug().Str("username", login.Username).Msg("User not found")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Got user")
|
|
||||||
|
|
||||||
// Check if password is correct
|
|
||||||
if !api.Auth.CheckPassword(*user, login.Password) {
|
|
||||||
log.Debug().Str("username", login.Username).Msg("Password incorrect")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Password correct, checking totp")
|
|
||||||
|
|
||||||
// Check if user has totp enabled
|
|
||||||
if user.TotpSecret != "" {
|
|
||||||
log.Debug().Msg("Totp enabled")
|
|
||||||
|
|
||||||
// Set totp pending cookie
|
|
||||||
api.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
|
||||||
Username: login.Username,
|
|
||||||
Provider: "username",
|
|
||||||
TotpPending: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Return totp required
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Waiting for totp",
|
|
||||||
"totpPending": true,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Stop further processing
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create session cookie with username as provider
|
|
||||||
api.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
|
||||||
Username: login.Username,
|
|
||||||
Provider: "username",
|
|
||||||
})
|
|
||||||
|
|
||||||
// Return logged in
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Logged in",
|
|
||||||
"totpPending": false,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.POST("/api/totp", func(c *gin.Context) {
|
|
||||||
// Create totp struct
|
|
||||||
var totpReq types.TotpRequest
|
|
||||||
|
|
||||||
// Bind JSON
|
|
||||||
err := c.BindJSON(&totpReq)
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if err != nil {
|
|
||||||
log.Error().Err(err).Msg("Failed to bind JSON")
|
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"status": 400,
|
|
||||||
"message": "Bad Request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Checking totp")
|
|
||||||
|
|
||||||
// Get user context
|
|
||||||
userContext := api.Hooks.UseUserContext(c)
|
|
||||||
|
|
||||||
// Check if we have a user
|
|
||||||
if userContext.Username == "" {
|
|
||||||
log.Debug().Msg("No user context")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get user
|
|
||||||
user := api.Auth.GetUser(userContext.Username)
|
|
||||||
|
|
||||||
// Check if user exists
|
|
||||||
if user == nil {
|
|
||||||
log.Debug().Msg("User not found")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if totp is correct
|
|
||||||
totpOk := totp.Validate(totpReq.Code, user.TotpSecret)
|
|
||||||
|
|
||||||
// TOTP is incorrect
|
|
||||||
if !totpOk {
|
|
||||||
log.Debug().Msg("Totp incorrect")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"status": 401,
|
|
||||||
"message": "Unauthorized",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Totp correct")
|
|
||||||
|
|
||||||
// Create session cookie with username as provider
|
|
||||||
api.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
|
||||||
Username: user.Username,
|
|
||||||
Provider: "username",
|
|
||||||
})
|
|
||||||
|
|
||||||
// Return logged in
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Logged in",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.POST("/api/logout", func(c *gin.Context) {
|
|
||||||
log.Debug().Msg("Logging out")
|
|
||||||
|
|
||||||
// Delete session cookie
|
|
||||||
api.Auth.DeleteSessionCookie(c)
|
|
||||||
|
|
||||||
log.Debug().Msg("Cleaning up redirect cookie")
|
|
||||||
|
|
||||||
// Clean up redirect cookie if it exists
|
|
||||||
c.SetCookie("tinyauth_redirect_uri", "", -1, "/", api.Domain, api.Config.CookieSecure, true)
|
|
||||||
|
|
||||||
// Return logged out
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Logged out",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.GET("/api/app", func(c *gin.Context) {
|
|
||||||
log.Debug().Msg("Getting app context")
|
|
||||||
|
|
||||||
// Get configured providers
|
|
||||||
configuredProviders := api.Providers.GetConfiguredProviders()
|
|
||||||
|
|
||||||
// We have username/password configured so add it to our providers
|
|
||||||
if api.Auth.UserAuthConfigured() {
|
|
||||||
configuredProviders = append(configuredProviders, "username")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create app context struct
|
|
||||||
appContext := types.AppContext{
|
|
||||||
Status: 200,
|
|
||||||
Message: "Ok",
|
|
||||||
ConfiguredProviders: configuredProviders,
|
|
||||||
DisableContinue: api.Config.DisableContinue,
|
|
||||||
Title: api.Config.Title,
|
|
||||||
GenericName: api.Config.GenericName,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return app context
|
|
||||||
c.JSON(200, appContext)
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.GET("/api/user", func(c *gin.Context) {
|
|
||||||
log.Debug().Msg("Getting user context")
|
|
||||||
|
|
||||||
// Get user context
|
|
||||||
userContext := api.Hooks.UseUserContext(c)
|
|
||||||
|
|
||||||
// Create user context response
|
|
||||||
userContextResponse := types.UserContextResponse{
|
|
||||||
Status: 200,
|
|
||||||
IsLoggedIn: userContext.IsLoggedIn,
|
|
||||||
Username: userContext.Username,
|
|
||||||
Provider: userContext.Provider,
|
|
||||||
Oauth: userContext.OAuth,
|
|
||||||
TotpPending: userContext.TotpPending,
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we are not logged in we set the status to 401 and add the WWW-Authenticate header else we set it to 200
|
|
||||||
if !userContext.IsLoggedIn {
|
|
||||||
log.Debug().Msg("Unauthorized")
|
|
||||||
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
|
||||||
userContextResponse.Message = "Unauthorized"
|
|
||||||
} else {
|
|
||||||
log.Debug().Interface("userContext", userContext).Msg("Authenticated")
|
|
||||||
userContextResponse.Message = "Authenticated"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return user context
|
|
||||||
c.JSON(200, userContextResponse)
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.GET("/api/oauth/url/:provider", func(c *gin.Context) {
|
|
||||||
// Create struct for OAuth request
|
|
||||||
var request types.OAuthRequest
|
|
||||||
|
|
||||||
// Bind URI
|
|
||||||
bindErr := c.BindUri(&request)
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if bindErr != nil {
|
|
||||||
log.Error().Err(bindErr).Msg("Failed to bind URI")
|
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"status": 400,
|
|
||||||
"message": "Bad Request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Got OAuth request")
|
|
||||||
|
|
||||||
// Check if provider exists
|
|
||||||
provider := api.Providers.GetProvider(request.Provider)
|
|
||||||
|
|
||||||
// Provider does not exist
|
|
||||||
if provider == nil {
|
|
||||||
c.JSON(404, gin.H{
|
|
||||||
"status": 404,
|
|
||||||
"message": "Not Found",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Str("provider", request.Provider).Msg("Got provider")
|
|
||||||
|
|
||||||
// Get auth URL
|
|
||||||
authURL := provider.GetAuthURL()
|
|
||||||
|
|
||||||
log.Debug().Msg("Got auth URL")
|
|
||||||
|
|
||||||
// Get redirect URI
|
|
||||||
redirectURI := c.Query("redirect_uri")
|
|
||||||
|
|
||||||
// Set redirect cookie if redirect URI is provided
|
|
||||||
if redirectURI != "" {
|
|
||||||
log.Debug().Str("redirectURI", redirectURI).Msg("Setting redirect cookie")
|
|
||||||
c.SetCookie("tinyauth_redirect_uri", redirectURI, 3600, "/", api.Domain, api.Config.CookieSecure, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tailscale does not have an auth url so we create a random code (does not need to be secure) to avoid caching and send it
|
|
||||||
if request.Provider == "tailscale" {
|
|
||||||
// Build tailscale query
|
|
||||||
tailscaleQuery, tailscaleQueryErr := query.Values(types.TailscaleQuery{
|
|
||||||
Code: (1000 + rand.IntN(9000)),
|
|
||||||
})
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if tailscaleQueryErr != nil {
|
|
||||||
log.Error().Err(tailscaleQueryErr).Msg("Failed to build query")
|
|
||||||
c.JSON(500, gin.H{
|
|
||||||
"status": 500,
|
|
||||||
"message": "Internal Server Error",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return tailscale URL (immidiately redirects to the callback)
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Ok",
|
|
||||||
"url": fmt.Sprintf("%s/api/oauth/callback/tailscale?%s", api.Config.AppURL, tailscaleQuery.Encode()),
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return auth URL
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "Ok",
|
|
||||||
"url": authURL,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
api.Router.GET("/api/oauth/callback/:provider", func(c *gin.Context) {
|
|
||||||
// Create struct for OAuth request
|
|
||||||
var providerName types.OAuthRequest
|
|
||||||
|
|
||||||
// Bind URI
|
|
||||||
bindErr := c.BindUri(&providerName)
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if api.handleError(c, "Failed to bind URI", bindErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Interface("provider", providerName.Provider).Msg("Got provider name")
|
|
||||||
|
|
||||||
// Get code
|
|
||||||
code := c.Query("code")
|
|
||||||
|
|
||||||
// Code empty so redirect to error
|
|
||||||
if code == "" {
|
|
||||||
log.Error().Msg("No code provided")
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, "/error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Got code")
|
|
||||||
|
|
||||||
// Get provider
|
|
||||||
provider := api.Providers.GetProvider(providerName.Provider)
|
|
||||||
|
|
||||||
log.Debug().Str("provider", providerName.Provider).Msg("Got provider")
|
|
||||||
|
|
||||||
// Provider does not exist
|
|
||||||
if provider == nil {
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, "/not-found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exchange token (authenticates user)
|
|
||||||
_, tokenErr := provider.ExchangeToken(code)
|
|
||||||
|
|
||||||
log.Debug().Msg("Got token")
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if api.handleError(c, "Failed to exchange token", tokenErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get email
|
|
||||||
email, emailErr := api.Providers.GetUser(providerName.Provider)
|
|
||||||
|
|
||||||
log.Debug().Str("email", email).Msg("Got email")
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if api.handleError(c, "Failed to get user", emailErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Email is not whitelisted
|
|
||||||
if !api.Auth.EmailWhitelisted(email) {
|
|
||||||
log.Warn().Str("email", email).Msg("Email not whitelisted")
|
|
||||||
|
|
||||||
// Build query
|
|
||||||
unauthorizedQuery, unauthorizedQueryErr := query.Values(types.UnauthorizedQuery{
|
|
||||||
Username: email,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if api.handleError(c, "Failed to build query", unauthorizedQueryErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect to unauthorized
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/unauthorized?%s", api.Config.AppURL, unauthorizedQuery.Encode()))
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Msg("Email whitelisted")
|
|
||||||
|
|
||||||
// Create session cookie
|
|
||||||
api.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
|
||||||
Username: email,
|
|
||||||
Provider: providerName.Provider,
|
|
||||||
})
|
|
||||||
|
|
||||||
// Get redirect URI
|
|
||||||
redirectURI, redirectURIErr := c.Cookie("tinyauth_redirect_uri")
|
|
||||||
|
|
||||||
// If it is empty it means that no redirect_uri was provided to the login screen so we just log in
|
|
||||||
if redirectURIErr != nil {
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, api.Config.AppURL)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Debug().Str("redirectURI", redirectURI).Msg("Got redirect URI")
|
|
||||||
|
|
||||||
// Clean up redirect cookie since we already have the value
|
|
||||||
c.SetCookie("tinyauth_redirect_uri", "", -1, "/", api.Domain, api.Config.CookieSecure, true)
|
|
||||||
|
|
||||||
// Build query
|
|
||||||
redirectQuery, redirectQueryErr := query.Values(types.LoginQuery{
|
|
||||||
RedirectURI: redirectURI,
|
|
||||||
})
|
|
||||||
|
|
||||||
log.Debug().Msg("Got redirect query")
|
|
||||||
|
|
||||||
// Handle error
|
|
||||||
if api.handleError(c, "Failed to build query", redirectQueryErr) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Redirect to continue with the redirect URI
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/continue?%s", api.Config.AppURL, redirectQuery.Encode()))
|
|
||||||
})
|
|
||||||
|
|
||||||
// Simple healthcheck
|
|
||||||
api.Router.GET("/api/healthcheck", func(c *gin.Context) {
|
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"status": 200,
|
|
||||||
"message": "OK",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (api *API) Run() {
|
func (api *API) Run() {
|
||||||
@@ -724,23 +105,12 @@ func (api *API) Run() {
|
|||||||
// Run server
|
// Run server
|
||||||
err := api.Router.Run(fmt.Sprintf("%s:%d", api.Config.Address, api.Config.Port))
|
err := api.Router.Run(fmt.Sprintf("%s:%d", api.Config.Address, api.Config.Port))
|
||||||
|
|
||||||
// Check error
|
// Check for errors
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal().Err(err).Msg("Failed to start server")
|
log.Fatal().Err(err).Msg("Failed to start server")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// handleError logs the error and redirects to the error page (only meant for stuff the user may access does not apply for login paths)
|
|
||||||
func (api *API) handleError(c *gin.Context, msg string, err error) bool {
|
|
||||||
// If error is not nil log it and redirect to error page also return true so we can stop further processing
|
|
||||||
if err != nil {
|
|
||||||
log.Error().Err(err).Msg(msg)
|
|
||||||
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", api.Config.AppURL))
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// zerolog is a middleware for gin that logs requests using zerolog
|
// zerolog is a middleware for gin that logs requests using zerolog
|
||||||
func zerolog() gin.HandlerFunc {
|
func zerolog() gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"tinyauth/internal/api"
|
"tinyauth/internal/api"
|
||||||
"tinyauth/internal/auth"
|
"tinyauth/internal/auth"
|
||||||
"tinyauth/internal/docker"
|
"tinyauth/internal/docker"
|
||||||
|
"tinyauth/internal/handlers"
|
||||||
"tinyauth/internal/hooks"
|
"tinyauth/internal/hooks"
|
||||||
"tinyauth/internal/providers"
|
"tinyauth/internal/providers"
|
||||||
"tinyauth/internal/types"
|
"tinyauth/internal/types"
|
||||||
@@ -19,13 +21,21 @@ import (
|
|||||||
|
|
||||||
// Simple API config for tests
|
// Simple API config for tests
|
||||||
var apiConfig = types.APIConfig{
|
var apiConfig = types.APIConfig{
|
||||||
Port: 8080,
|
Port: 8080,
|
||||||
Address: "0.0.0.0",
|
Address: "0.0.0.0",
|
||||||
Secret: "super-secret-api-thing-for-tests", // It is 32 chars long
|
Secret: "super-secret-api-thing-for-tests", // It is 32 chars long
|
||||||
AppURL: "http://tinyauth.localhost",
|
CookieSecure: false,
|
||||||
|
SessionExpiry: 3600,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple handlers config for tests
|
||||||
|
var handlersConfig = types.HandlersConfig{
|
||||||
|
AppURL: "http://localhost:8080",
|
||||||
|
Domain: ".localhost",
|
||||||
CookieSecure: false,
|
CookieSecure: false,
|
||||||
SessionExpiry: 3600,
|
|
||||||
DisableContinue: false,
|
DisableContinue: false,
|
||||||
|
Title: "Tinyauth",
|
||||||
|
GenericName: "Generic",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cookie
|
// Cookie
|
||||||
@@ -43,11 +53,11 @@ func getAPI(t *testing.T) *api.API {
|
|||||||
docker := docker.NewDocker()
|
docker := docker.NewDocker()
|
||||||
|
|
||||||
// Initialize docker
|
// Initialize docker
|
||||||
dockerErr := docker.Init()
|
err := docker.Init()
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if dockerErr != nil {
|
if err != nil {
|
||||||
t.Fatalf("Failed to initialize docker: %v", dockerErr)
|
t.Fatalf("Failed to initialize docker: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create auth service
|
// Create auth service
|
||||||
@@ -67,8 +77,11 @@ func getAPI(t *testing.T) *api.API {
|
|||||||
// Create hooks service
|
// Create hooks service
|
||||||
hooks := hooks.NewHooks(auth, providers)
|
hooks := hooks.NewHooks(auth, providers)
|
||||||
|
|
||||||
|
// Create handlers service
|
||||||
|
handlers := handlers.NewHandlers(handlersConfig, auth, hooks, providers)
|
||||||
|
|
||||||
// Create API
|
// Create API
|
||||||
api := api.NewAPI(apiConfig, hooks, auth, providers)
|
api := api.NewAPI(apiConfig, handlers)
|
||||||
|
|
||||||
// Setup routes
|
// Setup routes
|
||||||
api.Init()
|
api.Init()
|
||||||
@@ -123,6 +136,70 @@ func TestLogin(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Test app context
|
||||||
|
func TestAppContext(t *testing.T) {
|
||||||
|
t.Log("Testing app context")
|
||||||
|
|
||||||
|
// Get API
|
||||||
|
api := getAPI(t)
|
||||||
|
|
||||||
|
// Create recorder
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
|
||||||
|
// Create request
|
||||||
|
req, err := http.NewRequest("GET", "/api/app", nil)
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error creating request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the cookie
|
||||||
|
req.AddCookie(&http.Cookie{
|
||||||
|
Name: "tinyauth",
|
||||||
|
Value: cookie,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Serve the request
|
||||||
|
api.Router.ServeHTTP(recorder, req)
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assert.Equal(t, recorder.Code, http.StatusOK)
|
||||||
|
|
||||||
|
// Read the body of the response
|
||||||
|
body, err := io.ReadAll(recorder.Body)
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error getting body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unmarshal the body into the user struct
|
||||||
|
var app types.AppContext
|
||||||
|
|
||||||
|
err = json.Unmarshal(body, &app)
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Error unmarshalling body: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create tests values
|
||||||
|
expected := types.AppContext{
|
||||||
|
Status: 200,
|
||||||
|
Message: "OK",
|
||||||
|
ConfiguredProviders: []string{"username"},
|
||||||
|
DisableContinue: false,
|
||||||
|
Title: "Tinyauth",
|
||||||
|
GenericName: "Generic",
|
||||||
|
}
|
||||||
|
|
||||||
|
// We should get the username back
|
||||||
|
if !reflect.DeepEqual(app, expected) {
|
||||||
|
t.Fatalf("Expected %v, got %v", expected, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Test user context
|
// Test user context
|
||||||
func TestUserContext(t *testing.T) {
|
func TestUserContext(t *testing.T) {
|
||||||
t.Log("Testing user context")
|
t.Log("Testing user context")
|
||||||
@@ -154,11 +231,11 @@ func TestUserContext(t *testing.T) {
|
|||||||
assert.Equal(t, recorder.Code, http.StatusOK)
|
assert.Equal(t, recorder.Code, http.StatusOK)
|
||||||
|
|
||||||
// Read the body of the response
|
// Read the body of the response
|
||||||
body, bodyErr := io.ReadAll(recorder.Body)
|
body, err := io.ReadAll(recorder.Body)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if bodyErr != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error getting body: %v", bodyErr)
|
t.Fatalf("Error getting body: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unmarshal the body into the user struct
|
// Unmarshal the body into the user struct
|
||||||
@@ -168,11 +245,11 @@ func TestUserContext(t *testing.T) {
|
|||||||
|
|
||||||
var user User
|
var user User
|
||||||
|
|
||||||
jsonErr := json.Unmarshal(body, &user)
|
err = json.Unmarshal(body, &user)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if jsonErr != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error unmarshalling body: %v", jsonErr)
|
t.Fatalf("Error unmarshalling body: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// We should get the username back
|
// We should get the username back
|
||||||
|
|||||||
@@ -160,7 +160,7 @@ func (auth *Auth) ResourceAllowed(c *gin.Context, context types.UserContext) (bo
|
|||||||
appId := strings.Split(host, ".")[0]
|
appId := strings.Split(host, ".")[0]
|
||||||
|
|
||||||
// Check if resource is allowed
|
// Check if resource is allowed
|
||||||
allowed, allowedErr := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
|
allowed, err := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
|
||||||
// If the container has an oauth whitelist, check if the user is in it
|
// If the container has an oauth whitelist, check if the user is in it
|
||||||
if context.OAuth {
|
if context.OAuth {
|
||||||
if len(labels.OAuthWhitelist) == 0 {
|
if len(labels.OAuthWhitelist) == 0 {
|
||||||
@@ -187,9 +187,9 @@ func (auth *Auth) ResourceAllowed(c *gin.Context, context types.UserContext) (bo
|
|||||||
})
|
})
|
||||||
|
|
||||||
// If there is an error, return false
|
// If there is an error, return false
|
||||||
if allowedErr != nil {
|
if err != nil {
|
||||||
log.Error().Err(allowedErr).Msg("Error checking if resource is allowed")
|
log.Error().Err(err).Msg("Error checking if resource is allowed")
|
||||||
return false, allowedErr
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return if the resource is allowed
|
// Return if the resource is allowed
|
||||||
@@ -205,7 +205,7 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
|
|||||||
appId := strings.Split(host, ".")[0]
|
appId := strings.Split(host, ".")[0]
|
||||||
|
|
||||||
// Check if auth is enabled
|
// Check if auth is enabled
|
||||||
enabled, enabledErr := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
|
enabled, err := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
|
||||||
// Check if the allowed label is empty
|
// Check if the allowed label is empty
|
||||||
if labels.Allowed == "" {
|
if labels.Allowed == "" {
|
||||||
// Auth enabled
|
// Auth enabled
|
||||||
@@ -213,12 +213,12 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Compile regex
|
// Compile regex
|
||||||
regex, regexErr := regexp.Compile(labels.Allowed)
|
regex, err := regexp.Compile(labels.Allowed)
|
||||||
|
|
||||||
// If there is an error, invalid regex, auth enabled
|
// If there is an error, invalid regex, auth enabled
|
||||||
if regexErr != nil {
|
if err != nil {
|
||||||
log.Warn().Err(regexErr).Msg("Invalid regex")
|
log.Warn().Err(err).Msg("Invalid regex")
|
||||||
return true, regexErr
|
return true, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the uri matches the regex
|
// Check if the uri matches the regex
|
||||||
@@ -232,9 +232,9 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// If there is an error, auth enabled
|
// If there is an error, auth enabled
|
||||||
if enabledErr != nil {
|
if err != nil {
|
||||||
log.Error().Err(enabledErr).Msg("Error checking if auth is enabled")
|
log.Error().Err(err).Msg("Error checking if auth is enabled")
|
||||||
return true, enabledErr
|
return true, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return enabled, nil
|
return enabled, nil
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type Docker struct {
|
|||||||
|
|
||||||
func (docker *Docker) Init() error {
|
func (docker *Docker) Init() error {
|
||||||
// Create a new docker client
|
// Create a new docker client
|
||||||
apiClient, err := client.NewClientWithOpts(client.FromEnv)
|
client, err := client.NewClientWithOpts(client.FromEnv)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -32,7 +32,7 @@ func (docker *Docker) Init() error {
|
|||||||
|
|
||||||
// Set the context and api client
|
// Set the context and api client
|
||||||
docker.Context = context.Background()
|
docker.Context = context.Background()
|
||||||
docker.Client = apiClient
|
docker.Client = client
|
||||||
|
|
||||||
// Done
|
// Done
|
||||||
return nil
|
return nil
|
||||||
@@ -81,11 +81,11 @@ func (docker *Docker) ContainerAction(appId string, runCheck func(labels appType
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get the containers
|
// Get the containers
|
||||||
containers, containersErr := docker.GetContainers()
|
containers, err := docker.GetContainers()
|
||||||
|
|
||||||
// If there is an error, return false
|
// If there is an error, return false
|
||||||
if containersErr != nil {
|
if err != nil {
|
||||||
return false, containersErr
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got containers")
|
log.Debug().Msg("Got containers")
|
||||||
@@ -93,11 +93,11 @@ func (docker *Docker) ContainerAction(appId string, runCheck func(labels appType
|
|||||||
// Loop through the containers
|
// Loop through the containers
|
||||||
for _, container := range containers {
|
for _, container := range containers {
|
||||||
// Inspect the container
|
// Inspect the container
|
||||||
inspect, inspectErr := docker.InspectContainer(container.ID)
|
inspect, err := docker.InspectContainer(container.ID)
|
||||||
|
|
||||||
// If there is an error, return false
|
// If there is an error, return false
|
||||||
if inspectErr != nil {
|
if err != nil {
|
||||||
return false, inspectErr
|
return false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the container name (for some reason it is /name)
|
// Get the container name (for some reason it is /name)
|
||||||
|
|||||||
634
internal/handlers/handlers.go
Normal file
634
internal/handlers/handlers.go
Normal file
@@ -0,0 +1,634 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math/rand/v2"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"tinyauth/internal/auth"
|
||||||
|
"tinyauth/internal/hooks"
|
||||||
|
"tinyauth/internal/providers"
|
||||||
|
"tinyauth/internal/types"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/go-querystring/query"
|
||||||
|
"github.com/pquerna/otp/totp"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewHandlers(config types.HandlersConfig, auth *auth.Auth, hooks *hooks.Hooks, providers *providers.Providers) *Handlers {
|
||||||
|
return &Handlers{
|
||||||
|
Config: config,
|
||||||
|
Auth: auth,
|
||||||
|
Hooks: hooks,
|
||||||
|
Providers: providers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Handlers struct {
|
||||||
|
Config types.HandlersConfig
|
||||||
|
Auth *auth.Auth
|
||||||
|
Hooks *hooks.Hooks
|
||||||
|
Providers *providers.Providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) AuthHandler(c *gin.Context) {
|
||||||
|
// Create struct for proxy
|
||||||
|
var proxy types.Proxy
|
||||||
|
|
||||||
|
// Bind URI
|
||||||
|
err := c.BindUri(&proxy)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to bind URI")
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"status": 400,
|
||||||
|
"message": "Bad Request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the request is coming from a browser (tools like curl/bruno use */* and they don't include the text/html)
|
||||||
|
isBrowser := strings.Contains(c.Request.Header.Get("Accept"), "text/html")
|
||||||
|
|
||||||
|
if isBrowser {
|
||||||
|
log.Debug().Msg("Request is most likely coming from a browser")
|
||||||
|
} else {
|
||||||
|
log.Debug().Msg("Request is most likely not coming from a browser")
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Interface("proxy", proxy.Proxy).Msg("Got proxy")
|
||||||
|
|
||||||
|
// Check if auth is enabled
|
||||||
|
authEnabled, err := h.Auth.AuthEnabled(c)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to check if auth is enabled")
|
||||||
|
|
||||||
|
if proxy.Proxy == "nginx" || !isBrowser {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"status": 500,
|
||||||
|
"message": "Internal Server Error",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// If auth is not enabled, return 200
|
||||||
|
if !authEnabled {
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Authenticated",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user context
|
||||||
|
userContext := h.Hooks.UseUserContext(c)
|
||||||
|
|
||||||
|
// Get headers
|
||||||
|
uri := c.Request.Header.Get("X-Forwarded-Uri")
|
||||||
|
proto := c.Request.Header.Get("X-Forwarded-Proto")
|
||||||
|
host := c.Request.Header.Get("X-Forwarded-Host")
|
||||||
|
|
||||||
|
// Check if user is logged in
|
||||||
|
if userContext.IsLoggedIn {
|
||||||
|
log.Debug().Msg("Authenticated")
|
||||||
|
|
||||||
|
// Check if user is allowed to access subdomain, if request is nginx.example.com the subdomain (resource) is nginx
|
||||||
|
appAllowed, err := h.Auth.ResourceAllowed(c, userContext)
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to check if app is allowed")
|
||||||
|
|
||||||
|
if proxy.Proxy == "nginx" || !isBrowser {
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"status": 500,
|
||||||
|
"message": "Internal Server Error",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Bool("appAllowed", appAllowed).Msg("Checking if app is allowed")
|
||||||
|
|
||||||
|
// The user is not allowed to access the app
|
||||||
|
if !appAllowed {
|
||||||
|
log.Warn().Str("username", userContext.Username).Str("host", host).Msg("User not allowed")
|
||||||
|
|
||||||
|
// Set WWW-Authenticate header
|
||||||
|
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
||||||
|
|
||||||
|
if proxy.Proxy == "nginx" || !isBrowser {
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build query
|
||||||
|
queries, err := query.Values(types.UnauthorizedQuery{
|
||||||
|
Username: userContext.Username,
|
||||||
|
Resource: strings.Split(host, ".")[0],
|
||||||
|
})
|
||||||
|
|
||||||
|
// Handle error (no need to check for nginx/headers since we are sure we are using caddy/traefik)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to build queries")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// We are using caddy/traefik so redirect
|
||||||
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/unauthorized?%s", h.Config.AppURL, queries.Encode()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the user header
|
||||||
|
c.Header("Remote-User", userContext.Username)
|
||||||
|
|
||||||
|
// The user is allowed to access the app
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Authenticated",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// The user is not logged in
|
||||||
|
log.Debug().Msg("Unauthorized")
|
||||||
|
|
||||||
|
// Set www-authenticate header
|
||||||
|
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
||||||
|
|
||||||
|
if proxy.Proxy == "nginx" || !isBrowser {
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
queries, err := query.Values(types.LoginQuery{
|
||||||
|
RedirectURI: fmt.Sprintf("%s://%s%s", proto, host, uri),
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to build queries")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Interface("redirect_uri", fmt.Sprintf("%s://%s%s", proto, host, uri)).Msg("Redirecting to login")
|
||||||
|
|
||||||
|
// Redirect to login
|
||||||
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/?%s", h.Config.AppURL, queries.Encode()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) LoginHandler(c *gin.Context) {
|
||||||
|
// Create login struct
|
||||||
|
var login types.LoginRequest
|
||||||
|
|
||||||
|
// Bind JSON
|
||||||
|
err := c.BindJSON(&login)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to bind JSON")
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"status": 400,
|
||||||
|
"message": "Bad Request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Got login request")
|
||||||
|
|
||||||
|
// Get user based on username
|
||||||
|
user := h.Auth.GetUser(login.Username)
|
||||||
|
|
||||||
|
// User does not exist
|
||||||
|
if user == nil {
|
||||||
|
log.Debug().Str("username", login.Username).Msg("User not found")
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Got user")
|
||||||
|
|
||||||
|
// Check if password is correct
|
||||||
|
if !h.Auth.CheckPassword(*user, login.Password) {
|
||||||
|
log.Debug().Str("username", login.Username).Msg("Password incorrect")
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Password correct, checking totp")
|
||||||
|
|
||||||
|
// Check if user has totp enabled
|
||||||
|
if user.TotpSecret != "" {
|
||||||
|
log.Debug().Msg("Totp enabled")
|
||||||
|
|
||||||
|
// Set totp pending cookie
|
||||||
|
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
||||||
|
Username: login.Username,
|
||||||
|
Provider: "username",
|
||||||
|
TotpPending: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return totp required
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Waiting for totp",
|
||||||
|
"totpPending": true,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Stop further processing
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create session cookie with username as provider
|
||||||
|
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
||||||
|
Username: login.Username,
|
||||||
|
Provider: "username",
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return logged in
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Logged in",
|
||||||
|
"totpPending": false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) TotpHandler(c *gin.Context) {
|
||||||
|
// Create totp struct
|
||||||
|
var totpReq types.TotpRequest
|
||||||
|
|
||||||
|
// Bind JSON
|
||||||
|
err := c.BindJSON(&totpReq)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to bind JSON")
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"status": 400,
|
||||||
|
"message": "Bad Request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Checking totp")
|
||||||
|
|
||||||
|
// Get user context
|
||||||
|
userContext := h.Hooks.UseUserContext(c)
|
||||||
|
|
||||||
|
// Check if we have a user
|
||||||
|
if userContext.Username == "" {
|
||||||
|
log.Debug().Msg("No user context")
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user
|
||||||
|
user := h.Auth.GetUser(userContext.Username)
|
||||||
|
|
||||||
|
// Check if user exists
|
||||||
|
if user == nil {
|
||||||
|
log.Debug().Msg("User not found")
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if totp is correct
|
||||||
|
ok := totp.Validate(totpReq.Code, user.TotpSecret)
|
||||||
|
|
||||||
|
// TOTP is incorrect
|
||||||
|
if !ok {
|
||||||
|
log.Debug().Msg("Totp incorrect")
|
||||||
|
c.JSON(401, gin.H{
|
||||||
|
"status": 401,
|
||||||
|
"message": "Unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Totp correct")
|
||||||
|
|
||||||
|
// Create session cookie with username as provider
|
||||||
|
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
||||||
|
Username: user.Username,
|
||||||
|
Provider: "username",
|
||||||
|
})
|
||||||
|
|
||||||
|
// Return logged in
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Logged in",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) LogoutHandler(c *gin.Context) {
|
||||||
|
log.Debug().Msg("Logging out")
|
||||||
|
|
||||||
|
// Delete session cookie
|
||||||
|
h.Auth.DeleteSessionCookie(c)
|
||||||
|
|
||||||
|
log.Debug().Msg("Cleaning up redirect cookie")
|
||||||
|
|
||||||
|
// Clean up redirect cookie if it exists
|
||||||
|
c.SetCookie("tinyauth_redirect_uri", "", -1, "/", h.Config.Domain, h.Config.CookieSecure, true)
|
||||||
|
|
||||||
|
// Return logged out
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "Logged out",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) AppHandler(c *gin.Context) {
|
||||||
|
log.Debug().Msg("Getting app context")
|
||||||
|
|
||||||
|
// Get configured providers
|
||||||
|
configuredProviders := h.Providers.GetConfiguredProviders()
|
||||||
|
|
||||||
|
// We have username/password configured so add it to our providers
|
||||||
|
if h.Auth.UserAuthConfigured() {
|
||||||
|
configuredProviders = append(configuredProviders, "username")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create app context struct
|
||||||
|
appContext := types.AppContext{
|
||||||
|
Status: 200,
|
||||||
|
Message: "OK",
|
||||||
|
ConfiguredProviders: configuredProviders,
|
||||||
|
DisableContinue: h.Config.DisableContinue,
|
||||||
|
Title: h.Config.Title,
|
||||||
|
GenericName: h.Config.GenericName,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return app context
|
||||||
|
c.JSON(200, appContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) UserHandler(c *gin.Context) {
|
||||||
|
log.Debug().Msg("Getting user context")
|
||||||
|
|
||||||
|
// Get user context
|
||||||
|
userContext := h.Hooks.UseUserContext(c)
|
||||||
|
|
||||||
|
// Create user context response
|
||||||
|
userContextResponse := types.UserContextResponse{
|
||||||
|
Status: 200,
|
||||||
|
IsLoggedIn: userContext.IsLoggedIn,
|
||||||
|
Username: userContext.Username,
|
||||||
|
Provider: userContext.Provider,
|
||||||
|
Oauth: userContext.OAuth,
|
||||||
|
TotpPending: userContext.TotpPending,
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we are not logged in we set the status to 401 and add the WWW-Authenticate header else we set it to 200
|
||||||
|
if !userContext.IsLoggedIn {
|
||||||
|
log.Debug().Msg("Unauthorized")
|
||||||
|
c.Header("WWW-Authenticate", "Basic realm=\"tinyauth\"")
|
||||||
|
userContextResponse.Message = "Unauthorized"
|
||||||
|
} else {
|
||||||
|
log.Debug().Interface("userContext", userContext).Msg("Authenticated")
|
||||||
|
userContextResponse.Message = "Authenticated"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return user context
|
||||||
|
c.JSON(200, userContextResponse)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) OauthUrlHandler(c *gin.Context) {
|
||||||
|
// Create struct for OAuth request
|
||||||
|
var request types.OAuthRequest
|
||||||
|
|
||||||
|
// Bind URI
|
||||||
|
err := c.BindUri(&request)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to bind URI")
|
||||||
|
c.JSON(400, gin.H{
|
||||||
|
"status": 400,
|
||||||
|
"message": "Bad Request",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Got OAuth request")
|
||||||
|
|
||||||
|
// Check if provider exists
|
||||||
|
provider := h.Providers.GetProvider(request.Provider)
|
||||||
|
|
||||||
|
// Provider does not exist
|
||||||
|
if provider == nil {
|
||||||
|
c.JSON(404, gin.H{
|
||||||
|
"status": 404,
|
||||||
|
"message": "Not Found",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Str("provider", request.Provider).Msg("Got provider")
|
||||||
|
|
||||||
|
// Get auth URL
|
||||||
|
authURL := provider.GetAuthURL()
|
||||||
|
|
||||||
|
log.Debug().Msg("Got auth URL")
|
||||||
|
|
||||||
|
// Get redirect URI
|
||||||
|
redirectURI := c.Query("redirect_uri")
|
||||||
|
|
||||||
|
// Set redirect cookie if redirect URI is provided
|
||||||
|
if redirectURI != "" {
|
||||||
|
log.Debug().Str("redirectURI", redirectURI).Msg("Setting redirect cookie")
|
||||||
|
c.SetCookie("tinyauth_redirect_uri", redirectURI, 3600, "/", h.Config.Domain, h.Config.CookieSecure, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tailscale does not have an auth url so we create a random code (does not need to be secure) to avoid caching and send it
|
||||||
|
if request.Provider == "tailscale" {
|
||||||
|
// Build tailscale query
|
||||||
|
queries, err := query.Values(types.TailscaleQuery{
|
||||||
|
Code: (1000 + rand.IntN(9000)),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to build queries")
|
||||||
|
c.JSON(500, gin.H{
|
||||||
|
"status": 500,
|
||||||
|
"message": "Internal Server Error",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return tailscale URL (immidiately redirects to the callback)
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "OK",
|
||||||
|
"url": fmt.Sprintf("%s/api/oauth/callback/tailscale?%s", h.Config.AppURL, queries.Encode()),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return auth URL
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "OK",
|
||||||
|
"url": authURL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) OauthCallbackHandler(c *gin.Context) {
|
||||||
|
// Create struct for OAuth request
|
||||||
|
var providerName types.OAuthRequest
|
||||||
|
|
||||||
|
// Bind URI
|
||||||
|
err := c.BindUri(&providerName)
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to bind URI")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Interface("provider", providerName.Provider).Msg("Got provider name")
|
||||||
|
|
||||||
|
// Get code
|
||||||
|
code := c.Query("code")
|
||||||
|
|
||||||
|
// Code empty so redirect to error
|
||||||
|
if code == "" {
|
||||||
|
log.Error().Msg("No code provided")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Got code")
|
||||||
|
|
||||||
|
// Get provider
|
||||||
|
provider := h.Providers.GetProvider(providerName.Provider)
|
||||||
|
|
||||||
|
log.Debug().Str("provider", providerName.Provider).Msg("Got provider")
|
||||||
|
|
||||||
|
// Provider does not exist
|
||||||
|
if provider == nil {
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, "/not-found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange token (authenticates user)
|
||||||
|
_, err = provider.ExchangeToken(code)
|
||||||
|
|
||||||
|
log.Debug().Msg("Got token")
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Msg("Failed to exchange token")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get email
|
||||||
|
email, err := h.Providers.GetUser(providerName.Provider)
|
||||||
|
|
||||||
|
log.Debug().Str("email", email).Msg("Got email")
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Msg("Failed to get email")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Email is not whitelisted
|
||||||
|
if !h.Auth.EmailWhitelisted(email) {
|
||||||
|
log.Warn().Str("email", email).Msg("Email not whitelisted")
|
||||||
|
|
||||||
|
// Build query
|
||||||
|
queries, err := query.Values(types.UnauthorizedQuery{
|
||||||
|
Username: email,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Msg("Failed to build queries")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to unauthorized
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/unauthorized?%s", h.Config.AppURL, queries.Encode()))
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Email whitelisted")
|
||||||
|
|
||||||
|
// Create session cookie
|
||||||
|
h.Auth.CreateSessionCookie(c, &types.SessionCookie{
|
||||||
|
Username: email,
|
||||||
|
Provider: providerName.Provider,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get redirect URI
|
||||||
|
redirectURI, err := c.Cookie("tinyauth_redirect_uri")
|
||||||
|
|
||||||
|
// If it is empty it means that no redirect_uri was provided to the login screen so we just log in
|
||||||
|
if err != nil {
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, h.Config.AppURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Str("redirectURI", redirectURI).Msg("Got redirect URI")
|
||||||
|
|
||||||
|
// Clean up redirect cookie since we already have the value
|
||||||
|
c.SetCookie("tinyauth_redirect_uri", "", -1, "/", h.Config.Domain, h.Config.CookieSecure, true)
|
||||||
|
|
||||||
|
// Build query
|
||||||
|
queries, err := query.Values(types.LoginQuery{
|
||||||
|
RedirectURI: redirectURI,
|
||||||
|
})
|
||||||
|
|
||||||
|
log.Debug().Msg("Got redirect query")
|
||||||
|
|
||||||
|
// Handle error
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Msg("Failed to build queries")
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to continue with the redirect URI
|
||||||
|
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/continue?%s", h.Config.AppURL, queries.Encode()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handlers) HealthcheckHandler(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"status": 200,
|
||||||
|
"message": "OK",
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -15,21 +15,21 @@ type GenericUserInfoResponse struct {
|
|||||||
|
|
||||||
func GetGenericEmail(client *http.Client, url string) (string, error) {
|
func GetGenericEmail(client *http.Client, url string) (string, error) {
|
||||||
// Using the oauth client get the user info url
|
// Using the oauth client get the user info url
|
||||||
res, resErr := client.Get(url)
|
res, err := client.Get(url)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if resErr != nil {
|
if err != nil {
|
||||||
return "", resErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got response from generic provider")
|
log.Debug().Msg("Got response from generic provider")
|
||||||
|
|
||||||
// Read the body of the response
|
// Read the body of the response
|
||||||
body, bodyErr := io.ReadAll(res.Body)
|
body, err := io.ReadAll(res.Body)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if bodyErr != nil {
|
if err != nil {
|
||||||
return "", bodyErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Read body from generic provider")
|
log.Debug().Msg("Read body from generic provider")
|
||||||
@@ -38,11 +38,11 @@ func GetGenericEmail(client *http.Client, url string) (string, error) {
|
|||||||
var user GenericUserInfoResponse
|
var user GenericUserInfoResponse
|
||||||
|
|
||||||
// Unmarshal the body into the user struct
|
// Unmarshal the body into the user struct
|
||||||
jsonErr := json.Unmarshal(body, &user)
|
err = json.Unmarshal(body, &user)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if jsonErr != nil {
|
if err != nil {
|
||||||
return "", jsonErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Parsed user from generic provider")
|
log.Debug().Msg("Parsed user from generic provider")
|
||||||
|
|||||||
@@ -22,21 +22,21 @@ func GithubScopes() []string {
|
|||||||
|
|
||||||
func GetGithubEmail(client *http.Client) (string, error) {
|
func GetGithubEmail(client *http.Client) (string, error) {
|
||||||
// Get the user emails from github using the oauth http client
|
// Get the user emails from github using the oauth http client
|
||||||
res, resErr := client.Get("https://api.github.com/user/emails")
|
res, err := client.Get("https://api.github.com/user/emails")
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if resErr != nil {
|
if err != nil {
|
||||||
return "", resErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got response from github")
|
log.Debug().Msg("Got response from github")
|
||||||
|
|
||||||
// Read the body of the response
|
// Read the body of the response
|
||||||
body, bodyErr := io.ReadAll(res.Body)
|
body, err := io.ReadAll(res.Body)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if bodyErr != nil {
|
if err != nil {
|
||||||
return "", bodyErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Read body from github")
|
log.Debug().Msg("Read body from github")
|
||||||
@@ -45,11 +45,11 @@ func GetGithubEmail(client *http.Client) (string, error) {
|
|||||||
var emails GithubUserInfoResponse
|
var emails GithubUserInfoResponse
|
||||||
|
|
||||||
// Unmarshal the body into the user struct
|
// Unmarshal the body into the user struct
|
||||||
jsonErr := json.Unmarshal(body, &emails)
|
err = json.Unmarshal(body, &emails)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if jsonErr != nil {
|
if err != nil {
|
||||||
return "", jsonErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Parsed emails from github")
|
log.Debug().Msg("Parsed emails from github")
|
||||||
|
|||||||
@@ -20,21 +20,21 @@ func GoogleScopes() []string {
|
|||||||
|
|
||||||
func GetGoogleEmail(client *http.Client) (string, error) {
|
func GetGoogleEmail(client *http.Client) (string, error) {
|
||||||
// Get the user info from google using the oauth http client
|
// Get the user info from google using the oauth http client
|
||||||
res, resErr := client.Get("https://www.googleapis.com/userinfo/v2/me")
|
res, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if resErr != nil {
|
if err != nil {
|
||||||
return "", resErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got response from google")
|
log.Debug().Msg("Got response from google")
|
||||||
|
|
||||||
// Read the body of the response
|
// Read the body of the response
|
||||||
body, bodyErr := io.ReadAll(res.Body)
|
body, err := io.ReadAll(res.Body)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if bodyErr != nil {
|
if err != nil {
|
||||||
return "", bodyErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Read body from google")
|
log.Debug().Msg("Read body from google")
|
||||||
@@ -43,11 +43,11 @@ func GetGoogleEmail(client *http.Client) (string, error) {
|
|||||||
var user GoogleUserInfoResponse
|
var user GoogleUserInfoResponse
|
||||||
|
|
||||||
// Unmarshal the body into the user struct
|
// Unmarshal the body into the user struct
|
||||||
jsonErr := json.Unmarshal(body, &user)
|
err = json.Unmarshal(body, &user)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if jsonErr != nil {
|
if err != nil {
|
||||||
return "", jsonErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Parsed user from google")
|
log.Debug().Msg("Parsed user from google")
|
||||||
|
|||||||
@@ -128,11 +128,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
|
|||||||
log.Debug().Msg("Got client from github")
|
log.Debug().Msg("Got client from github")
|
||||||
|
|
||||||
// Get the email from the github provider
|
// Get the email from the github provider
|
||||||
email, emailErr := GetGithubEmail(client)
|
email, err := GetGithubEmail(client)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if emailErr != nil {
|
if err != nil {
|
||||||
return "", emailErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got email from github")
|
log.Debug().Msg("Got email from github")
|
||||||
@@ -152,11 +152,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
|
|||||||
log.Debug().Msg("Got client from google")
|
log.Debug().Msg("Got client from google")
|
||||||
|
|
||||||
// Get the email from the google provider
|
// Get the email from the google provider
|
||||||
email, emailErr := GetGoogleEmail(client)
|
email, err := GetGoogleEmail(client)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if emailErr != nil {
|
if err != nil {
|
||||||
return "", emailErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got email from google")
|
log.Debug().Msg("Got email from google")
|
||||||
@@ -176,11 +176,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
|
|||||||
log.Debug().Msg("Got client from tailscale")
|
log.Debug().Msg("Got client from tailscale")
|
||||||
|
|
||||||
// Get the email from the tailscale provider
|
// Get the email from the tailscale provider
|
||||||
email, emailErr := GetTailscaleEmail(client)
|
email, err := GetTailscaleEmail(client)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if emailErr != nil {
|
if err != nil {
|
||||||
return "", emailErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got email from tailscale")
|
log.Debug().Msg("Got email from tailscale")
|
||||||
@@ -200,11 +200,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
|
|||||||
log.Debug().Msg("Got client from generic")
|
log.Debug().Msg("Got client from generic")
|
||||||
|
|
||||||
// Get the email from the generic provider
|
// Get the email from the generic provider
|
||||||
email, emailErr := GetGenericEmail(client, providers.Config.GenericUserURL)
|
email, err := GetGenericEmail(client, providers.Config.GenericUserURL)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if emailErr != nil {
|
if err != nil {
|
||||||
return "", emailErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got email from generic")
|
log.Debug().Msg("Got email from generic")
|
||||||
|
|||||||
@@ -31,21 +31,21 @@ var TailscaleEndpoint = oauth2.Endpoint{
|
|||||||
|
|
||||||
func GetTailscaleEmail(client *http.Client) (string, error) {
|
func GetTailscaleEmail(client *http.Client) (string, error) {
|
||||||
// Get the user info from tailscale using the oauth http client
|
// Get the user info from tailscale using the oauth http client
|
||||||
res, resErr := client.Get("https://api.tailscale.com/api/v2/tailnet/-/users")
|
res, err := client.Get("https://api.tailscale.com/api/v2/tailnet/-/users")
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if resErr != nil {
|
if err != nil {
|
||||||
return "", resErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Got response from tailscale")
|
log.Debug().Msg("Got response from tailscale")
|
||||||
|
|
||||||
// Read the body of the response
|
// Read the body of the response
|
||||||
body, bodyErr := io.ReadAll(res.Body)
|
body, err := io.ReadAll(res.Body)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if bodyErr != nil {
|
if err != nil {
|
||||||
return "", bodyErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Read body from tailscale")
|
log.Debug().Msg("Read body from tailscale")
|
||||||
@@ -54,11 +54,11 @@ func GetTailscaleEmail(client *http.Client) (string, error) {
|
|||||||
var users TailscaleUserInfoResponse
|
var users TailscaleUserInfoResponse
|
||||||
|
|
||||||
// Unmarshal the body into the user struct
|
// Unmarshal the body into the user struct
|
||||||
jsonErr := json.Unmarshal(body, &users)
|
err = json.Unmarshal(body, &users)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if jsonErr != nil {
|
if err != nil {
|
||||||
return "", jsonErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Debug().Msg("Parsed users from tailscale")
|
log.Debug().Msg("Parsed users from tailscale")
|
||||||
|
|||||||
@@ -69,15 +69,12 @@ type UserContext struct {
|
|||||||
|
|
||||||
// APIConfig is the configuration for the API
|
// APIConfig is the configuration for the API
|
||||||
type APIConfig struct {
|
type APIConfig struct {
|
||||||
Port int
|
Port int
|
||||||
Address string
|
Address string
|
||||||
Secret string
|
Secret string
|
||||||
AppURL string
|
CookieSecure bool
|
||||||
CookieSecure bool
|
SessionExpiry int
|
||||||
SessionExpiry int
|
Domain string
|
||||||
DisableContinue bool
|
|
||||||
GenericName string
|
|
||||||
Title string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// OAuthConfig is the configuration for the providers
|
// OAuthConfig is the configuration for the providers
|
||||||
@@ -164,3 +161,13 @@ type AppContext struct {
|
|||||||
type TotpRequest struct {
|
type TotpRequest struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Server configuration
|
||||||
|
type HandlersConfig struct {
|
||||||
|
AppURL string
|
||||||
|
Domain string
|
||||||
|
CookieSecure bool
|
||||||
|
DisableContinue bool
|
||||||
|
GenericName string
|
||||||
|
Title string
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,11 +29,11 @@ func ParseUsers(users string) (types.Users, error) {
|
|||||||
|
|
||||||
// Loop through the users and split them by colon
|
// Loop through the users and split them by colon
|
||||||
for _, user := range userList {
|
for _, user := range userList {
|
||||||
parsed, parseErr := ParseUser(user)
|
parsed, err := ParseUser(user)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if parseErr != nil {
|
if err != nil {
|
||||||
return types.Users{}, parseErr
|
return types.Users{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append the user to the users struct
|
// Append the user to the users struct
|
||||||
@@ -46,14 +46,14 @@ func ParseUsers(users string) (types.Users, error) {
|
|||||||
return usersParsed, nil
|
return usersParsed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Root url parses parses a hostname and returns the root domain (e.g. sub1.sub2.domain.com -> sub2.domain.com)
|
// Get upper domain parses a hostname and returns the upper domain (e.g. sub1.sub2.domain.com -> sub2.domain.com)
|
||||||
func GetRootURL(urlSrc string) (string, error) {
|
func GetUpperDomain(urlSrc string) (string, error) {
|
||||||
// Make sure the url is valid
|
// Make sure the url is valid
|
||||||
urlParsed, parseErr := url.Parse(urlSrc)
|
urlParsed, err := url.Parse(urlSrc)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if parseErr != nil {
|
if err != nil {
|
||||||
return "", parseErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Split the hostname by period
|
// Split the hostname by period
|
||||||
@@ -69,19 +69,19 @@ func GetRootURL(urlSrc string) (string, error) {
|
|||||||
// Reads a file and returns the contents
|
// Reads a file and returns the contents
|
||||||
func ReadFile(file string) (string, error) {
|
func ReadFile(file string) (string, error) {
|
||||||
// Check if the file exists
|
// Check if the file exists
|
||||||
_, statErr := os.Stat(file)
|
_, err := os.Stat(file)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if statErr != nil {
|
if err != nil {
|
||||||
return "", statErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the file
|
// Read the file
|
||||||
data, readErr := os.ReadFile(file)
|
data, err := os.ReadFile(file)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if readErr != nil {
|
if err != nil {
|
||||||
return "", readErr
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return the file contents
|
// Return the file contents
|
||||||
@@ -152,10 +152,10 @@ func GetUsers(conf string, file string) (types.Users, error) {
|
|||||||
// If the file is set, read the file and append the users to the users string
|
// If the file is set, read the file and append the users to the users string
|
||||||
if file != "" {
|
if file != "" {
|
||||||
// Read the file
|
// Read the file
|
||||||
fileContents, fileErr := ReadFile(file)
|
contents, err := ReadFile(file)
|
||||||
|
|
||||||
// If there isn't an error we can append the users to the users string
|
// If there isn't an error we can append the users to the users string
|
||||||
if fileErr == nil {
|
if err == nil {
|
||||||
log.Debug().Msg("Using users from file")
|
log.Debug().Msg("Using users from file")
|
||||||
|
|
||||||
// Append the users to the users string
|
// Append the users to the users string
|
||||||
@@ -164,7 +164,7 @@ func GetUsers(conf string, file string) (types.Users, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parse the file contents into a comma separated list of users
|
// Parse the file contents into a comma separated list of users
|
||||||
users += ParseFileToLine(fileContents)
|
users += ParseFileToLine(contents)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,15 +38,15 @@ func TestParseUsers(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Test the get root url function
|
// Test the get upper domain function
|
||||||
func TestGetRootURL(t *testing.T) {
|
func TestGetUpperDomain(t *testing.T) {
|
||||||
t.Log("Testing get root url with a valid url")
|
t.Log("Testing get upper domain with a valid url")
|
||||||
|
|
||||||
// Test the get root url function with a valid url
|
// Test the get upper domain function with a valid url
|
||||||
url := "https://sub1.sub2.domain.com:8080"
|
url := "https://sub1.sub2.domain.com:8080"
|
||||||
expected := "sub2.domain.com"
|
expected := "sub2.domain.com"
|
||||||
|
|
||||||
result, err := utils.GetRootURL(url)
|
result, err := utils.GetUpperDomain(url)
|
||||||
|
|
||||||
// Check if there was an error
|
// Check if there was an error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -102,7 +102,7 @@ func TestParseFileToLine(t *testing.T) {
|
|||||||
t.Log("Testing parse file to line with a valid string")
|
t.Log("Testing parse file to line with a valid string")
|
||||||
|
|
||||||
// Test the parse file to line function with a valid string
|
// Test the parse file to line function with a valid string
|
||||||
content := "user1:pass1\nuser2:pass2"
|
content := "\nuser1:pass1\nuser2:pass2\n"
|
||||||
expected := "user1:pass1,user2:pass2"
|
expected := "user1:pass1,user2:pass2"
|
||||||
|
|
||||||
result := utils.ParseFileToLine(content)
|
result := utils.ParseFileToLine(content)
|
||||||
|
|||||||
Reference in New Issue
Block a user