job "authelia" {
  group "authelia" {
    network {
      mode = "bridge"
      port "http" {
        static = 9091
      }
    }

    service {
      connect {
        sidecar_service {
          proxy {
            upstreams {
              destination_name = "postgres"
              local_bind_port  = 5432
            }
          }
        }
      }
    }

    service {
      name = "auth"
      port = "http"

      tags = [
        "traefik.enable=true",
      ]

      connect {
        sidecar_service {}
      }

      check {
        type     = "http"
        path     = "/health"
        interval = "10s"
        timeout  = "2s"
      }
    }

    task "authelia" {
      driver = "docker"

      config {
        image = "authelia/authelia:latest"

        ports = ["http"]

        volumes = [
          "local/config:/config",
          "local/data:/data" # TODO: Move this to a volume
        ]
      }

      resources {
        cpu    = 100
        memory = 128
      }

      template {
        data = <<EOF
server:
  address: tcp://0.0.0.0:{{ env "NOMAD_PORT_http" }}/
  endpoints:
    authz:
      forward-auth:
        implementation: 'ForwardAuth'
        authn_strategies:
          - name: 'CookieSession'
theme: "auto"
identity_validation:
  reset_password:
    jwt_secret: "{{ with nomadVar "nomad/jobs/authelia" }}{{ .jwt_secret }}{{ end }}"

authentication_backend:
  file:
    path: /config/users_database.yml

access_control:
  default_policy: deny
  rules:
    - domain: "*.othrayte.one"
      policy: one_factor

session:
  name: authelia_session
  secret: "{{ with nomadVar "nomad/jobs/authelia" }}{{ .session_secret }}{{ end }}"
  inactivity: '2 days and 9 hours'
  expiration: '1 hour'
  remember_me: '90 days'
  cookies:
    - domain: othrayte.one
      authelia_url: "https://auth.othrayte.one"

storage:
  encryption_key: "{{ with nomadVar "nomad/jobs/authelia" }}{{ .encryption_key }}{{ end }}"
  postgres:
    address: 'tcp://127.0.0.1:5432'
    database: 'authelia'
    schema: 'public'
    username: 'authelia'
    password: '{{ with nomadVar "nomad/jobs/authelia" }}{{ .database_pw }}{{ end }}'
    timeout: '5s'

notifier:
  filesystem:
    filename: /config/notification.txt
EOF

        destination = "local/config/configuration.yml"
      }

      template {
        data = <<EOF
# Users database for Authelia
users:
  othrayte:
    password: "$2y$10$FeemMJevZXq6y1pc6FNOXeIlthGWiGHRmMfpV33BNcpChA5ozLUmK"
    displayname: "Adrian"
    email: "othrayte@gmail.com"
EOF

        destination = "local/config/users_database.yml"
      }
    }
  }
}
