my-homelab-configs/apps/opsproof/overlay/handlers/authentication/authentication.go

84 lines
1.9 KiB
Go

package authentication
import (
"crypto/rand"
"encoding/hex"
"net/http"
"os"
"strings"
"time"
"go.laravel.com/auth"
"go.laravel.com/auth/social"
"go.laravel.com/db"
"go.laravel.com/inertia"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
const dexProvider social.Provider = "dex"
func Login(request *web.Request) *web.Response {
return inertia.Render("SignIn", inertia.Props{
"provider": "Dex",
"notice": "Operator access uses the homelab identity provider. OpsProof never receives or stores your Dex password.",
})
}
func Start(request *web.Request) *web.Response {
return social.Redirect(request, dexProvider)
}
func Callback(request *web.Request) *web.Response {
profile, err := social.User(request, dexProvider)
if err != nil {
return web.Fail(err)
}
email := strings.ToLower(strings.TrimSpace(profile.VerifiedEmail()))
if email == "" || !operatorAllowed(email) {
return web.Abort(http.StatusForbidden)
}
name := strings.TrimSpace(profile.Name)
if name == "" {
name = email
}
verified := time.Now().UTC()
password := make([]byte, 32)
if _, err := rand.Read(password); err != nil {
return web.Fail(err)
}
user, _, err := model.FirstOrCreate[models.User](request,
db.Values{"email": email},
db.Values{
"name": name,
"email_verified_at": verified,
"password": "dex-only-" + hex.EncodeToString(password),
},
)
if err != nil {
return web.Fail(err)
}
if err := auth.Login(request, &user, false); err != nil {
return web.Fail(err)
}
return auth.RedirectIntended("/")
}
func Logout(request *web.Request) *web.Response {
if err := auth.Logout(request); err != nil {
return web.Fail(err)
}
return web.Redirect("/")
}
func operatorAllowed(email string) bool {
for _, allowed := range strings.Split(os.Getenv("OPSPROOF_OPERATOR_EMAILS"), ",") {
if strings.EqualFold(strings.TrimSpace(allowed), email) {
return true
}
}
return false
}