stuve-it-backend/ldapLogin/main.go

72 lines
2.0 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"
"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 {
e.Router.GET("/api/ldap/login", func(c echo.Context) error {
// step 1: get data from request
data := struct {
CN string `json:"cn" form:"cn"`
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.CN)
// 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.CN, 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
}