Files
libredesk/cmd/auth.go
T
Abhinav Raut 966707191d fix: oidc hide secrets in json marshal
- adds new public handler that returns available providers.
2025-01-30 01:43:44 +05:30

68 lines
2.1 KiB
Go

package main
import (
"strconv"
amodels "github.com/abhinavxd/libredesk/internal/auth/models"
"github.com/abhinavxd/libredesk/internal/envelope"
"github.com/valyala/fasthttp"
"github.com/zerodha/fastglue"
)
// handleOIDCLogin redirects to the OIDC provider for login.
func handleOIDCLogin(r *fastglue.Request) error {
var (
app = r.Context.(*App)
providerID, err = strconv.Atoi(r.RequestCtx.UserValue("id").(string))
csrfToken = string(r.RequestCtx.Request.Header.Cookie("csrf_token"))
)
if err != nil {
app.lo.Error("error parsing provider id", "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, "Error parsing provider id.", nil, envelope.GeneralError)
}
authURL, err := app.auth.LoginURL(providerID, csrfToken)
if err != nil {
return sendErrorEnvelope(r, err)
}
return r.Redirect(authURL, fasthttp.StatusFound, nil, "")
}
// handleOIDCCallback receives the redirect callback from the OIDC provider and completes the handshake.
func handleOIDCCallback(r *fastglue.Request) error {
var (
app = r.Context.(*App)
code = string(r.RequestCtx.QueryArgs().Peek("code"))
state = string(r.RequestCtx.QueryArgs().Peek("state"))
providerID, err = strconv.Atoi(string(r.RequestCtx.QueryArgs().Peek("id")))
csrfToken = string(r.RequestCtx.Request.Header.Cookie("csrf_token"))
)
if err != nil {
app.lo.Error("error parsing provider id", "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, "Error parsing provider id.", nil, envelope.GeneralError)
}
_, claims, err := app.auth.ExchangeOIDCToken(r.RequestCtx, providerID, code, csrfToken)
if err != nil {
app.lo.Error("error exchanging oidc token", "error", err)
return err
}
// Get user by e-mail received.
user, err := app.user.GetByEmail(claims.Email)
if err != nil {
return err
}
// Set the session.
if err := app.auth.SaveSession(amodels.User{
ID: user.ID,
Email: user.Email.String,
FirstName: user.FirstName,
LastName: user.LastName,
}, r); err != nil {
return err
}
return r.Redirect(state, fasthttp.StatusFound, nil, "")
}