78 lines
2.1 KiB
Go
78 lines
2.1 KiB
Go
package ldapLogin
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/go-ldap/ldap/v3"
|
|
"github.com/labstack/echo/v5"
|
|
"github.com/pocketbase/pocketbase"
|
|
"github.com/pocketbase/pocketbase/apis"
|
|
"github.com/pocketbase/pocketbase/core"
|
|
"gitlab.uni-ulm.de/stuve-it/it-tools/backend/ldapSync"
|
|
"gitlab.uni-ulm.de/stuve-it/it-tools/backend/logger"
|
|
"os"
|
|
)
|
|
|
|
// InitLDAPLogin initializes ldap login endpoint
|
|
//
|
|
// this endpoint is used to authenticate users against ldap server
|
|
// it adds the following endpoint to the app:
|
|
// GET /api/ldap/login
|
|
//
|
|
// the endpoint expects the following request data:
|
|
//
|
|
// {
|
|
// "cn": "user common name",
|
|
// "password": "user password"
|
|
// }
|
|
//
|
|
// if the user is authenticated successfully the endpoint returns and apis.RecordAuthResponse
|
|
func InitLDAPLogin(app *pocketbase.PocketBase, e *core.ServeEvent) error {
|
|
|
|
// add endpoint to app
|
|
logger.LogInfoF("Adding LDAP Login Endpoint")
|
|
|
|
e.Router.POST("/api/ldap/login", func(c echo.Context) error {
|
|
|
|
logger.LogInfoF("LDAP Login")
|
|
|
|
// step 1: get data from request
|
|
data := struct {
|
|
Username string `json:"username" form:"username"`
|
|
Password string `json:"password" form:"password"`
|
|
}{}
|
|
if err := c.Bind(&data); err != nil {
|
|
return apis.NewBadRequestError("Failed to read request data", err)
|
|
}
|
|
|
|
// step 2: get ldap user by cn from ldapUsers table
|
|
record, err := ldapSync.GetLdapUserByCN(app, data.Username)
|
|
|
|
// if user does not exist in ldapUsers table return error
|
|
if err != nil {
|
|
return apis.NewBadRequestError("Invalid credentials", err)
|
|
}
|
|
|
|
// step 3: connect to ldap server
|
|
conn, err := ldap.DialURL(os.Getenv("LDAP_URL"))
|
|
if err != nil {
|
|
return apis.NewBadRequestError(
|
|
"Failed to read request data",
|
|
fmt.Errorf("unable to connect to ldap server - %s", err),
|
|
)
|
|
}
|
|
defer conn.Close()
|
|
|
|
// step 4: bind to ldap server with user credentials from request
|
|
err = conn.Bind(data.Username, data.Password)
|
|
if err != nil {
|
|
// if bind fails return error - invalid credentials
|
|
return apis.NewBadRequestError("Invalid credentials", err)
|
|
}
|
|
|
|
// return auth response
|
|
return apis.RecordAuthResponse(app, c, record, nil)
|
|
}, apis.ActivityLogger(app))
|
|
|
|
return nil
|
|
}
|