diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..57dc561
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,13 @@
+.git
+.github
+node_modules
+docs
+
+internal/web/static/styles.css
+internal/web/static/js/*.js
+Dockerfile
+README.md
+LICENSE
+.env*
+.prettier*
+.gitignore
diff --git a/.env b/.env
new file mode 100644
index 0000000..d976916
--- /dev/null
+++ b/.env
@@ -0,0 +1,14 @@
+# If a value is left empty, it will get set to the default during application startup.
+
+LDAP_SERVER=""
+LDAP_IS_AD=""
+LDAP_BASE_DN=""
+LDAP_READONLY_USER=""
+LDAP_READONLY_PASSWORD=""
+
+MIN_LENGTH=""
+MIN_NUMBERS=""
+MIN_SYMBOLS=""
+MIN_UPPERCASE=""
+MIN_LOWERCASE=""
+PASSWORD_CAN_INCLUDE_USERNAME=""
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..f1b219b
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,6 @@
+version: 2
+updates:
+ - package-ecosystem: "gomod"
+ directory: "/"
+ schedule:
+ interval: "weekly"
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
new file mode 100644
index 0000000..00fd604
--- /dev/null
+++ b/.github/workflows/check.yml
@@ -0,0 +1,135 @@
+name: Check
+
+on:
+ release:
+ types: [published]
+ pull_request:
+ push:
+ branches:
+ - main
+
+jobs:
+ go-test:
+ name: Run Go tests
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up Go
+ uses: actions/setup-go@v4
+ with:
+ go-version: "1.20"
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: "18"
+
+ - uses: pnpm/action-setup@v2
+ name: Install pnpm
+ id: pnpm-install
+ with:
+ version: 8
+ run_install: false
+
+ - name: Get pnpm store directory
+ id: pnpm-cache
+ shell: bash
+ run: |
+ echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
+
+ - uses: actions/cache@v3
+ name: Setup pnpm cache
+ with:
+ path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
+ key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
+ restore-keys: |
+ ${{ runner.os }}-pnpm-store-
+
+ - name: Install dependencies
+ run: pnpm install && go mod download
+
+ - name: Check types
+ run: pnpm build:assets
+
+ - name: Build
+ run: go build -v ./...
+
+ - name: Test
+ run: go test -v ./...
+
+ types:
+ name: Check types
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: "18"
+
+ - uses: pnpm/action-setup@v2
+ name: Install pnpm
+ id: pnpm-install
+ with:
+ version: 8
+ run_install: false
+
+ - name: Get pnpm store directory
+ id: pnpm-cache
+ shell: bash
+ run: |
+ echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
+
+ - uses: actions/cache@v3
+ name: Setup pnpm cache
+ with:
+ path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
+ key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
+ restore-keys: |
+ ${{ runner.os }}-pnpm-store-
+
+ - name: Install dependencies
+ run: pnpm install
+
+ - name: Check types
+ run: pnpm js:build
+
+ formatting:
+ name: Check formatting
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: "18"
+
+ - uses: pnpm/action-setup@v2
+ name: Install pnpm
+ id: pnpm-install
+ with:
+ version: 8
+ run_install: false
+
+ - name: Get pnpm store directory
+ id: pnpm-cache
+ shell: bash
+ run: |
+ echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
+
+ - uses: actions/cache@v3
+ name: Setup pnpm cache
+ with:
+ path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
+ key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
+ restore-keys: |
+ ${{ runner.os }}-pnpm-store-
+
+ - name: Install dependencies
+ run: pnpm install
+
+ - name: Check formatting
+ run: pnpm prettier --check .
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
new file mode 100644
index 0000000..f710cf5
--- /dev/null
+++ b/.github/workflows/docker.yml
@@ -0,0 +1,66 @@
+name: Docker
+
+on:
+ release:
+ types: [published]
+ schedule:
+ - cron: "0 0 * * 0"
+ pull_request:
+ push:
+ branches:
+ - main
+
+env:
+ REGISTRY: ghcr.io
+ IMAGE_NAME: "${{ github.repository_owner }}/ldap-selfservice-password-changer"
+
+jobs:
+ docker:
+ name: Build Images
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up QEMU
+ uses: docker/setup-qemu-action@v2
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v2
+
+ - name: Cache docker layers
+ uses: actions/cache@v3
+ id: cache
+ with:
+ path: /tmp/.buildx-cache
+ key: ${{ runner.os }}-buildx-${{ github.sha }}
+ restore-keys: |
+ ${{ runner.os }}-buildx-
+
+ - name: Gather Docker metadata
+ id: meta
+ uses: docker/metadata-action@v4
+ with:
+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
+ tags: |
+ type=ref,event=branch
+ type=ref,event=pr
+ type=semver,pattern={{version}}
+ type=semver,pattern={{version}}.{{major}}
+ labels: |
+ cache-from=type=local,src=/tmp/.buildx-cache
+ cache-to=type=local,dest=/tmp/.buildx-cache
+
+ - name: Log in to the Container registry
+ uses: docker/login-action@v2
+ with:
+ registry: ${{ env.REGISTRY }}
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build and push Docker image
+ uses: docker/build-push-action@v4
+ with:
+ push: true
+ tags: ${{ steps.meta.outputs.tags }}
+ labels: ${{ steps.meta.outputs.labels }}
+ platforms: linux/amd64,linux/arm/v7,linux/arm64
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6ad4900
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+node_modules
+internal/web/static/js/*.js
+internal/web/static/styles.css
+.env.local
+*.bbolt
\ No newline at end of file
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..2f788d5
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,3 @@
+internal/web/static/styles.css
+internal/web/static/js/*.js
+pnpm-lock.yaml
diff --git a/.prettierrc.js b/.prettierrc.js
new file mode 100644
index 0000000..e6ca573
--- /dev/null
+++ b/.prettierrc.js
@@ -0,0 +1,16 @@
+module.exports = {
+ printWidth: 120,
+ trailingComma: "none",
+ tabWidth: 2,
+ semi: true,
+ singleQuote: false,
+ plugins: [require("prettier-plugin-tailwindcss"), require("prettier-plugin-go-template")],
+ overrides: [
+ {
+ files: ["*.html"],
+ options: {
+ parser: "go-template"
+ }
+ }
+ ]
+};
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..0f23057
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,30 @@
+FROM --platform=amd64 node:18 AS frontend-builder
+WORKDIR /build
+RUN npm i -g pnpm
+
+COPY package.json .
+COPY pnpm-lock.yaml .
+RUN pnpm i
+
+COPY . .
+
+RUN pnpm build:assets
+
+FROM golang:1.20-alpine AS backend-builder
+WORKDIR /build
+RUN apk add git
+
+COPY ./go.mod .
+COPY ./go.sum .
+RUN go mod download
+
+COPY . .
+COPY --from=frontend-builder /build/internal/web/static/styles.css /build/internal/web/static/styles.css
+COPY --from=frontend-builder /build/internal/web/static/js/*.js /build/internal/web/static/js
+RUN CGO_ENABLED=0 go build -o /build/ldap-passwd
+
+FROM alpine:3 AS runner
+
+COPY --from=backend-builder /build/ldap-passwd /usr/local/bin/ldap-passwd
+
+ENTRYPOINT [ "/usr/local/bin/ldap-passwd" ]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f59c096
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2023 Netresearch DTT GmbH
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9567beb
--- /dev/null
+++ b/README.md
@@ -0,0 +1,101 @@
+
+
LDAP Selfservice Password Changer
+
+LDAP Selfservice Password Changer is a web frontend and JSON RPC API for allowing your users to change their own passwords in your LDAP or ActiveDirectory server.
+
+
+
+
+## Running
+
+### Natively
+
+If you want to run this service without a Docker container, you have to build it yourself.
+
+Prerequisites:
+
+- Go 1.20+
+- Node.js v16+
+- Corepack (`npm i -g corepack`)
+
+You can configure this via a `.env.local` file or via command options (for more information you can run `./ldap-selfservice-password-changer --help`).
+
+
+
+```bash
+corepack enable
+pnpm i
+pnpm build
+
+./ldap-selfservice-password-changer \
+ `# You can also configure these via environment variables,` \
+ `# please see the .env file for available options.` \
+ -ldap-server ldaps://dc1.example.com:636 -active-directory \
+ -readonly-password readonly -readonly-user readonly \
+ -base-dn DC=example,DC=com
+```
+
+### Docker
+
+We have a Docker image available [here](https://github.com/netresearch/ldap-selfservice-password-changer/pkgs/container/ldap-selfservice-password-changer).
+
+You can ignore the warning that the service could not load a `.env` file.
+
+
+
+```bash
+docker run \
+ `# Run the password-changer container detached from the current terminal` \
+ -d --name ldap-password-changer \
+ `# You might want to mount your host SSL certificate directory,` \
+ `# if you have a self-signed certificate for your LDAPS connection` \
+ -v /etc/ssl/certs:/etc/ssl/certs:ro \
+ -p 3000:3000 \
+ ghcr.io/netresearch/ldap-selfservice-password-changer \
+ `# You can also configure these via environment variables,` \
+ `# please see the .env file for available options.` \
+ -ldap-server ldaps://dc1.example.com:636 -active-directory \
+ -readonly-password readonly -readonly-user readonly \
+ -base-dn DC=example,DC=com
+```
+
+## Developing
+
+Prerequisites:
+
+- Go 1.20+
+- Node.js v16+
+- Corepack (`npm i -g corepack`)
+
+```bash
+corepack enable
+
+# Install dependencies
+pnpm i
+
+touch .env.local
+# Edit the `.env.local` to include the arguments, you want to give to the application.
+# Required are:
+# - LDAP_SERVER
+# - LDAP_BASE_DN
+# - LDAP_READONLY_USER
+# - LDAP_READONLY_PASSWORD
+
+# Running normally
+pnpm start
+
+# Running in dev mode
+# This will restart the application every time, you make
+# a change.
+pnpm dev
+```
+
+## License
+
+LDAP Selfservice Password Changer is licensed under the MIT license, for more information please refer to the [included LICENSE file](LICENSE).
+
+## Contributing
+
+Feel free to contribute by creating a Pull Request!
+
+This project uses [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for commit messages and the default `gofmt` and `prettier` formatting rules.
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..ab54073
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,4 @@
+# Architecture
+
+The following architecture will be used:
+![Architecture](./architecture.png)
diff --git a/docs/architecture.png b/docs/architecture.png
new file mode 100644
index 0000000..3b531d1
Binary files /dev/null and b/docs/architecture.png differ
diff --git a/docs/logo.png b/docs/logo.png
new file mode 100644
index 0000000..6810d87
Binary files /dev/null and b/docs/logo.png differ
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..d084f9a
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,34 @@
+module github.com/netresearch/ldap-selfservice-password-changer
+
+go 1.20
+
+require (
+ github.com/gofiber/fiber/v2 v2.48.0
+ github.com/gofiber/storage/bbolt v1.3.5
+ github.com/gofiber/template/html/v2 v2.0.5
+ github.com/joho/godotenv v1.5.1
+ github.com/netresearch/simple-ldap-go v0.0.0-20231002103847-cb56d7d4e6c7
+ github.com/rs/zerolog v1.29.1
+)
+
+require (
+ github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
+ github.com/andybalholm/brotli v1.0.5 // indirect
+ github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
+ github.com/go-ldap/ldap/v3 v3.4.6 // indirect
+ github.com/gofiber/template v1.8.2 // indirect
+ github.com/gofiber/utils v1.1.0 // indirect
+ github.com/google/uuid v1.3.1 // indirect
+ github.com/klauspost/compress v1.16.7 // indirect
+ github.com/mattn/go-colorable v0.1.13 // indirect
+ github.com/mattn/go-isatty v0.0.19 // indirect
+ github.com/mattn/go-runewidth v0.0.14 // indirect
+ github.com/rivo/uniseg v0.4.4 // indirect
+ github.com/valyala/bytebufferpool v1.0.0 // indirect
+ github.com/valyala/fasthttp v1.48.0 // indirect
+ github.com/valyala/tcplisten v1.0.0 // indirect
+ go.etcd.io/bbolt v1.3.7 // indirect
+ golang.org/x/crypto v0.13.0 // indirect
+ golang.org/x/sys v0.12.0 // indirect
+ golang.org/x/text v0.13.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..0eab55c
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,119 @@
+github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
+github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
+github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 h1:Kk6a4nehpJ3UuJRqlA3JxYxBZEqCeOmATOvrbT4p9RA=
+github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
+github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
+github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
+github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
+github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
+github.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A=
+github.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc=
+github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
+github.com/gofiber/fiber/v2 v2.48.0 h1:cRVMCb9aUJDsyHxGFLwz/sGzDggdailZZyptU9F9cU0=
+github.com/gofiber/fiber/v2 v2.48.0/go.mod h1:xqJgfqrc23FJuqGOW6DVgi3HyZEm2Mn9pRqUb2kHSX8=
+github.com/gofiber/storage/bbolt v1.3.5 h1:9ZDMTbeah5tfj3eX+hFu3F1AHiBO117ce3Gel7tkxlk=
+github.com/gofiber/storage/bbolt v1.3.5/go.mod h1:GibrOAQTFOzzzWWVCgq+V+gS8dUbaPeAMGI4FNZ32sI=
+github.com/gofiber/template v1.8.2 h1:PIv9s/7Uq6m+Fm2MDNd20pAFFKt5wWs7ZBd8iV9pWwk=
+github.com/gofiber/template v1.8.2/go.mod h1:bs/2n0pSNPOkRa5VJ8zTIvedcI/lEYxzV3+YPXdBvq8=
+github.com/gofiber/template/html/v2 v2.0.5 h1:BKLJ6Qr940NjntbGmpO3zVa4nFNGDCi/IfUiDB9OC20=
+github.com/gofiber/template/html/v2 v2.0.5/go.mod h1:RCF14eLeQDCSUPp0IGc2wbSSDv6yt+V54XB/+Unz+LM=
+github.com/gofiber/utils v1.1.0 h1:vdEBpn7AzIUJRhe+CiTOJdUcTg4Q9RK+pEa0KPbLdrM=
+github.com/gofiber/utils v1.1.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0=
+github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
+github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
+github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
+github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I=
+github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
+github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
+github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
+github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
+github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
+github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
+github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
+github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
+github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002091551-aa3c68c43a90 h1:A4sgcCe3ZrT/FpgsUY8tCfOHae6yI5VvHauo9zxitcQ=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002091551-aa3c68c43a90/go.mod h1:v00qbwupQnx2Mk3oJoJylMWD54yJk6vHsbFj5RIOK5o=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002094326-383f3eda4fe0 h1:C8jIl/OEDMHwu/OSZ5Pd2pDk2ePx8JaX+9YLLioIfIA=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002094326-383f3eda4fe0/go.mod h1:v00qbwupQnx2Mk3oJoJylMWD54yJk6vHsbFj5RIOK5o=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002095049-edec788b6515 h1:1ZJoAqs/0F1Dn3dNqiMJleurJy4Wk5mwNT+7QeQ30p8=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002095049-edec788b6515/go.mod h1:v00qbwupQnx2Mk3oJoJylMWD54yJk6vHsbFj5RIOK5o=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002103847-cb56d7d4e6c7 h1:hN2eW111sh8hpPT4GwIXafbSqHtJfAnLGc+hZAQehnk=
+github.com/netresearch/simple-ldap-go v0.0.0-20231002103847-cb56d7d4e6c7/go.mod h1:v00qbwupQnx2Mk3oJoJylMWD54yJk6vHsbFj5RIOK5o=
+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
+github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
+github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
+github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc=
+github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
+github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
+github.com/valyala/fasthttp v1.48.0 h1:oJWvHb9BIZToTQS3MuQ2R3bJZiNSa2KiNdeI8A+79Tc=
+github.com/valyala/fasthttp v1.48.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
+github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
+github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
+github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ=
+go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
+golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
+golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
+golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
+golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/ldap_cache/cache.go b/internal/ldap_cache/cache.go
new file mode 100644
index 0000000..d6c0476
--- /dev/null
+++ b/internal/ldap_cache/cache.go
@@ -0,0 +1,182 @@
+package ldap_cache
+
+import (
+ "sync"
+ "time"
+
+ ldap "github.com/netresearch/simple-ldap-go"
+ "github.com/rs/zerolog/log"
+)
+
+type Cache struct {
+ stop chan struct{}
+
+ m sync.RWMutex
+ client *ldap.LDAP
+ users []ldap.User
+ groups []ldap.Group
+}
+
+type FullLDAPUser struct {
+ ldap.User
+ Groups []ldap.Group
+}
+
+type FullLDAPGroup struct {
+ ldap.Group
+ Members []ldap.User
+}
+
+func New(client *ldap.LDAP) *Cache {
+ return &Cache{
+ stop: make(chan struct{}),
+ client: client,
+ users: make([]ldap.User, 0),
+ groups: make([]ldap.Group, 0),
+ }
+}
+
+func (l *Cache) Run() {
+ t := time.NewTicker(30 * time.Second)
+
+ l.refresh()
+
+ for {
+ select {
+ case <-l.stop:
+ t.Stop()
+ log.Info().Msg("LDAP cache stopped")
+
+ return
+ case <-t.C:
+ l.refresh()
+ }
+ }
+}
+
+func (l *Cache) Stop() {
+ l.stop <- struct{}{}
+}
+
+func (l *Cache) refreshUsers() error {
+ users, err := l.client.FindUsers()
+ if err != nil {
+ return err
+ }
+
+ l.m.Lock()
+ l.users = users
+ l.m.Unlock()
+
+ return nil
+}
+
+func (l *Cache) refreshGroups() error {
+ groups, err := l.client.FindGroups()
+ if err != nil {
+ return err
+ }
+
+ l.m.Lock()
+ l.groups = groups
+ l.m.Unlock()
+
+ return nil
+}
+
+func (l *Cache) refresh() {
+ if err := l.refreshUsers(); err != nil {
+ log.Error().Err(err).Send()
+ }
+
+ if err := l.refreshGroups(); err != nil {
+ log.Error().Err(err).Send()
+ }
+
+ log.Debug().Msgf("Refreshed LDAP cache with %d users and %d groups", len(l.users), len(l.groups))
+}
+
+func (l *Cache) FindUsers() []ldap.User {
+ l.m.RLock()
+ defer l.m.RUnlock()
+
+ return l.users
+}
+
+func (l *Cache) FindUserByDN(dn string) (ldap.User, error) {
+ l.m.RLock()
+ defer l.m.RUnlock()
+
+ for _, user := range l.users {
+ if user.DN == dn {
+ return user, nil
+ }
+ }
+
+ return ldap.User{}, ldap.ErrUserNotFound
+}
+
+func (l *Cache) FindUserBySAMAccountName(samAccountName string) (ldap.User, error) {
+ l.m.RLock()
+ defer l.m.RUnlock()
+
+ for _, user := range l.users {
+ if user.SAMAccountName == samAccountName {
+ return user, nil
+ }
+ }
+
+ return ldap.User{}, ldap.ErrUserNotFound
+}
+
+func (l *Cache) FindGroups() []ldap.Group {
+ l.m.RLock()
+ defer l.m.RUnlock()
+
+ return l.groups
+}
+
+func (l *Cache) FindGroupByDN(dn string) (ldap.Group, error) {
+ l.m.RLock()
+ defer l.m.RUnlock()
+
+ for _, group := range l.groups {
+ if group.DN == dn {
+ return group, nil
+ }
+ }
+
+ return ldap.Group{}, ldap.ErrGroupNotFound
+}
+
+func (l *Cache) PopulateGroupsForUser(user *ldap.User) *FullLDAPUser {
+ full := &FullLDAPUser{
+ User: *user,
+ Groups: make([]ldap.Group, 0),
+ }
+
+ for _, groupDN := range user.Groups {
+ group, err := l.FindGroupByDN(groupDN)
+ if err == nil {
+ full.Groups = append(full.Groups, group)
+ }
+ }
+
+ return full
+}
+
+func (l *Cache) PopulateUsersForGroup(group *ldap.Group) *FullLDAPGroup {
+ full := &FullLDAPGroup{
+ Group: *group,
+ Members: make([]ldap.User, 0),
+ }
+
+ for _, userDN := range group.Members {
+ user, err := l.FindUserByDN(userDN)
+ if err == nil {
+ full.Members = append(full.Members, user)
+ }
+ }
+
+ return full
+}
diff --git a/internal/options/app.go b/internal/options/app.go
new file mode 100644
index 0000000..4e15aaa
--- /dev/null
+++ b/internal/options/app.go
@@ -0,0 +1,93 @@
+package options
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "strconv"
+
+ "github.com/joho/godotenv"
+ "github.com/rs/zerolog/log"
+)
+
+type Opts struct {
+ LdapServer string
+ IsActiveDirectory bool
+ BaseDN string
+ ReadonlyUser string
+ ReadonlyPassword string
+
+ DBPath string
+}
+
+func panicWhenEmpty(name string, value *string) {
+ if *value == "" {
+ log.Fatal().Msgf("err: The option --%s is required", name)
+ }
+}
+
+func envStringOrDefault(name, d string) string {
+ if v, exists := os.LookupEnv(name); exists && v != "" {
+ return v
+ }
+
+ return d
+}
+
+func envIntOrDefault(name string, d uint64) uint {
+ raw := envStringOrDefault(name, fmt.Sprintf("%v", d))
+
+ v, err := strconv.ParseUint(raw, 10, 8)
+ if err != nil {
+ log.Fatal().Msgf("err: could not parse environment variable \"%s\" (containing \"%s\") as uint: %v", name, raw, err)
+ }
+
+ return uint(v)
+}
+
+func envBoolOrDefault(name string, d bool) bool {
+ raw := envStringOrDefault(name, fmt.Sprintf("%v", d))
+
+ v2, err := strconv.ParseBool(raw)
+ if err != nil {
+ log.Fatal().Msgf("err: could not parse environment variable \"%s\" (containing \"%s\") as bool: %v", name, raw, err)
+ }
+
+ return v2
+}
+
+func Parse() *Opts {
+ if err := godotenv.Load(".env.local", ".env"); err != nil {
+ log.Warn().Err(err).Msg("could not load .env file")
+ }
+
+ var (
+ fLdapServer = flag.String("ldap-server", envStringOrDefault("LDAP_SERVER", ""), "LDAP server URI, has to begin with `ldap://` or `ldaps://`. If this is an ActiveDirectory server, this *has* to be `ldaps://`.")
+ fIsActiveDirectory = flag.Bool("active-directory", envBoolOrDefault("LDAP_IS_AD", false), "Mark the LDAP server as ActiveDirectory.")
+ fBaseDN = flag.String("base-dn", envStringOrDefault("LDAP_BASE_DN", ""), "Base DN of your LDAP directory.")
+ fReadonlyUser = flag.String("readonly-user", envStringOrDefault("LDAP_READONLY_USER", ""), "User that can read all users in your LDAP directory.")
+ fReadonlyPassword = flag.String("readonly-password", envStringOrDefault("LDAP_READONLY_PASSWORD", ""), "Password for the readonly user.")
+
+ fDBPath = flag.String("db-path", envStringOrDefault("DB_PATH", "db.bbolt"), "Path to the SQLite database file.")
+ )
+
+ if !flag.Parsed() {
+ flag.Parse()
+ }
+
+ panicWhenEmpty("ldap-server", fLdapServer)
+ panicWhenEmpty("base-dn", fBaseDN)
+ panicWhenEmpty("readonly-user", fReadonlyUser)
+ panicWhenEmpty("readonly-password", fReadonlyPassword)
+ panicWhenEmpty("db-path", fDBPath)
+
+ return &Opts{
+ LdapServer: *fLdapServer,
+ IsActiveDirectory: *fIsActiveDirectory,
+ BaseDN: *fBaseDN,
+ ReadonlyUser: *fReadonlyUser,
+ ReadonlyPassword: *fReadonlyPassword,
+
+ DBPath: *fDBPath,
+ }
+}
diff --git a/internal/web/auth.go b/internal/web/auth.go
new file mode 100644
index 0000000..545f4fe
--- /dev/null
+++ b/internal/web/auth.go
@@ -0,0 +1,57 @@
+package web
+
+import (
+ "github.com/gofiber/fiber/v2"
+ "github.com/rs/zerolog/log"
+)
+
+func (a *App) logoutHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ if err := sess.Destroy(); err != nil {
+ return handle500(c, err)
+ }
+
+ return c.Redirect("/login")
+}
+
+func (a *App) loginHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ username := c.Query("username")
+ password := c.Query("password")
+
+ if username != "" && password != "" {
+ user, err := a.ldap.CheckPasswordForSAMAccountName(username, password)
+ if err != nil {
+ log.Error().Err(err).Msg("could not check password")
+
+ return c.Render("views/login", fiber.Map{
+ "session": sess,
+ "title": "Login",
+ "headscripts": "",
+ "flashes": []string{"Invalid username or password"},
+ }, "layouts/base")
+ }
+
+ sess.Set("username", user.SAMAccountName)
+ sess.Set("password", password)
+ if err := sess.Save(); err != nil {
+ return handle500(c, err)
+ }
+
+ return c.Redirect("/")
+ }
+
+ return c.Render("views/login", fiber.Map{
+ "session": sess,
+ "title": "Login",
+ "headscripts": "",
+ }, "layouts/base")
+}
diff --git a/internal/web/groups.go b/internal/web/groups.go
new file mode 100644
index 0000000..e267478
--- /dev/null
+++ b/internal/web/groups.go
@@ -0,0 +1,62 @@
+package web
+
+import (
+ "net/url"
+
+ "github.com/gofiber/fiber/v2"
+ "github.com/rs/zerolog/log"
+)
+
+func (a *App) groupsHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ if sess.Fresh() {
+ return c.Redirect("/login")
+ }
+
+ groups := a.ldapCache.FindGroups()
+
+ return c.Render("views/groups", fiber.Map{
+ "session": sess,
+ "title": "All groups",
+ "activePage": "/groups",
+ "headscripts": "",
+ "groups": groups,
+ }, "layouts/logged-in")
+}
+
+func (a *App) groupHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ if sess.Fresh() {
+ return c.Redirect("/login")
+ }
+
+ groupDN, err := url.PathUnescape(c.Params("groupDN"))
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ thinGroup, err := a.ldapCache.FindGroupByDN(groupDN)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ group := a.ldapCache.PopulateUsersForGroup(&thinGroup)
+
+ log.Debug().Interface("group", group).Msg("Populated group")
+
+ return c.Render("views/group", fiber.Map{
+ "session": sess,
+ "title": "All groups",
+ "activePage": "/groups",
+ "headscripts": "",
+ "group": group,
+ }, "layouts/logged-in")
+}
diff --git a/internal/web/layouts/base.html b/internal/web/layouts/base.html
new file mode 100644
index 0000000..e94dcd0
--- /dev/null
+++ b/internal/web/layouts/base.html
@@ -0,0 +1,29 @@
+
+
+
+ {{ .title }} - LDAP Manager
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ .headscripts }}
+
+
+
+
+
+
+ {{ embed }}
+
+
diff --git a/internal/web/layouts/logged-in.html b/internal/web/layouts/logged-in.html
new file mode 100644
index 0000000..d0e2105
--- /dev/null
+++ b/internal/web/layouts/logged-in.html
@@ -0,0 +1,53 @@
+
+
+
+ {{ .title }} - LDAP Manager
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ .headscripts }}
+
+
+
+
+
+
+
+
+
+ {{ embed }}
+
+
+
diff --git a/internal/web/server.go b/internal/web/server.go
new file mode 100644
index 0000000..d7bd1ca
--- /dev/null
+++ b/internal/web/server.go
@@ -0,0 +1,124 @@
+package web
+
+import (
+ "net/http"
+
+ "github.com/gofiber/fiber/v2"
+ "github.com/gofiber/fiber/v2/middleware/compress"
+ "github.com/gofiber/fiber/v2/middleware/filesystem"
+ "github.com/gofiber/fiber/v2/middleware/session"
+ "github.com/gofiber/storage/bbolt"
+ "github.com/gofiber/template/html/v2"
+ "github.com/netresearch/ldap-selfservice-password-changer/internal/ldap_cache"
+ "github.com/netresearch/ldap-selfservice-password-changer/internal/options"
+ "github.com/netresearch/ldap-selfservice-password-changer/internal/web/static"
+ ldap "github.com/netresearch/simple-ldap-go"
+ "github.com/rs/zerolog/log"
+)
+
+type App struct {
+ ldap *ldap.LDAP
+ ldapCache *ldap_cache.Cache
+ sessionStore *session.Store
+ fiber *fiber.App
+}
+
+func NewApp(opts *options.Opts) (*App, error) {
+ ldap, err := ldap.New(opts.LdapServer, opts.BaseDN, opts.ReadonlyUser, opts.ReadonlyPassword, opts.IsActiveDirectory)
+ if err != nil {
+ return nil, err
+ }
+
+ views := html.NewFileSystem(http.FS(templates), ".html")
+ views.AddFunc("inputOpts", tplInputOpts)
+ views.AddFunc("navbarActive", tplNavbarActive)
+
+ sessionStorage := bbolt.New(bbolt.Config{
+ Database: opts.DBPath,
+ Bucket: "sessions",
+ Reset: false,
+ })
+ sessionStore := session.New(session.Config{
+ Storage: sessionStorage,
+ })
+
+ f := fiber.New(fiber.Config{
+ AppName: "netresearch/ldap-manager",
+ BodyLimit: 4 * 1024,
+ Views: views,
+ })
+ f.Use(compress.New(compress.Config{
+ Level: compress.LevelBestSpeed,
+ }))
+ f.Use("/static", filesystem.New(filesystem.Config{
+ Root: http.FS(static.Static),
+ MaxAge: 24 * 60 * 60,
+ }))
+
+ a := &App{
+ ldap: ldap,
+ ldapCache: ldap_cache.New(ldap),
+ sessionStore: sessionStore,
+ fiber: f,
+ }
+
+ f.Get("/", a.indexHandler)
+ f.Get("/users", a.usersHandler)
+ f.Get("/users/:userDN", a.userHandler)
+ f.Get("/groups", a.groupsHandler)
+ f.Get("/groups/:groupDN", a.groupHandler)
+ f.Get("/login", a.loginHandler)
+ f.Get("/logout", a.logoutHandler)
+
+ f.Use(a.fourOhFourHandler)
+
+ return a, nil
+}
+
+func (a *App) Listen(addr string) error {
+ go a.ldapCache.Run()
+
+ return a.fiber.Listen(addr)
+}
+
+func handle500(c *fiber.Ctx, err error) error {
+ log.Error().Err(err).Msg("could not get session")
+
+ return c.Render("views/500", fiber.Map{
+ "title": "error",
+ "headscripts": "",
+ "error": err.Error(),
+ }, "layouts/base")
+}
+
+func (a *App) indexHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ // TODO: put this into a middleware
+ if sess.Fresh() {
+ return c.Redirect("/login")
+ }
+
+ user, err := a.ldapCache.FindUserBySAMAccountName(sess.Get("username").(string))
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ return c.Render("views/index", fiber.Map{
+ "session": sess,
+ "title": "List",
+ "activePage": "/",
+ "headscripts": "",
+ "user": user,
+ }, "layouts/logged-in")
+}
+
+func (a *App) fourOhFourHandler(c *fiber.Ctx) error {
+ return c.Render("views/404", fiber.Map{
+ "title": "404",
+ "headscripts": "",
+ }, "layouts/base")
+}
diff --git a/internal/web/static/android-chrome-192x192.png b/internal/web/static/android-chrome-192x192.png
new file mode 100644
index 0000000..a784471
Binary files /dev/null and b/internal/web/static/android-chrome-192x192.png differ
diff --git a/internal/web/static/android-chrome-512x512.png b/internal/web/static/android-chrome-512x512.png
new file mode 100644
index 0000000..95d42e4
Binary files /dev/null and b/internal/web/static/android-chrome-512x512.png differ
diff --git a/internal/web/static/apple-touch-icon.png b/internal/web/static/apple-touch-icon.png
new file mode 100644
index 0000000..314c931
Binary files /dev/null and b/internal/web/static/apple-touch-icon.png differ
diff --git a/internal/web/static/browserconfig.xml b/internal/web/static/browserconfig.xml
new file mode 100644
index 0000000..b3930d0
--- /dev/null
+++ b/internal/web/static/browserconfig.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+ #da532c
+
+
+
diff --git a/internal/web/static/favicon-16x16.png b/internal/web/static/favicon-16x16.png
new file mode 100644
index 0000000..451b87e
Binary files /dev/null and b/internal/web/static/favicon-16x16.png differ
diff --git a/internal/web/static/favicon-32x32.png b/internal/web/static/favicon-32x32.png
new file mode 100644
index 0000000..5e943bd
Binary files /dev/null and b/internal/web/static/favicon-32x32.png differ
diff --git a/internal/web/static/favicon.ico b/internal/web/static/favicon.ico
new file mode 100644
index 0000000..b79e9fc
Binary files /dev/null and b/internal/web/static/favicon.ico differ
diff --git a/internal/web/static/js/app.ts b/internal/web/static/js/app.ts
new file mode 100644
index 0000000..dfb9067
--- /dev/null
+++ b/internal/web/static/js/app.ts
@@ -0,0 +1,196 @@
+import {
+ mustBeLongerThan,
+ mustIncludeLowercase,
+ mustIncludeNumbers,
+ mustIncludeSymbols,
+ mustIncludeUppercase,
+ mustMatchNewPassword,
+ mustNotBeEmpty,
+ mustNotIncludeUsername,
+ mustNotMatchCurrentPassword,
+ toggleValidator
+} from "./validators.js";
+
+type Opts = {
+ minLength: number;
+ minNumbers: number;
+ minSymbols: number;
+ minUppercase: number;
+ minLowercase: number;
+ passwordCanIncludeUsername: boolean;
+};
+
+export const init = (opts: Opts) => {
+ const successContainer = document.querySelector("div[data-purpose='successContainer']");
+ if (!successContainer) throw new Error("Could not find success container element");
+
+ const form = document.querySelector("#form");
+ if (!form) throw new Error("Could not find form element");
+
+ const submitButton = form.querySelector("& > div[data-purpose='submit'] > button[type='submit']");
+ if (!submitButton) throw new Error("Could not find submit button element");
+
+ const submitErrorContainer = form.querySelector(
+ "& > div[data-purpose='submit'] > div[data-purpose='errors']"
+ );
+ if (!submitErrorContainer) throw new Error("Could not find submit error container element");
+
+ type Field = [string, ((v: string) => string)[]];
+
+ const fieldsWithValidators = [
+ ["username", [mustNotBeEmpty]],
+ ["current", [mustNotBeEmpty]],
+ [
+ "new",
+ [
+ mustNotBeEmpty,
+ mustBeLongerThan(opts.minLength),
+ mustNotMatchCurrentPassword,
+ toggleValidator(mustNotIncludeUsername, !opts.passwordCanIncludeUsername),
+ mustIncludeNumbers(opts.minNumbers),
+ mustIncludeSymbols(opts.minSymbols),
+ mustIncludeUppercase(opts.minUppercase),
+ mustIncludeLowercase(opts.minLowercase)
+ ]
+ ],
+ ["new2", [mustNotBeEmpty, mustMatchNewPassword]]
+ ] satisfies Field[];
+
+ const fields = fieldsWithValidators.map(([name, validators]) => {
+ const f = form.querySelector(`#${name}`);
+ if (!f) throw new Error(`Field "${name}" does not exist`);
+
+ const inputContainer = f.querySelector('div[data-purpose="inputContainer"]');
+ if (!inputContainer) throw new Error(`Input container for "${name}" does not exist`);
+
+ const input = inputContainer.querySelector("input");
+ if (!input) throw new Error(`Input for "${name}" does not exist`);
+
+ const revealButton = inputContainer.querySelector('button[data-purpose="reveal"]');
+ if (!revealButton && input.type === "password") throw new Error(`Reveal button for "${name}" does not exist`);
+
+ const errorContainer = f.querySelector('div[data-purpose="errors"]');
+ if (!errorContainer) throw new Error(`Error for "${name}" does not exist`);
+
+ const getValue = () => input.value;
+ const setErrors = (errors: string[]) => {
+ errorContainer.innerHTML = "";
+
+ if (errors.length > 0) {
+ inputContainer.classList.add("border-red-500");
+ } else {
+ inputContainer.classList.remove("border-red-500");
+ }
+
+ for (const error of errors) {
+ const el = document.createElement("p");
+ el.innerText = error;
+
+ errorContainer.appendChild(el);
+ }
+ };
+
+ const validate = () => {
+ const value = getValue();
+
+ const errors = validators
+ .map((validate) => validate(value))
+ .reduce((acc, v) => {
+ if (v.length > 0) acc.push(v);
+
+ return acc;
+ }, [] as string[]);
+
+ console.log(`Validated "${name}": ${errors.length} error(s)`);
+
+ setErrors(errors);
+
+ return errors.length > 0;
+ };
+
+ if (revealButton) {
+ revealButton.onclick = (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ const newType = input.type === "password" ? "text" : "password";
+ const revealed = newType === "text";
+
+ console.log(`${revealed ? "Showing" : "Hiding"} content of "${name}"`);
+
+ input.type = newType;
+ f.dataset["revealed"] = revealed.toString();
+ };
+ }
+
+ return { input, errorContainer, getValue, validate };
+ });
+
+ const toggleFields = (enabled: boolean) => {
+ [submitButton, ...fields.map(({ input }) => input)].forEach((el) => (el.disabled = !enabled));
+ submitButton.dataset["loading"] = (!enabled).toString();
+ };
+
+ form.onsubmit = async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ const [username, oldPassword, newPassword] = fields.map((f) => f.getValue());
+
+ const hasErrors = fields.map(({ validate }) => validate()).some((e) => e === true);
+ submitButton.disabled = hasErrors;
+ if (hasErrors) return;
+
+ console.log("Changing password...");
+ toggleFields(false);
+
+ try {
+ const res = await fetch("/api/rpc", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify({
+ method: "change-password",
+ params: [username, oldPassword, newPassword]
+ })
+ });
+
+ const body = await res.text();
+
+ if (!res.ok) {
+ let err = body;
+
+ try {
+ const parsed = JSON.parse(body);
+
+ err = parsed.data[0];
+ } catch (e) {}
+
+ throw new Error(`An error occurred: ${err}`);
+ }
+
+ console.log("Changed successfully");
+
+ form.style.display = "none";
+ successContainer.style.display = "block";
+ } catch (e) {
+ console.error(e);
+
+ submitErrorContainer.innerText = (e as Error).message;
+
+ // Re-enable inputs but keep the submit button disabled,
+ // since we know that this isn't going to work. After the validators
+ // successfully re-run, it will enable the submit button again.
+ toggleFields(true);
+ submitButton.disabled = true;
+ }
+ };
+
+ form.onchange = (e) => {
+ e.stopPropagation();
+
+ const hasErrors = fields.map(({ validate }) => validate()).some((e) => e === true);
+ submitButton.disabled = hasErrors;
+ };
+};
diff --git a/internal/web/static/js/validators.ts b/internal/web/static/js/validators.ts
new file mode 100644
index 0000000..32e7bbd
--- /dev/null
+++ b/internal/web/static/js/validators.ts
@@ -0,0 +1,74 @@
+const specialCharacters = (() => {
+ // Generate an array of special characters according to the ASCII table:
+ // https://en.wikipedia.org/wiki/ASCII
+ const specialCharacters = [];
+
+ for (let i = "!".charCodeAt(0); i <= "/".charCodeAt(0); i++) {
+ specialCharacters.push(String.fromCharCode(i));
+ }
+
+ for (let i = ":".charCodeAt(0); i <= "@".charCodeAt(0); i++) {
+ specialCharacters.push(String.fromCharCode(i));
+ }
+
+ for (let i = "[".charCodeAt(0); i <= "`".charCodeAt(0); i++) {
+ specialCharacters.push(String.fromCharCode(i));
+ }
+
+ for (let i = "{".charCodeAt(0); i <= "~".charCodeAt(0); i++) {
+ specialCharacters.push(String.fromCharCode(i));
+ }
+
+ return specialCharacters;
+})();
+const specialCharsString = specialCharacters.join(", ");
+
+const pluralize = (singular: string, amount: number) => (amount === 1 ? singular : singular + "s");
+
+const form = document.querySelector("#form");
+if (!form) throw new Error("Could not find form element");
+
+const submitButton = form.querySelector("button[type='submit']");
+if (!submitButton) throw new Error("Could not find submit button element");
+
+export const mustNotBeEmpty = (v: string) => (v.length === 0 ? "The input must not be empty" : "");
+export const mustBeLongerThan = (minLength: number) => (v: string) =>
+ v.length < minLength ? `The input must be at least ${minLength} ${pluralize("character", minLength)} long` : "";
+export const mustIncludeNumbers = (amount: number) => (v: string) =>
+ v.split("").filter((c) => !isNaN(+c)).length < amount
+ ? `The input must include at least ${amount} ${pluralize("number", amount)}`
+ : "";
+export const mustIncludeSymbols = (amount: number) => (v: string) =>
+ v.split("").filter((c) => specialCharacters.includes(c)).length < amount
+ ? `The input must include at least ${amount} ${pluralize("symbol", amount)}: ${specialCharsString}}`
+ : "";
+export const mustIncludeUppercase = (amount: number) => (v: string) =>
+ v.split("").filter((c) => c === c.toUpperCase() && c !== c.toLowerCase()).length < amount
+ ? `The input must include at least ${amount} uppercase ${pluralize("character", amount)}`
+ : "";
+export const mustIncludeLowercase = (amount: number) => (v: string) =>
+ v.split("").filter((c) => c === c.toLowerCase() && c !== c.toUpperCase()).length < amount
+ ? `The input must include at least ${amount} lowercase ${pluralize("character", amount)}`
+ : "";
+
+export const mustMatchNewPassword = (v: string) => {
+ const passwordInput = form.querySelector(`#new input`);
+ if (!passwordInput) throw new Error("Could not find password input element");
+
+ return passwordInput.value !== v ? "The input must match the new password" : "";
+};
+export const mustNotMatchCurrentPassword = (v: string) => {
+ const passwordInput = form.querySelector(`#current input`);
+ if (!passwordInput) throw new Error("Could not find password input element");
+
+ return passwordInput.value === v ? "The input must not match the current password" : "";
+};
+export const mustNotIncludeUsername = (v: string) => {
+ const passwordInput = form.querySelector(`#username input`);
+ if (!passwordInput) throw new Error("Could not find username input element");
+
+ return v.includes(passwordInput.value) ? "The input must not include the username" : "";
+};
+
+export const toggleValidator = (validate: (v: string) => string, enabled: boolean) => (v: string) =>
+ enabled ? validate(v) : "";
diff --git a/internal/web/static/logo.webp b/internal/web/static/logo.webp
new file mode 100644
index 0000000..9f91bcc
Binary files /dev/null and b/internal/web/static/logo.webp differ
diff --git a/internal/web/static/mstile-150x150.png b/internal/web/static/mstile-150x150.png
new file mode 100644
index 0000000..94b174b
Binary files /dev/null and b/internal/web/static/mstile-150x150.png differ
diff --git a/internal/web/static/safari-pinned-tab.svg b/internal/web/static/safari-pinned-tab.svg
new file mode 100644
index 0000000..1b8797c
--- /dev/null
+++ b/internal/web/static/safari-pinned-tab.svg
@@ -0,0 +1,71 @@
+
+
+
diff --git a/internal/web/static/site.webmanifest b/internal/web/static/site.webmanifest
new file mode 100644
index 0000000..4bab644
--- /dev/null
+++ b/internal/web/static/site.webmanifest
@@ -0,0 +1,20 @@
+{
+ "name": "LDAP Password Changer",
+ "short_name": "Password Changer",
+ "icons": [
+ {
+ "src": "/android-chrome-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ },
+ {
+ "src": "/android-chrome-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ],
+ "theme_color": "#b8e9f4",
+ "background_color": "#b8e9f4",
+ "display": "standalone",
+ "orientation": "portrait"
+}
diff --git a/internal/web/static/static.go b/internal/web/static/static.go
new file mode 100644
index 0000000..04f73a7
--- /dev/null
+++ b/internal/web/static/static.go
@@ -0,0 +1,6 @@
+package static
+
+import "embed"
+
+//go:embed *.css js/*.js *.png *.ico *.svg *.webp site.webmanifest browserconfig.xml
+var Static embed.FS
diff --git a/internal/web/tailwind.css b/internal/web/tailwind.css
new file mode 100644
index 0000000..e241530
--- /dev/null
+++ b/internal/web/tailwind.css
@@ -0,0 +1,5 @@
+/* This file is an entrypoint for the TailwindCSS compiler */
+
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
diff --git a/internal/web/templates.go b/internal/web/templates.go
new file mode 100644
index 0000000..870d801
--- /dev/null
+++ b/internal/web/templates.go
@@ -0,0 +1,38 @@
+package web
+
+import (
+ "embed"
+)
+
+//go:embed views layouts
+var templates embed.FS
+
+type InputOpts struct {
+ Name string
+ Placeholder string
+ Type string
+ Autocomplete string
+}
+
+func tplInputOpts(name, placeholder, type_, autocomplete string) InputOpts {
+ if type_ != "password" && type_ != "text" {
+ panic("InputOpts type must be either `password` or `text`")
+ }
+
+ return InputOpts{
+ name,
+ placeholder,
+ type_,
+ autocomplete,
+ }
+}
+
+const NavbarItemBaseClass = "px-2 py-1 "
+
+func tplNavbarActive(activeTab, tab string) string {
+ if activeTab == tab {
+ return NavbarItemBaseClass + "text-white font-bold bg-gray-700 rounded-md"
+ }
+
+ return NavbarItemBaseClass
+}
diff --git a/internal/web/users.go b/internal/web/users.go
new file mode 100644
index 0000000..5e6c999
--- /dev/null
+++ b/internal/web/users.go
@@ -0,0 +1,59 @@
+package web
+
+import (
+ "net/url"
+
+ "github.com/gofiber/fiber/v2"
+)
+
+func (a *App) usersHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ if sess.Fresh() {
+ return c.Redirect("/login")
+ }
+
+ users := a.ldapCache.FindUsers()
+
+ return c.Render("views/users", fiber.Map{
+ "session": sess,
+ "title": "All users",
+ "activePage": "/users",
+ "headscripts": "",
+ "users": users,
+ }, "layouts/logged-in")
+}
+
+func (a *App) userHandler(c *fiber.Ctx) error {
+ sess, err := a.sessionStore.Get(c)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ if sess.Fresh() {
+ return c.Redirect("/login")
+ }
+
+ userDN, err := url.PathUnescape(c.Params("userDN"))
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ thinUser, err := a.ldapCache.FindUserByDN(userDN)
+ if err != nil {
+ return handle500(c, err)
+ }
+
+ user := a.ldapCache.PopulateGroupsForUser(&thinUser)
+
+ return c.Render("views/user", fiber.Map{
+ "session": sess,
+ "title": "All users",
+ "activePage": "/users",
+ "headscripts": "",
+ "user": user,
+ }, "layouts/logged-in")
+}
diff --git a/internal/web/views/404.html b/internal/web/views/404.html
new file mode 100644
index 0000000..fba0b2a
--- /dev/null
+++ b/internal/web/views/404.html
@@ -0,0 +1,10 @@
+