Compare commits

..

10 Commits

Author SHA1 Message Date
Guwan d30582faa5 1 2025-09-02 00:02:19 +08:00
Denis CLAVIER 52682cae68 Fix database config because Mattermost Preview migrated to Postgres 2024-03-24 15:09:09 +04:00
Denis CLAVIER c65ae73d1d Fix Postgres 15 permission denied issue 2023-04-04 13:09:14 +04:00
Denis CLAVIER e7efc7da13
Merge pull request #92 from WanpengQian/master
Some adjustments
2022-08-23 07:18:42 +02:00
Sen Manho 2a775074b9 Using displayName instead of cn for Full Name 2022-05-18 23:16:32 +09:00
Sen Manho 7a0d14f23d Do not check password minimal length 2022-05-18 23:05:52 +09:00
Sen Manho 18d958858b Adjust login page's style. 2022-05-18 22:21:14 +09:00
Denis CLAVIER 8f1f233794 Replace localhost with DNS entries in docker-compose - fix #91 2022-03-31 23:58:10 +02:00
Denis CLAVIER 04f46615ff Migrate from Apache to Nginx - Add HTTPS support - fix #80 2021-12-10 19:09:23 +01:00
Denis CLAVIER 1dda14438d Patch demo for Mattermost Desktop >= 4.7 (#80) 2021-11-24 16:32:18 +01:00
21 changed files with 678 additions and 504 deletions

3
.gitignore vendored
View File

@ -1,4 +1,7 @@
config_init.sh
config_ldap.php
config_db.php
data
certs
.idea

View File

@ -3,9 +3,9 @@ Install using containers - Docker/Podman
The easiest way to setup Mattermost-LDAP is using the docker-compose implementation.
For production use, you must use the `docker-copose.yaml` file available at the root of this repository. Unlike the Demo, this docker-compose file only setup Mattermost-LDAP with an Apache server and a PostgreSQL database.
For production use, you must use the [`docker-compose.yaml`](https://github.com/Crivaledaz/Mattermost-LDAP/blob/master/docker-compose.yaml) file available at the root of this repository. Unlike the Demo, this docker-compose file only setup Mattermost-LDAP with an Nginx server linked to a PHP engine and a PostgreSQL database.
This implementation uses an embedded Oauth server, which can be configured by environment variables.
This implementation uses the repository Oauth server, which can be configured by environment variables.
## Requirements
@ -17,42 +17,33 @@ For more information about Podman installation, see official documentation : htt
## Preparation
First, you need to clone (or download and extract) this repository on your server :
First, you need to clone (or download and extract) this repository on your server with:
```bash
git clone https://github.com/Crivaledaz/Mattermost-LDAP
cd Mattermost-LDAP
```
Then, before running the docker-compose file, you need to adapt LDAP and DB parameters. All parameters are gathered in the `env.example` file and they are passed to Postgres and Oauth server by environment variables.
Then, before running the docker-compose file, you need to adapt LDAP and DB parameters. All parameters are gathered in `environment` sections in the [`docker-compose.yaml`](https://github.com/Crivaledaz/Mattermost-LDAP/blob/master/docker-compose.yaml) file and they are passed to Postgres and Oauth server by environment variables.
Copy the `env.example` file to `.env` and edit it to change with your values.
You must edit the docker-compose file to adapt parameters with your values.
**Warning** : Postgres root password and database Oauth password must be changed. Client and secret tokens must be generated randomly, using `openssl rand -hex 32`.
For more information about available parameters, refer to the [configuration section](https://github.com/Crivaledaz/Mattermost-LDAP#configuration) of the repository README.
Otherwise, for production, you need to create a directory to store PostgreSQL data. This directory will contain the Oauth database and allows data persistence, even if containers are stopped or restarted. By default, this Mattermost-LDAP implementation uses folder `data/` next to the `docker-compose.yaml` file to store data. This folder need to be created before running Docker compose :
```bash
mkdir data
```
To use Mattermost-LDAP with your own Mattermost server, you need to configure your Mattermost instance as described in section "Configure Mattermost".
To use Mattermost-LDAP with your own Mattermost server, you need to configure your Mattermost instance as described in section "Configure Mattermost" below.
## Configure Mattermost
Active Gitlab authentication in `System Console > Gitlab` (or `config.json`) and fill application id and secret with the two tokens got during install section. For the next fields use this :
Active Gitlab authentication in Mattermost configuration and fill GitLab parameters, with your values. To do this, you need to edit the `config.json` file or change parameters in Mattermost configuration table if you use configuration in the database.
```
User API Endpoint : http://HOSTNAME/oauth/resource.php
Auth Endpoint: http://HOSTNAME/oauth/authorize.php
Token Endpoint: http://HOSTNAME/oauth/token.php
```
Change `HOSTNAME` by hostname or ip of the server where you have installed Mattermost-LDAP module.
Since Mattermost 4.9, these fields are disabled in admin panel, so you need to edit directly section `GitLabSettings` in the Mattermost configuration file `config.json`.
In the `config.json` file, GitLab configuration is gathered in the section `GitLabSettings`. You have to enable it and to fill parameters with your values. Once completed, the section should look like :
In the `config.json` file, GitLab configuration is gathered in the section `GitLabSettings`. Adapt this section with your values, it should seems like this :
```
"GitLabSettings": {
@ -60,32 +51,50 @@ In the `config.json` file, GitLab configuration is gathered in the section `GitL
"Secret": "fedcba987654321fedcba987654321",
"Id": "123456789abcdef123456789abcdef",
"Scope": "",
"AuthEndpoint": "http://localhost/oauth/authorize.php",
"TokenEndpoint": "http://localhost/oauth/token.php",
"UserApiEndpoint": "http://localhost/oauth/resource.php"
"AuthEndpoint": "https://<HOSTNAME>/oauth/authorize.php",
"TokenEndpoint": "https://<HOSTNAME>/oauth/token.php",
"UserApiEndpoint": "https://<HOSTNAME>/oauth/resource.php"
},
```
*Note* : You need to restart the Mattermost server to take into account the change.
Change `<HOSTNAME>` by the hostname or ip of the server where you have installed Mattermost-LDAP module. The `Secret` and `Id` parameters should contain the tokens generated previously.
**Note** : You need to restart the Mattermost server to take into account the change.
## HTTPS configuration
Since Mattermost-LDAP version 2.1, HTTPS is enable by default to protect sensitive data exchanged between users and Mattermost-LDAP (LDAP username and password).
You need to provide a pair of TLS certificates and to store these in a directory named `certs`. To generate self-signed certificates you can use the following command :
```bash
mkdir certs
openssl req -x509 -newkey rsa:4096 -sha256 -days 364 -nodes -keyout certs/key.pem -out certs/cert.pem -subj '/CN=<HOSTNAME>' -extensions san -config <( echo '[req]'; echo 'distinguished_name=req'; echo '[san]'; echo 'subjectAltName=DNS:localhost,<HOSTNAME>')
```
Replace `<HOSTNAME>` by the hostname serving the Oauth server (ie: the server where you have installed Mattermost-LDAP).
**Remark** : By default, Mattermost does not trust self-signed certificate. To remediate you need to add the certificate to the Mattermost server certificate bundle or change the parameter `EnableInsecureOutgoingConnection` to true in the Mattermost configuration (`config.json`).
Alternatively, you can use your own certificates and place them in the `certs` directory. This directory will be consumed by the Nginx container as a volume.
*Note* : Your certificates should be in PEM format and must be named `cert.pem` and `key.pem`, to match the Nginx configuration.
## Usage
Once the `.env` file have been adapted, you can run the docker-compose file with the following commands :
Once you have adapted environement paramters in the docker-compose file, you can run Mattermost-LDAP with the following commands (from the root of the repository) :
```bash
# With Docker
docker-compose build
docker-compose up -d
# With Podman
podman-compose build
podman-compose up -d
```
The build command allows Docker compose to build necessary image. Images use are available in the [Docker/](Docker) directory of this repository. The up command starts all services described in the Docker compose file.
The previous command starts all services described in the Docker compose file. The `-d` argument allows to start all container in background, in a detached mode.
Once all services are started, go to Mattermost server and click on GitLab button to login with LDAP credential on Mattermost-LDAP. Then, if you login successfully and authorize Mattermost-LDAP to transmit your data to Mattermost, you should be log on Mattermost.
To stop Mattermost server and Mattermost-LDAP, use the following command :
To stop Mattermost-LDAP, use the following command :
```bash
# With Docker
docker-compose down
@ -93,61 +102,3 @@ docker-compose down
# With Podman
podman-compose down
```
## Extension
### Additional information for usage with nginx-proxy, nginx-proxy-letsencrypt
In case you want to use `nginx-proxy`, `nginx-proxy-letsencrypt`, and (for example) `openldap`, it is possible to use subdomains for your services. Following this approach you could have mattermost running on on `https://chat.example.com` and authenticate via this container from `https://oauth.example.com`. This container will then have its own letsencypt certificate.
You can add the following settings to your configuration files for this type of setup.
In `docker-compose.yaml` :
```yaml
version: '3'
[...]
services:
mattermost-ldap:
[...]
expose:
- 80
- 443
environment:
[...]
- VIRTUAL_HOST=oauth.example.com,www.oauth.example.com
- LETSENCRYPT_HOST=oauth.example.com,www.oauth.example.com
[...]
```
In `.env`:
```bash
[...]
redirect_uri = "https://chat.example.com/signup/gitlab/complete"
ldap_filter = "(&(objectClass=inetOrgPerson)(memberof=cn=chat,ou=groups,dc=example,dc=com))"
[...]
```
This filter will additionally allow you to filter based on group affiliation within your LDAP server.
Finally, add the following to your mattermost `config.json` to ensure the correct redirect.
```json
"GitLabSettings": {
"Enable": true,
"Secret": "XXX",
"Id": "YYY",
"Scope": "",
"AuthEndpoint": "https://oauth.example.com/oauth/authorize.php",
"TokenEndpoint": "https://oauth.example.com/oauth/token.php",
"UserApiEndpoint": "https://oauth.example.com/oauth/resource.php"
},
```

View File

@ -11,6 +11,7 @@ uid: jdoe
cn: John DOE
sn: DOE
gn: John
displayName: John DOE
mail: john.doe@example.com
objectClass: inetOrgPerson
# Password : test1234

View File

@ -14,27 +14,28 @@
"UseLetsEncrypt": false,
"LetsEncryptCertificateCacheFile": "./config/letsencrypt.cache",
"Forward80To443": false,
"TrustedProxyIPHeader": [
"X-Forwarded-For",
"X-Real-IP"
],
"TrustedProxyIPHeader": [],
"ReadTimeout": 300,
"WriteTimeout": 300,
"IdleTimeout": 60,
"MaximumLoginAttempts": 10,
"GoroutineHealthThreshold": -1,
"GoogleDeveloperKey": "",
"EnableOAuthServiceProvider": false,
"EnableOAuthServiceProvider": true,
"EnableIncomingWebhooks": true,
"EnableOutgoingWebhooks": true,
"EnableOutgoingOAuthConnections": false,
"EnableCommands": true,
"EnableOnlyAdminIntegrations": true,
"OutgoingIntegrationRequestsTimeout": 30,
"EnablePostUsernameOverride": false,
"EnablePostIconOverride": false,
"EnableLinkPreviews": false,
"GoogleDeveloperKey": "",
"EnableLinkPreviews": true,
"EnablePermalinkPreviews": true,
"RestrictLinkPreviews": "",
"EnableTesting": false,
"EnableDeveloper": false,
"EnableOpenTracing": false,
"DeveloperFlags": "",
"EnableClientPerformanceDebugging": false,
"EnableSecurityFixAlert": true,
"EnableInsecureOutgoingConnections": false,
"AllowedUntrustedInternalConnections": "",
@ -46,81 +47,99 @@
"CorsAllowCredentials": false,
"CorsDebug": false,
"AllowCookiesForSubdomains": false,
"SessionLengthWebInDays": 30,
"SessionLengthMobileInDays": 30,
"ExtendSessionLengthWithActivity": false,
"TerminateSessionsOnPasswordChange": false,
"SessionLengthWebInDays": 180,
"SessionLengthWebInHours": 4320,
"SessionLengthMobileInDays": 180,
"SessionLengthMobileInHours": 4320,
"SessionLengthSSOInDays": 30,
"SessionLengthSSOInHours": 720,
"SessionCacheInMinutes": 10,
"SessionIdleTimeoutInMinutes": 0,
"SessionIdleTimeoutInMinutes": 43200,
"WebsocketSecurePort": 443,
"WebsocketPort": 80,
"WebserverMode": "gzip",
"EnableCustomEmoji": false,
"EnableGifPicker": true,
"GiphySdkKey": "",
"EnableCustomEmoji": true,
"EnableEmojiPicker": true,
"EnableGifPicker": false,
"GfycatApiKey": "2_KtH_W5",
"GfycatApiSecret": "3wLVZPiswc3DnaiaFoLkDvB4X0IV6CpMkj4tf2inJRsBY6-FnkT08zGmppWFgeof",
"RestrictCustomEmojiCreation": "all",
"RestrictPostDelete": "all",
"AllowEditPost": "always",
"PostEditTimeLimit": -1,
"TimeBetweenUserTypingUpdatesMilliseconds": 5000,
"EnableCrossTeamSearch": true,
"EnablePostSearch": true,
"EnableFileSearch": true,
"MinimumHashtagLength": 3,
"EnableUserTypingMessages": true,
"EnableChannelViewedMessages": true,
"EnableUserStatuses": true,
"ExperimentalEnableAuthenticationTransfer": true,
"ClusterLogTimeoutMilliseconds": 2000,
"CloseUnusedDirectMessages": false,
"EnablePreviewFeatures": true,
"EnableTutorial": true,
"EnableOnboardingFlow": true,
"ExperimentalEnableDefaultChannelLeaveJoinMessages": true,
"ExperimentalGroupUnreadChannels": "disabled",
"ExperimentalChannelOrganization": false,
"ExperimentalChannelSidebarOrganization": "disabled",
"ImageProxyType": "",
"ImageProxyURL": "",
"ImageProxyOptions": "",
"EnableAPITeamDeletion": false,
"EnableAPITriggerAdminNotifications": false,
"EnableAPIUserDeletion": false,
"EnableAPIPostDeletion": false,
"EnableDesktopLandingPage": true,
"ExperimentalEnableHardenedMode": false,
"DisableLegacyMFA": false,
"ExperimentalStrictCSRFEnforcement": false,
"EnableEmailInvitations": false,
"DisableBotsWhenOwnerIsDeactivated": true,
"EnableBotAccountCreation": false,
"EnableSVGs": true,
"EnableLatex": true
"EnableLatex": true,
"EnableInlineLatex": true,
"PostPriority": true,
"AllowPersistentNotifications": true,
"AllowPersistentNotificationsForGuests": false,
"PersistentNotificationIntervalMinutes": 5,
"PersistentNotificationMaxCount": 6,
"PersistentNotificationMaxRecipients": 5,
"EnableAPIChannelDeletion": false,
"EnableLocalMode": false,
"LocalModeSocketLocation": "/var/tmp/mattermost_local.socket",
"EnableAWSMetering": false,
"SplitKey": "",
"FeatureFlagSyncIntervalSeconds": 30,
"DebugSplit": false,
"ThreadAutoFollow": true,
"CollapsedThreads": "always_on",
"ManagedResourcePaths": "",
"EnableCustomGroups": true,
"AllowSyncedDrafts": true,
"UniqueEmojiReactionLimitPerPost": 50,
"RefreshPostStatsRunTime": "00:00",
"MaximumPayloadSizeBytes": 100000,
"MaximumURLLength": 2048,
"ScheduledPosts": true,
"EnableWebHubChannelIteration": false,
"FrameAncestors": "",
"DeleteAccountLink": ""
},
"TeamSettings": {
"SiteName": "Mattermost",
"MaxUsersPerTeam": 50,
"EnableTeamCreation": true,
"EnableJoinLeaveMessageByDefault": true,
"EnableUserCreation": true,
"EnableOpenServer": false,
"EnableUserDeactivation": false,
"RestrictCreationToDomains": "",
"EnableCustomUserStatuses": true,
"EnableCustomBrand": false,
"CustomBrandText": "",
"CustomDescriptionText": "",
"RestrictDirectMessage": "any",
"RestrictTeamInvite": "all",
"RestrictPublicChannelManagement": "all",
"RestrictPrivateChannelManagement": "all",
"RestrictPublicChannelCreation": "all",
"RestrictPrivateChannelCreation": "all",
"RestrictPublicChannelDeletion": "all",
"RestrictPrivateChannelDeletion": "all",
"RestrictPrivateChannelManageMembers": "all",
"EnableXToLeaveChannelsFromLHS": false,
"EnableLastActiveTime": true,
"UserStatusAwayTimeout": 300,
"MaxChannelsPerTeam": 2000,
"MaxNotificationsPerChannel": 1000000,
"MaxNotificationsPerChannel": 1000,
"EnableConfirmNotificationsToChannel": true,
"TeammateNameDisplay": "username",
"ExperimentalViewArchivedChannels": false,
"ExperimentalViewArchivedChannels": true,
"ExperimentalEnableAutomaticReplies": false,
"ExperimentalHideTownSquareinLHS": false,
"ExperimentalTownSquareIsReadOnly": false,
"LockTeammateNameDisplay": false,
"ExperimentalPrimaryTeam": "",
"ExperimentalDefaultChannels": []
@ -128,85 +147,116 @@
"ClientRequirements": {
"AndroidLatestVersion": "",
"AndroidMinVersion": "",
"DesktopLatestVersion": "",
"DesktopMinVersion": "",
"IosLatestVersion": "",
"IosMinVersion": ""
},
"SqlSettings": {
"DriverName": "mysql",
"DataSource": "mmuser:mostest@tcp(localhost:3306)/mattermost_test?charset=utf8mb4,utf8",
"DriverName": "postgres",
"DataSource": "postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable\u0026connect_timeout=10\u0026binary_parameters=yes",
"DataSourceReplicas": [],
"DataSourceSearchReplicas": [],
"MaxIdleConns": 20,
"ConnMaxLifetimeMilliseconds": 3600000,
"ConnMaxIdleTimeMilliseconds": 300000,
"MaxOpenConns": 300,
"Trace": false,
"AtRestEncryptKey": "95ps7omhzmhusdfqh5bki5ye4xfd4hgw",
"QueryTimeout": 30
"AtRestEncryptKey": "73i1z9pkuxx93ad4jcey333ta5o7gid8",
"QueryTimeout": 30,
"DisableDatabaseSearch": false,
"MigrationsStatementTimeoutSeconds": 100000,
"ReplicaLagSettings": [],
"ReplicaMonitorIntervalSeconds": 5
},
"LogSettings": {
"EnableConsole": true,
"ConsoleLevel": "DEBUG",
"ConsoleJson": true,
"EnableColor": false,
"EnableFile": true,
"FileLevel": "INFO",
"FileJson": true,
"FileLocation": "",
"EnableWebhookDebugging": true,
"EnableDiagnostics": true
"EnableDiagnostics": true,
"VerboseDiagnostics": false,
"EnableSentry": true,
"AdvancedLoggingJSON": {},
"MaxFieldSize": 2048
},
"ExperimentalAuditSettings": {
"SysLogEnabled": false,
"SysLogIP": "localhost",
"SysLogPort": 6514,
"SysLogTag": "",
"SysLogCert": "",
"SysLogInsecure": false,
"SysLogMaxQueueSize": 1000,
"FileEnabled": false,
"FileName": "",
"FileMaxSizeMB": 100,
"FileMaxAgeDays": 0,
"FileMaxBackups": 0,
"FileCompress": false,
"FileMaxQueueSize": 1000
"FileMaxQueueSize": 1000,
"AdvancedLoggingJSON": {},
"Certificate": ""
},
"NotificationLogSettings": {
"EnableConsole": true,
"ConsoleLevel": "DEBUG",
"ConsoleJson": true,
"EnableColor": false,
"EnableFile": true,
"FileLevel": "INFO",
"FileJson": true,
"FileLocation": ""
"FileLocation": "",
"AdvancedLoggingJSON": {}
},
"PasswordSettings": {
"MinimumLength": 5,
"MinimumLength": 8,
"Lowercase": false,
"Number": false,
"Uppercase": false,
"Symbol": false
"Symbol": false,
"EnableForgotLink": true
},
"FileSettings": {
"EnableFileAttachments": true,
"EnableMobileUpload": true,
"EnableMobileDownload": true,
"MaxFileSize": 52428800,
"MaxFileSize": 104857600,
"MaxImageResolution": 33177600,
"MaxImageDecoderConcurrency": -1,
"DriverName": "local",
"Directory": "/mm/mattermost-data/",
"EnablePublicLink": false,
"PublicLinkSalt": "g3w9kzz9ewg1bskanhruqorygm81rp7j",
"ExtractContent": true,
"ArchiveRecursion": false,
"PublicLinkSalt": "6xzurkkqaebfptiaw49ubjeyq5megscz",
"InitialFont": "nunito-bold.ttf",
"AmazonS3AccessKeyId": "",
"AmazonS3SecretAccessKey": "",
"AmazonS3Bucket": "",
"AmazonS3PathPrefix": "",
"AmazonS3Region": "",
"AmazonS3Endpoint": "s3.amazonaws.com",
"AmazonS3SSL": true,
"AmazonS3SignV2": false,
"AmazonS3SSE": false,
"AmazonS3Trace": false
"AmazonS3Trace": false,
"AmazonS3RequestTimeoutMilliseconds": 30000,
"AmazonS3UploadPartSizeBytes": 5242880,
"AmazonS3StorageClass": "",
"DedicatedExportStore": false,
"ExportDriverName": "local",
"ExportDirectory": "./data/",
"ExportAmazonS3AccessKeyId": "",
"ExportAmazonS3SecretAccessKey": "",
"ExportAmazonS3Bucket": "",
"ExportAmazonS3PathPrefix": "",
"ExportAmazonS3Region": "",
"ExportAmazonS3Endpoint": "s3.amazonaws.com",
"ExportAmazonS3SSL": true,
"ExportAmazonS3SignV2": false,
"ExportAmazonS3SSE": false,
"ExportAmazonS3Trace": false,
"ExportAmazonS3RequestTimeoutMilliseconds": 30000,
"ExportAmazonS3PresignExpiresSeconds": 21600,
"ExportAmazonS3UploadPartSizeBytes": 104857600,
"ExportAmazonS3StorageClass": ""
},
"EmailSettings": {
"EnableSignUpWithEmail": false,
@ -229,15 +279,16 @@
"SendPushNotifications": false,
"PushNotificationServer": "",
"PushNotificationContents": "generic",
"PushNotificationBuffer": 1000,
"EnableEmailBatching": false,
"EmailBatchingBufferSize": 256,
"EmailBatchingInterval": 30,
"EnablePreviewModeBanner": true,
"SkipServerCertificateVerification": false,
"EmailNotificationContentsType": "full",
"LoginButtonColor": "",
"LoginButtonBorderColor": "",
"LoginButtonTextColor": ""
"LoginButtonColor": "#0000",
"LoginButtonBorderColor": "#2389D7",
"LoginButtonTextColor": "#2389D7"
},
"RateLimitSettings": {
"Enable": false,
@ -253,21 +304,31 @@
"ShowFullName": true
},
"SupportSettings": {
"TermsOfServiceLink": "https://about.mattermost.com/default-terms/",
"PrivacyPolicyLink": "https://about.mattermost.com/default-privacy-policy/",
"AboutLink": "https://about.mattermost.com/default-about/",
"HelpLink": "https://about.mattermost.com/default-help/",
"ReportAProblemLink": "https://about.mattermost.com/default-report-a-problem/",
"SupportEmail": "feedback@mattermost.com",
"TermsOfServiceLink": "https://mattermost.com/pl/terms-of-use/",
"PrivacyPolicyLink": "https://mattermost.com/pl/privacy-policy/",
"AboutLink": "https://mattermost.com/pl/about-mattermost",
"HelpLink": "https://mattermost.com/pl/help/",
"ReportAProblemLink": "https://mattermost.com/pl/report-a-bug",
"ReportAProblemType": "default",
"ReportAProblemMail": "",
"AllowDownloadLogs": true,
"ForgotPasswordLink": "",
"SupportEmail": "",
"CustomTermsOfServiceEnabled": false,
"CustomTermsOfServiceReAcceptancePeriod": 365
"CustomTermsOfServiceReAcceptancePeriod": 365,
"EnableAskCommunityLink": true
},
"AnnouncementSettings": {
"EnableBanner": false,
"BannerText": "",
"BannerColor": "#f2a93b",
"BannerTextColor": "#333333",
"AllowBannerDismissal": true
"AllowBannerDismissal": true,
"AdminNoticesEnabled": true,
"UserNoticesEnabled": true,
"NoticesURL": "https://notices.mattermost.com/",
"NoticesFetchFrequency": 3600,
"NoticesSkipCache": false
},
"ThemeSettings": {
"EnableThemeSelection": true,
@ -277,12 +338,15 @@
},
"GitLabSettings": {
"Enable": true,
"Secret": "fedcba987654321fedcba987654321",
"Id": "123456789abcdef123456789abcdef",
"Secret": "987654321",
"Id": "123456789",
"Scope": "",
"AuthEndpoint": "http://localhost/oauth/authorize.php",
"TokenEndpoint": "http://localhost/oauth/token.php",
"UserApiEndpoint": "http://localhost/oauth/resource.php"
"AuthEndpoint": "http://localhost/oauth/authorize",
"TokenEndpoint": "http://webserver/oauth/token.php",
"UserAPIEndpoint": "http://webserver/oauth/resource.php",
"DiscoveryEndpoint": "",
"ButtonText": "",
"ButtonColor": ""
},
"GoogleSettings": {
"Enable": false,
@ -291,7 +355,10 @@
"Scope": "profile email",
"AuthEndpoint": "https://accounts.google.com/o/oauth2/v2/auth",
"TokenEndpoint": "https://www.googleapis.com/oauth2/v4/token",
"UserApiEndpoint": "https://www.googleapis.com/plus/v1/people/me"
"UserAPIEndpoint": "https://people.googleapis.com/v1/people/me?personFields=names,emailAddresses,nicknames,metadata",
"DiscoveryEndpoint": "",
"ButtonText": "",
"ButtonColor": ""
},
"Office365Settings": {
"Enable": false,
@ -300,9 +367,22 @@
"Scope": "User.Read",
"AuthEndpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
"TokenEndpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
"UserApiEndpoint": "https://graph.microsoft.com/v1.0/me",
"UserAPIEndpoint": "https://graph.microsoft.com/v1.0/me",
"DiscoveryEndpoint": "",
"DirectoryId": ""
},
"OpenIdSettings": {
"Enable": false,
"Secret": "",
"Id": "",
"Scope": "profile openid email",
"AuthEndpoint": "",
"TokenEndpoint": "",
"UserAPIEndpoint": "",
"DiscoveryEndpoint": "",
"ButtonText": "",
"ButtonColor": "#145DBF"
},
"LdapSettings": {
"Enable": false,
"EnableSync": false,
@ -312,6 +392,7 @@
"BaseDN": "",
"BindUsername": "",
"BindPassword": "",
"MaximumLoginAttempts": 10,
"UserFilter": "",
"GroupFilter": "",
"GuestFilter": "",
@ -327,36 +408,43 @@
"IdAttribute": "",
"PositionAttribute": "",
"LoginIdAttribute": "",
"PictureAttribute": "",
"SyncIntervalMinutes": 60,
"ReAddRemovedMembers": false,
"SkipCertificateVerification": false,
"PublicCertificateFile": "",
"PrivateKeyFile": "",
"QueryTimeout": 60,
"MaxPageSize": 0,
"LoginFieldName": "",
"LoginButtonColor": "",
"LoginButtonBorderColor": "",
"LoginButtonTextColor": "",
"Trace": false
"LoginButtonColor": "#0000",
"LoginButtonBorderColor": "#2389D7",
"LoginButtonTextColor": "#2389D7"
},
"ComplianceSettings": {
"Enable": false,
"Directory": "./data/",
"EnableDaily": false
"EnableDaily": false,
"BatchSize": 30000
},
"LocalizationSettings": {
"DefaultServerLocale": "en",
"DefaultClientLocale": "en",
"AvailableLocales": ""
"AvailableLocales": "",
"EnableExperimentalLocales": false
},
"SamlSettings": {
"Enable": false,
"EnableSyncWithLdap": false,
"EnableSyncWithLdapIncludeAuth": false,
"IgnoreGuestsLdapSync": false,
"Verify": true,
"Encrypt": true,
"SignRequest": false,
"IdpUrl": "",
"IdpDescriptorUrl": "",
"IdpMetadataUrl": "",
"IdpURL": "",
"IdpDescriptorURL": "",
"IdpMetadataURL": "",
"ServiceProviderIdentifier": "",
"AssertionConsumerServiceURL": "",
"SignatureAlgorithm": "RSAwithSHA1",
"CanonicalAlgorithm": "Canonical1.0",
@ -376,15 +464,33 @@
"NicknameAttribute": "",
"LocaleAttribute": "",
"PositionAttribute": "",
"LoginButtonText": "With SAML",
"LoginButtonColor": "",
"LoginButtonBorderColor": "",
"LoginButtonTextColor": ""
"LoginButtonText": "SAML",
"LoginButtonColor": "#34a28b",
"LoginButtonBorderColor": "#2389D7",
"LoginButtonTextColor": "#ffffff"
},
"NativeAppSettings": {
"AppDownloadLink": "https://about.mattermost.com/downloads/",
"AndroidAppDownloadLink": "https://about.mattermost.com/mattermost-android-app/",
"IosAppDownloadLink": "https://about.mattermost.com/mattermost-ios-app/"
"AppCustomURLSchemes": [
"mmauth://",
"mmauthbeta://"
],
"AppDownloadLink": "https://mattermost.com/pl/download-apps",
"AndroidAppDownloadLink": "https://mattermost.com/pl/android-app/",
"IosAppDownloadLink": "https://mattermost.com/pl/ios-app/",
"MobileExternalBrowser": false,
"MobileEnableBiometrics": false,
"MobilePreventScreenCapture": false,
"MobileJailbreakProtection": false,
"MobileEnableSecureFilePreview": false,
"MobileAllowPdfLinkNavigation": false
},
"CacheSettings": {
"CacheType": "lru",
"RedisAddress": "",
"RedisPassword": "********************************",
"RedisDB": -1,
"RedisCachePrefix": "",
"DisableClientCache": false
},
"ClusterSettings": {
"Enable": false,
@ -393,33 +499,42 @@
"NetworkInterface": "",
"BindAddress": "",
"AdvertiseAddress": "",
"UseIpAddress": true,
"UseExperimentalGossip": false,
"UseIPAddress": true,
"EnableGossipCompression": true,
"EnableExperimentalGossipEncryption": false,
"EnableGossipEncryption": false,
"ReadOnlyConfig": true,
"GossipPort": 8074,
"StreamingPort": 8075,
"MaxIdleConns": 100,
"MaxIdleConnsPerHost": 128,
"IdleConnTimeoutMilliseconds": 90000
"GossipPort": 8074
},
"MetricsSettings": {
"Enable": false,
"BlockProfileRate": 0,
"ListenAddress": ":8067"
"ListenAddress": ":8067",
"EnableClientMetrics": true,
"EnableNotificationMetrics": true,
"ClientSideUserIds": []
},
"ExperimentalSettings": {
"ClientSideCertEnable": false,
"ClientSideCertCheck": "secondary",
"EnableClickToReply": false,
"LinkMetadataTimeoutMilliseconds": 5000,
"RestrictSystemAdmin": false,
"UseNewSAMLLibrary": false
"EnableSharedChannels": false,
"EnableRemoteClusterService": false,
"DisableAppBar": false,
"DisableRefetchingOnBrowserFocus": false,
"DelayChannelAutocomplete": false,
"DisableWakeUpReconnectHandler": false,
"UsersStatusAndProfileFetchingPollIntervalMilliseconds": 3000,
"YoutubeReferrerPolicy": false,
"ExperimentalChannelCategorySorting": false
},
"AnalyticsSettings": {
"MaxUsersForStatistics": 2500
},
"ElasticsearchSettings": {
"ConnectionUrl": "",
"ConnectionURL": "",
"Backend": "elasticsearch",
"Username": "elastic",
"Password": "changeme",
"EnableIndexing": false,
@ -435,18 +550,38 @@
"AggregatePostsAfterDays": 365,
"PostsAggregatorJobStartTime": "03:00",
"IndexPrefix": "",
"GlobalSearchPrefix": "",
"LiveIndexingBatchSize": 1,
"BulkIndexingTimeWindowSeconds": 3600,
"BatchSize": 10000,
"RequestTimeoutSeconds": 30,
"SkipTLSVerification": false,
"Trace": ""
"CA": "",
"ClientCert": "",
"ClientKey": "",
"Trace": "",
"IgnoredPurgeIndexes": ""
},
"BleveSettings": {
"IndexDir": "",
"EnableIndexing": false,
"EnableSearching": false,
"EnableAutocomplete": false,
"BatchSize": 10000
},
"DataRetentionSettings": {
"EnableMessageDeletion": false,
"EnableFileDeletion": false,
"EnableBoardsDeletion": false,
"MessageRetentionDays": 365,
"MessageRetentionHours": 0,
"FileRetentionDays": 365,
"DeletionJobStartTime": "02:00"
"FileRetentionHours": 0,
"BoardsRetentionDays": 365,
"DeletionJobStartTime": "02:00",
"BatchSize": 3000,
"TimeBetweenBatchesMilliseconds": 100,
"RetentionIdsBatchSize": 100,
"PreservePinnedPosts": false
},
"MessageExportSettings": {
"EnableExport": false,
@ -454,43 +589,98 @@
"DailyRunTime": "01:00",
"ExportFromTimestamp": 0,
"BatchSize": 10000,
"DownloadExportResults": false,
"ChannelBatchSize": 100,
"ChannelHistoryBatchSize": 10,
"GlobalRelaySettings": {
"CustomerType": "A9",
"SmtpUsername": "",
"SmtpPassword": "",
"EmailAddress": ""
"SMTPUsername": "",
"SMTPPassword": "",
"EmailAddress": "",
"SMTPServerTimeout": 1800,
"CustomSMTPServerName": "",
"CustomSMTPPort": "25"
}
},
"JobSettings": {
"RunJobs": true,
"RunScheduler": true
"RunScheduler": true,
"CleanupJobsThresholdDays": -1,
"CleanupConfigThresholdDays": -1
},
"PluginSettings": {
"Enable": true,
"EnableUploads": true,
"AllowInsecureDownloadUrl": false,
"AllowInsecureDownloadURL": false,
"EnableHealthCheck": true,
"Directory": "./plugins",
"ClientDirectory": "./client/plugins",
"Plugins": {},
"Plugins": {
"mattermost-ai": {
"allowedUpstreamHostnames": "",
"bots": null,
"defaultBotName": "",
"embeddingSearchConfig": {
"chunkingOptions": {
"chunkOverlap": 0,
"chunkSize": 0,
"chunkingStrategy": "",
"minChunkSize": 0
},
"dimensions": 0,
"embeddingProvider": {
"parameters": null,
"type": ""
},
"parameters": null,
"type": "",
"vectorStore": {
"parameters": null,
"type": ""
}
},
"enableLLMTrace": false,
"mcp": {
"enabled": false,
"idleTimeoutMinutes": 0,
"servers": null
},
"services": null,
"transcriptBackend": ""
},
"playbooks": {
"BotUserID": "6ieoijnzdfgnzq7535rbomzqjy"
}
},
"PluginStates": {
"com.mattermost.calls": {
"Enable": true
},
"com.mattermost.nps": {
"Enable": true
},
"mattermost-ai": {
"Enable": true
},
"playbooks": {
"Enable": true
}
},
"EnableMarketplace": true,
"EnableRemoteMarketplace": true,
"AutomaticPrepackagedPlugins": true,
"RequirePluginSignature": false,
"MarketplaceUrl": "https://api.integrations.mattermost.com",
"SignaturePublicKeyFiles": []
"MarketplaceURL": "https://api.integrations.mattermost.com",
"SignaturePublicKeyFiles": [],
"ChimeraOAuthProxyURL": ""
},
"DisplaySettings": {
"CustomUrlSchemes": [],
"ExperimentalTimezone": false
"CustomURLSchemes": [],
"MaxMarkdownNodes": 0
},
"GuestAccountsSettings": {
"Enable": false,
"HideTags": false,
"AllowEmailAccounts": true,
"EnforceMultifactorAuthentication": false,
"RestrictCreationToDomains": ""
@ -500,5 +690,83 @@
"ImageProxyType": "local",
"RemoteImageProxyURL": "",
"RemoteImageProxyOptions": ""
},
"CloudSettings": {
"CWSURL": "https://customers.mattermost.com",
"CWSAPIURL": "https://portal.internal.prod.cloud.mattermost.com",
"CWSMock": false,
"Disable": false
},
"ImportSettings": {
"Directory": "./import",
"RetentionDays": 30
},
"ExportSettings": {
"Directory": "./export",
"RetentionDays": 30
},
"WranglerSettings": {
"PermittedWranglerRoles": [],
"AllowedEmailDomain": [],
"MoveThreadMaxCount": 100,
"MoveThreadToAnotherTeamEnable": false,
"MoveThreadFromPrivateChannelEnable": false,
"MoveThreadFromDirectMessageChannelEnable": false,
"MoveThreadFromGroupMessageChannelEnable": false
},
"ConnectedWorkspacesSettings": {
"EnableSharedChannels": false,
"EnableRemoteClusterService": false,
"DisableSharedChannelsStatusSync": false,
"SyncUsersOnConnectionOpen": false,
"GlobalUserSyncBatchSize": 25,
"MaxPostsPerSync": 50,
"MemberSyncBatchSize": 20
},
"AccessControlSettings": {
"EnableAttributeBasedAccessControl": false,
"EnableChannelScopeAccessControl": false,
"EnableUserManagedAttributes": false
},
"ContentFlaggingSettings": {
"EnableContentFlagging": false,
"ReviewerSettings": {
"CommonReviewers": true,
"CommonReviewerIds": [],
"TeamReviewersSetting": {},
"SystemAdminsAsReviewers": false,
"TeamAdminsAsReviewers": true
},
"NotificationSettings": {
"EventTargetMapping": {
"assigned": [
"reviewers"
],
"dismissed": [
"reviewers",
"reporter"
],
"flagged": [
"reviewers"
],
"removed": [
"reviewers",
"author",
"reporter"
]
}
},
"AdditionalSettings": {
"Reasons": [
"Inappropriate content",
"Sensitive data",
"Security concern",
"Harassment or abuse",
"Spam or phishing"
],
"ReporterCommentRequired": true,
"ReviewerCommentRequired": true,
"HideFlaggedContent": true
}
}
}

View File

@ -10,7 +10,7 @@ services:
- 389:389
- 636:636
volumes:
- ./bootstrap.ldif:/container/service/slapd/assets/config/bootstrap/ldif/50-bootstrap.ldif
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/Demo/bootstrap.ldif:/container/service/slapd/assets/config/bootstrap/ldif/50-bootstrap.ldif
environment:
LDAP_ORGANISATION: "Example Corp"
LDAP_DOMAIN: "example.com"
@ -19,25 +19,25 @@ services:
LDAP_READONLY_USER_USERNAME: "butler"
LDAP_READONLY_USER_PASSWORD: "readonly"
nginx:
webserver:
image: nginx
restart: always
ports:
- 80:80
- 443:443
volumes:
- ../oauth:/var/www/html/oauth
- ./nginx.conf:/etc/nginx/nginx.conf
links:
- "php:php"
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/oauth:/var/www/html/oauth
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/Demo/nginx.conf:/etc/nginx/nginx.conf
depends_on:
- php
php:
build: ../Docker/php-ldap-pgsql
build: D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/Docker/php-ldap-pgsql
image: php-ldap-pgsql
volumes:
- ../oauth:/var/www/html/oauth
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/oauth:/var/www/html/oauth
environment:
ldap_host: ldap://localhost:389/
ldap_host: ldap://ldap:389/
ldap_port: 389
ldap_version: 3
ldap_search_attribute: uid
@ -45,34 +45,26 @@ services:
ldap_filter: "(objectClass=*)"
ldap_bind_dn: "cn=butler,dc=example,dc=com"
ldap_bind_pass: "readonly"
db_host: "127.0.0.1"
db_host: "database"
db_port: "5432"
db_type: "pgsql"
db_name: "oauth_db"
db_user: "oauth"
db_pass: "oauth_secure-pass"
depends_on:
- database
- ldap
db:
database:
image: postgres:alpine
restart: always
volumes:
- ../db_init/init_postgres.sh:/docker-entrypoint-initdb.d/init_postgres.sh
- ../db_init/config_init.sh.example:/docker-entrypoint-initdb.d/config_init.sh
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/db_init/init_postgres.sh:/docker-entrypoint-initdb.d/init_postgres.sh
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/db_init/config_init.sh.example:/docker-entrypoint-initdb.d/config_init.sh
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: rootroot
POSTGRES_HOST_AUTH_METHOD: trust
client_id: 123456789abcdef123456789abcdef
client_secret: fedcba987654321fedcba987654321
redirect_uri: "http://localhost/signup/gitlab/complete"
grant_types: "authorization_code"
scope: "api"
user_id: ""
db_user: "oauth"
db_pass: "oauth_secure-pass"
db_name: "oauth_db"
db_host: "127.0.0.1"
db_port: "5432"
mattermost:
image: mattermost/mattermost-preview
@ -81,4 +73,4 @@ services:
extra_hosts:
- dockerhost:127.0.0.1
volumes:
- ./config.json:/mm/mattermost/config/config_docker.json
- D:/23_Gitlab/dockerCompose/mattermost-ldap/Mattermost-LDAP/Demo/config.json:/mm/mattermost/config/config_docker.json

View File

@ -31,8 +31,8 @@ http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mattermost_cache:10m max_size=3g inactive=120m use_temp_path=off;
upstream mattermost {
server localhost:8065;
upstream mm-svc {
server mattermost:8065;
}
server {
@ -65,7 +65,7 @@ http {
proxy_buffers 256 16k;
proxy_buffer_size 16k;
proxy_read_timeout 600s;
proxy_pass http://mattermost;
proxy_pass http://mm-svc;
}
location /oauth/gitlab/ {
@ -84,7 +84,15 @@ http {
proxy_cache_min_uses 2;
proxy_cache_use_stale timeout;
proxy_cache_lock on;
proxy_pass http://mattermost;
proxy_pass http://mm-svc;
}
location /oauth/access_token {
try_files $uri /oauth/index.php;
}
location /oauth/authorize {
try_files $uri /oauth/authorize.php$is_args$args;
}
location ~ /oauth/.*\.php$ {
@ -117,7 +125,7 @@ http {
proxy_cache_min_uses 2;
proxy_cache_use_stale timeout;
proxy_cache_lock on;
proxy_pass http://mattermost;
proxy_pass http://mm-svc;
}
}

View File

@ -1,26 +0,0 @@
# Image mattermostldap
FROM php:apache
RUN set -x \
&& apt-get update \
&& apt-get install -y libpq-dev libldap2-dev git\
&& rm -rf /var/lib/apt/lists/* \
&& docker-php-ext-configure pgsql --with-pgsql=/usr/local/pgsql \
&& docker-php-ext-install pdo pdo_pgsql pgsql \
&& docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ \
&& docker-php-ext-install ldap
# Enable development php.ini config (Solve empty answer from token.php)
RUN ln -s /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini
# Get Mattermost-LDAP project
RUN git clone https://github.com/crivaledaz/Mattermost-LDAP.git /opt/Mattermost-LDAP/
# Install server Oauth
RUN cp -r /opt/Mattermost-LDAP/oauth/ /var/www/html/
# Get config file
RUN cp /var/www/html/oauth/config_db.php.example /var/www/html/oauth/config_db.php; cp /var/www/html/oauth/LDAP/config_ldap.php.example /var/www/html/oauth/LDAP/config_ldap.php
# Open and expose port 80 for Apache server
EXPOSE 80

View File

@ -1,6 +1,6 @@
The MIT License
Copyright (c) 2017-2020 Denis CLAVIER
Copyright (c) 2017-2021 Denis CLAVIER
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -7,7 +7,7 @@ This module provides an external LDAP authentication in Mattermost for the Team
Currently, LDAP authentication in Mattermost is not featured in the Team Edition (only in the Enterprise Edition). Thus, the only way to get LDAP authentication in Mattermost is to install Gitlab and use its Single Sign On (SSO) feature. Gitlab allows LDAP authentication and transmits user data to Mattermost. So, anyone who wishes to use LDAP with Mattermost must run Gitlab, even if he does not use it, for the SSO feature.
However, although Gitlab is a nice software, it is resources-consuming and a bit complicated to manage if you just want the SSO feature. That's the reason why, this module provides an oauth server to only reproduce the Gitlab SSO feature and allows a simple and secure LDAP authentication to Mattermost.
However, although Gitlab is a nice software, it is resources-consuming and a bit complicated to manage if you just want the SSO feature. That's the reason why, this module provides an Oauth server to only reproduce the Gitlab SSO feature and allows a simple and secure LDAP authentication to Mattermost.
The Mattermost-LDAP project uses the Gitlab authentication feature from Mattermost and substitute Gitlab to LDAP interaction. The main advantage of this module is to provide a light and easy to use LDAP connector for Mattermost not to need Gitlab.
@ -19,7 +19,7 @@ See Limitation section for more information.
## Quick Start - Demonstration
To test and try Mattermost-LDAP, you can use the demonstration available in the `Demo/` folder. This demonstration is based on a docker-compose implementation describe in the `Demo/docker-compose.yaml` file.
To test and try Mattermost-LDAP, you can use the demonstration available in the `Demo/` folder. This demonstration is based on a docker-compose implementation describe in the [`Demo/docker-compose.yaml` file](https://github.com/Crivaledaz/Mattermost-LDAP/blob/master/Demo/docker-compose.yaml).
This docker-compose file instantiate a Mattermost Server from the official preview image provides by Mattermost, a Mattemrost-LDAP pre-configured server with a PostgreSQL database and an OpenLDAP server with a test user : John DOE.
@ -64,7 +64,7 @@ docker-compose up -d
podman-compose up -d
```
The up command starts all services described in the Docker compose file. The `-d` argument allow to start all container in background, in a detach mode.
The up command starts all services described in the Docker compose file. The `-d` argument allows to start all container in background, in a detach mode.
Once all services are started, go to Mattermost server. Mattermost should be available after a few seconds on localhost : http://localhost.
@ -104,7 +104,7 @@ Configuration files are provided with examples and default values. Each config f
You can find a detailed description of each parameters available below.
**Note** : For container, these variables are overload by environment variables define in `.env` file or `docker-compose.yaml` file.
**Note** : For container, these variables are overload by environment variables define in the [`docker-compose.yaml`](https://github.com/Crivaledaz/Mattermost-LDAP/blob/master/docker-compose.yaml) file.
### Init script parameters
@ -179,7 +179,7 @@ Keep in mind this will create a new account on your Mattermost server with infor
## Limitation
This module has been tested on Centos 7, Fedora and Ubuntu with PostgreSQL and Mattermost Community Edition version 4.1, 4.9, 5.0.1, 5.10, 5.15.1, 5.51.0 and 5.22.0. Mattermost-LDAP is compliant with Mattermost Team Edition 4.x.x and 5.x.x.
This module has been tested on Centos (7, 8, 8 stream), Fedora and Ubuntu with PostgreSQL and Mattermost Community Edition version 4.1, 4.9, 5.0.1, 5.10, 5.15.1, 5.51.0, 5.22.0, 5.36.0 and 6.0.0. Mattermost-LDAP is compliant with Mattermost Team Edition 4.x.x, 5.x.x and 6.x.x.
Others operating systems has not been tested yet but should work fine.

View File

@ -1,16 +1,18 @@
#!/bin/bash
#####################################--CONFIGURATION FILE--########################################
#Client configuration
client_id=$(if [ -z $client_id ]; then echo "123456789"; else echo $client_id; fi)
client_secret=$(if [ -z $client_secret ]; then echo "987654321"; else echo $client_secret; fi)
redirect_uri=$(if [ -z $redirect_uri ]; then echo "http://mattermost.company.com/signup/gitlab/complete"; else echo $redirect_uri; fi)
grant_types=$(if [ -z $grant_types ]; then echo "authorization_code"; else echo $grant_types; fi)
scope=$(if [ -z $scope ]; then echo "api"; else echo $client_id; fi)
user_id=$(if [ -z $user_id ]; then echo ""; else echo $user_id; fi)
# Client configuration
client_id=${client_id:-123456789}
client_secret=${client_secret:-987654321}
redirect_uri=${redirect_uri:-http://mattermost.company.com/signup/gitlab/complete}
grant_types=${grant_types:-authorization_code}
scope=${scope:-api}
user_id=${user_id:-}
#Database configuration
db_user=$(if [ -z $db_user ]; then echo "oauth"; else echo $db_user; fi)
db_name=$(if [ -z $db_name ]; then echo "oauth_db"; else echo $db_name; fi)
db_pass=$(if [ -z $db_pass ]; then echo "oauth_secure-pass"; else echo $db_pass; fi)
db_host=$(if [ -z $db_host ]; then echo "localhost"; else echo $db_host; fi)
db_port=$(if [ -z $db_port ]; then echo "5432"; else echo $db_port; fi)
# Database configuration
db_user=${db_user:-oauth}
db_name=${db_name:-oauth_db}
db_pass=${db_pass:-oauth_secure-pass}
db_host=${db_host:-localhost}
db_port=${db_port:-5432}

View File

@ -1,45 +1,46 @@
#!/bin/bash
#This script need right to become postgres user (so root) and to read/write in httpd directory
# This script needs root privileges and access to Postgres
source config_init.sh
set -e
source /docker-entrypoint-initdb.d/config_init.sh
#######################################--Fonctions--###############################################
#######################################--Functions--###############################################
ok() { echo -e '\e[32m'$1'\e[m'; }
error() { echo -e '\e[31m'$1'\e[m'; }
info() { echo -e '\e[34m'$1'\e[m'; }
warn() { echo -e '\e[33m'$1'\e[m'; }
ok() { echo -e '\e[32m'"$1"'\e[m'; }
error(){ echo -e '\e[31m'"$1"'\e[m'; }
info() { echo -e '\e[34m'"$1"'\e[m'; }
warn() { echo -e '\e[33m'"$1"'\e[m'; }
#######################################--SQL STATEMENT--###########################################
#Tables creation
create_table_oauth_client="CREATE TABLE oauth_clients (client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000) NOT NULL, grant_types VARCHAR(80), scope VARCHAR(100), user_id VARCHAR(80), CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id));"
create_table_oauth_access_tokens="CREATE TABLE oauth_access_tokens (access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT access_token_pk PRIMARY KEY (access_token));"
create_table_oauth_authorization_codes="CREATE TABLE oauth_authorization_codes (authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code));"
create_table_oauth_refresh_tokens="CREATE TABLE oauth_refresh_tokens (refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token));"
create_table_users="CREATE TABLE users (id SERIAL NOT NULL, username VARCHAR(255) NOT NULL, CONSTRAINT id_pk PRIMARY KEY (id));"
create_table_oauth_scopes="CREATE TABLE oauth_scopes (scope TEXT, is_default BOOLEAN);"
# Tables creation
create_table_oauth_client="CREATE TABLE IF NOT EXISTS oauth_clients (client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000) NOT NULL, grant_types VARCHAR(80), scope VARCHAR(100), user_id VARCHAR(80), CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id));"
create_table_oauth_access_tokens="CREATE TABLE IF NOT EXISTS oauth_access_tokens (access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT access_token_pk PRIMARY KEY (access_token));"
create_table_oauth_authorization_codes="CREATE TABLE IF NOT EXISTS oauth_authorization_codes (authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code));"
create_table_oauth_refresh_tokens="CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token));"
create_table_users="CREATE TABLE IF NOT EXISTS users (id SERIAL NOT NULL, username VARCHAR(255) NOT NULL, CONSTRAINT id_pk PRIMARY KEY (id));"
create_table_oauth_scopes="CREATE TABLE IF NOT EXISTS oauth_scopes (scope TEXT, is_default BOOLEAN);"
#Client creation
create_client="INSERT INTO oauth_clients (client_id,client_secret,redirect_uri,grant_types,scope,user_id) VALUES ('$client_id','$client_secret','$redirect_uri','$grant_types','$scope','$user_id');"
# Client creation
create_client="INSERT INTO oauth_clients (client_id,client_secret,redirect_uri,grant_types,scope,user_id) VALUES ('$client_id','$client_secret','$redirect_uri','$grant_types','$scope','$user_id') ON CONFLICT (client_id) DO NOTHING;"
###################################################################################################
#Welcome Message
info "This script will create a new Oauth role and an associated database for Mattermost-LDAP\nTo edit configuration please edit this script before running !\n"
warn "SuperUser right must be ask to create the new role and database in postgres\n"
info "Press ctrl+c to stop the script"
# Welcome
info "This script will create a new OAuth role and database for Mattermost-LDAP"
warn "SuperUser rights are required to create role and database in Postgres"
info "Press ctrl+c to stop the script if you are not ready"
sleep 5
#Creating Oauth role and associated database (need admin account on postgres)
info "Creation of role $db_user and database $db_name ..."
# Create role and DB
info "Creating role [$db_user] and database [$db_name] ..."
psql -U postgres -c "CREATE DATABASE $db_name;"
psql -U postgres -c "CREATE USER $db_user WITH ENCRYPTED PASSWORD '$db_pass';"
psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE $db_name TO $db_user;"
psql -U postgres -c "ALTER DATABASE $db_name OWNER TO $db_user;"
#Creating tables for ouath database (use oauth role)
info "Creation of tables for database $db_name (using $db_user)"
# Create tables
info "Creating tables in database $db_name (using $db_user)"
psql -U $db_user -d $db_name -c "$create_table_oauth_client"
psql -U $db_user -d $db_name -c "$create_table_oauth_access_tokens"
psql -U $db_user -d $db_name -c "$create_table_oauth_authorization_codes"
@ -47,18 +48,16 @@ psql -U $db_user -d $db_name -c "$create_table_oauth_refresh_tokens"
psql -U $db_user -d $db_name -c "$create_table_users"
psql -U $db_user -d $db_name -c "$create_table_oauth_scopes"
#Insert new client in the database
info "Insert new client in the database"
# Insert client
info "Inserting new client into database"
psql -U $db_user -d $db_name -c "$create_client"
#Verification
psql -U $db_user -d $db_name -c "SELECT * from oauth_clients WHERE client_id='$client_id';" | grep '(1'
if [ $? ]
then ok "Client has been created ! Oauth Database is configured.\n"
info "Client ID : $client_id"
warn "Client Secret : $client_secret\n"
info "Keep id and secret, you will need them to configure Mattermost"
warn "Beware Client Secret IS PRIVATE and MUST BE KEPT SECRET"
else error "Client has not been created ! Check log below"
# Verification
if psql -U $db_user -d $db_name -c "SELECT * FROM oauth_clients WHERE client_id='$client_id';" | grep -q "$client_id"; then
ok "Client has been created! OAuth Database is configured."
info "Client ID : $client_id"
warn "Client Secret : $client_secret"
info "Keep ID and Secret safe, you will need them to configure Mattermost"
else
error "Client was not created! Please check logs."
fi

View File

@ -1,30 +1,42 @@
version: '3'
services:
mattermost-ldap:
build: Docker/mattermostldap
image: mattermostldap
webserver:
image: nginx
restart: always
ports:
- 80:80
- 443:443
volumes:
- ./oauth:/var/www/html/oauth
- ./oauth.conf:/etc/nginx/conf.d/oauth.conf:ro
- ./certs:/etc/nginx/certs
depends_on:
- php
php:
build: ./Docker/php-ldap-pgsql
image: php-ldap-pgsql
volumes:
- ./oauth:/var/www/html/oauth
environment:
- ldap_host
- ldap_port
- ldap_version
- ldap_start_tls
- ldap_search_attribute
- ldap_base_dn
- ldap_filter
- ldap_bind_dn
- ldap_bind_pass
- db_host
- db_port
- db_type
- db_name
- db_user
- db_pass
ldap_host: ldap://ldap.company.com:389/
ldap_port: 389
ldap_version: 3
ldap_start_tls: 0
ldap_search_attribute: uid
ldap_base_dn: "ou=People,o=Company"
ldap_filter: "(objectClass=*)"
ldap_bind_dn: ""
ldap_bind_pass: ""
db_host: "database"
db_port: "5432"
db_type: "pgsql"
db_name: "oauth_db"
db_user: "oauth"
db_pass: "oauth_secure-pass"
depends_on:
- database
db:
database:
image: postgres:alpine
restart: always
volumes:
@ -32,17 +44,17 @@ services:
- ./db_init/config_init.sh.example:/docker-entrypoint-initdb.d/config_init.sh
- ./data/:/var/lib/postgresql/data/
environment:
- POSTGRES_USER
- POSTGRES_PASSWORD
- POSTGRES_HOST_AUTH_METHOD
- client_id
- client_secret
- redirect_uri
- grant_types
- scope
- user_id
- db_user
- db_pass
- db_name
- db_host
- db_port
POSTGRES_USER: postgres
POSTGRES_PASSWORD: rootroot
POSTGRES_HOST_AUTH_METHOD: trust
client_id: 123456789abcdef123456789abcdef
client_secret: fedcba987654321fedcba987654321
redirect_uri: "https://mattermost.company.com/signup/gitlab/complete"
grant_types: "authorization_code"
scope: "api"
user_id: ""
db_user: "oauth"
db_pass: "oauth_secure-pass"
db_name: "oauth_db"
db_host: "127.0.0.1"
db_port: "5432"

View File

@ -1,88 +0,0 @@
# Docker compose parameters for Mattermost-LDAP
#
# Adapt these parameters to match with your configuration.
# More information available in section "Configuration" in README.md
#
# Oauth client configuration
#
# Client ID token. Must be a random hex value. Use `openssl rand -hex 32` to generate a token.
client_id = "123456789abcdef123456789abcdef"
# Client Secret token. Must be a random hex value. Use `openssl rand -hex 32` to generate a token.
client_secret = "fedcba987654321fedcba987654321"
# Redirect URI use by Oauth server to redirect user after authentifictaion process. Must be the same than as Mattermost give to Oauth server.
redirect_uri = "http://localhost/signup/gitlab/complete"
# Grant types method uses by Oauth server
grant_types = "authorization_code"
# Scope of the client in the Oauth server
scope = "api"
# Non important parameter. Could be used as a commentary field
user_id = ""
#
# Database configuration
#
# Username for the PostgreSQL administrator account
POSTGRES_USER = "postgres"
# Password for PostgreSQL administrator account
POSTGRES_PASSWORD = "rootroot"
# Method to use for connection to database
POSTGRES_HOST_AUTH_METHOD = "trust"
# Oauth user to connect the database
db_user = "oauth"
# Oauth password to connect the database
db_pass = "oauth_secure-pass"
# Oauth database name
db_name = "oauth_db"
# PostgreSQL database host
db_host = "127.0.0.1"
# PostgreSQL database port
db_port = "5432"
# Database type. Docker compose implementation for Mattermost-LDAP uses PostgreSQL.
db_type = "pgsql"
#
# LDAP configuration
#
# LDAP host or IP
ldap_host = "ldap://ldap.company.com:389/"
# LDAP port
ldap_port = "389"
# LDAP protocol version
ldap_version = "3"
# LDAP STARTTLS
ldap_start_tls = "1"
# Unique identifier for entry in LDAP
ldap_search_attribute = "uid"
# Base DN to search from in LDAP
ldap_base_dn = "ou=People,o=Company"
# Additional filter for LDAP search
ldap_filter = "(objectClass=*)"
# Service account to bind LDAP server
ldap_bind_dn = ""
# Password for service account to bind LDAP server
ldap_bind_pass = ""

46
oauth.conf Normal file
View File

@ -0,0 +1,46 @@
server {
listen *:443;
server_name localhost;
root /var/www/html;
index index.php index.html index.htm;
ssl on;
ssl_certificate ./certs/cert.pem;
ssl_certificate_key ./certs/key.pem;
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
location /oauth/access_token {
try_files $uri /oauth/index.php;
}
location /oauth/authorize {
try_files $uri /oauth/authorize.php$is_args$args;
}
location ~ /oauth/.*\.php$ {
try_files $uri =404;
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80 default_server;
server_name localhost;
index index.php index.html index.htm;
return 301 https://$host$request_uri;
}

View File

@ -154,7 +154,7 @@ class LDAP implements LDAPInterface
*/
public function getDataForMattermost($ldap_base_dn, $ldap_filter, $ldap_bind_dn, $ldap_bind_pass, $ldap_search_attribute, $user)
{
$attribute=array("cn","mail");
$attribute=array("cn","mail","displayName");
if (!is_string($ldap_base_dn)) {
throw new InvalidArgumentException('First argument to LDAP/getData must be the ldap base directory name (string). Ex: o=Company');
@ -212,7 +212,9 @@ class LDAP implements LDAPInterface
throw new Exception('An error has occured during ldap_get_values execution (complete name). Please check parameter of LDAP/getData.');
}
return array("mail" => $mail[0], "cn" => $cn[0]);
$displayName = ldap_get_values($this->ldap_server, $data, "displayName");
return array("mail" => $mail[0], "cn" => $cn[0], "displayName" => $displayName[0]);
}
/*

View File

@ -30,7 +30,7 @@ if (!isset($_SESSION['uid']))
// Store the authorize request
$explode_url=explode("/", strip_tags(trim($_SERVER['REQUEST_URI'])));
$_SESSION['auth_page']=end($explode_url);
header('Location: index.php');
header('Location: access_token');
exit();
}

View File

@ -41,7 +41,7 @@ else
{
messageShow($prompt_template, 'Username has incorrect format ... Please try again');
}
elseif (strlen($_POST['password']) > 64 || strlen($_POST['password']) <= 7)
elseif (strlen($_POST['password']) > 64)
{
messageShow($prompt_template, 'Password has incorrect format ... Please try again');
}

View File

@ -36,7 +36,7 @@ try {
// Here is the patch for Mattermost 4.4 and newer. Gitlab has changed the JSON output of oauth service. Many data are not used by Mattermost, but there is a stack error if we delete them. That's the reason why date and many parameters are null or empty.
$resp = array(
"id" => $assoc_id,
"name" => $data['cn'],
"name" => strlen($data['displayName']) > 0 ? $data['displayName'] : $data['cn'],
"username" => $user,
"state" => "active",
"avatar_url" => "",

View File

@ -47,12 +47,12 @@ table {
#form_icon img {
width: 100%;
max-width: 450px;
max-width: 150px;
}
#form_icon_prompt img {
width: 50%;
max-width: 350px;
max-width: 150px;
}
@ -63,7 +63,7 @@ table {
justify-content: center;
align-items: center;
position: absolute;
transform: translate(-50%, 25%);
transform: translate(-50%, 8%);
}
/* Style input fields */
@ -86,7 +86,7 @@ table {
height: 60px;
/* Make the borders more round */
border-radius: 12px;
border-radius: 5px;
width: 100%;
}
@ -118,7 +118,7 @@ table {
text-transform: capitalize;
text-align: center;
display: inline-block;
margin-top: 25%;
margin-top: 10%;
margin-right: 2%;
width: 50%;
}

View File

@ -1,4 +1,4 @@
<?php
<?php
/**
* Adapted from Oauth2-server-php cookbook
* @see http://bshaffer.github.io/oauth2-server-php-docs/cookbook/

4
两行sql.txt Normal file
View File

@ -0,0 +1,4 @@
docker exec -it demo-database-1 psql -U postgres -d oauth_db -c "SELECT client_id, client_secret, redirect_uri FROM oauth_clients;"
docker exec -it demo-database-1 psql -U oauth -d oauth_db -c "UPDATE oauth_clients SET redirect_uri='http://localhost/signup/gitlab/complete' WHERE client_id='123456789';"