Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Added password policy to the HTTP API and the Manager UI (#1524)

Martin Peeters4f44988c1a32
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index 42285fb04..76b445cef 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -864,6 +864,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
realmRepresentation.setEnabled(realm.getEnabled());
realmRepresentation.setDuplicateEmailsAllowed(realm.getDuplicateEmailsAllowed());
realmRepresentation.setResetPasswordAllowed(realm.getResetPasswordAllowed());
+ realmRepresentation.setPasswordPolicy(realm.getPasswordPolicyString());
realmRepresentation.setNotBefore(realm.getNotBefore() != null ? realm.getNotBefore().intValue() : null);
configureRealm(realmRepresentation);
realmResource.update(realmRepresentation);
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index cec82788f..9548389c3 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -393,6 +393,21 @@
"submit": "Submit",
"password": "Password",
"repeatPassword": "Repeat password",
+ "password-policy-invalid-length": "The password must be between {{0}} and {{1}} characters long",
+ "password-policy-invalid-length-too-short": "The password must have at least {{0}} characters",
+ "password-policy-invalid-length-too-long": "The password must be below the maximum of {{0}} characters",
+ "password-policy-special-chars-single": "The password must have at least {{0}} special character",
+ "password-policy-special-chars": "The password must have at least {{0}} special characters",
+ "password-policy-digits-single": "The password must have at least {{0}} number",
+ "password-policy-digits": "The password must have at least {{0}} numbers",
+ "password-policy-uppercase-single": "The password must have at least {{0}} uppercase character",
+ "password-policy-uppercase": "The password must have at least {{0}} uppercase characters",
+ "password-policy-lowercase-single": "The password must have at least {{0}} lowercase character",
+ "password-policy-lowercase": "The password must have at least {{0}} lowercase characters",
+ "password-policy-recently-used": "The password cannot be recently used",
+ "password-policy-not-email-username": "The password cannot be the email address nor the username",
+ "password-policy-not-username": "The password cannot be the username",
+ "password-policy-not-email": "The password cannot be the email address",
"details": "Details",
"permissions":"Permissions",
"linkedAssets":"Linked assets",
@@ -601,6 +616,7 @@
"createUserFailed": "Create user failed",
"saveUserFailed": "Save user failed",
"saveUserSucceeded": "Saved user successfully!",
+ "savePasswordFailed": "Failed to set the password.",
"userAlreadyExists": "Error occurred! This user already exists.",
"invalidUsername": "Username must be 3-255 alpha numerical characters",
"invalidEmail": "Invalid email address",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 9b4630395..be789a91c 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -391,6 +391,21 @@
"submit": "Verzenden",
"password": "Wachtwoord",
"repeatPassword": "Herhaal wachtwoord",
+ "password-policy-invalid-length": "Het wachtwoord moet minstens {{0}}, en mag maximaal {{1}} tekens hebben",
+ "password-policy-invalid-length-too-short": "Het wachtwoord moet minstens {{0}} tekens hebben",
+ "password-policy-invalid-length-too-long": "Het wachtwoord mag maximaal {{0}} tekens hebben",
+ "password-policy-special-chars-single": "Het wachtwoord moet minstens {{0}} speciaal teken bevatten",
+ "password-policy-special-chars": "Het wachtwoord moet minstens {{0}} speciale tekens bevatten",
+ "password-policy-digits-single": "Het wachtwoord moet minstens {{0}} cijfer bevatten",
+ "password-policy-digits": "Het wachtwoord moet minstens {{0}} cijfers bevatten",
+ "password-policy-uppercase-single": "Het wachtwoord moet minstens {{0}} hoofdletter bevatten",
+ "password-policy-uppercase": "Het wachtwoord moet minstens {{0}} hoofdletters bevatten",
+ "password-policy-lowercase-single": "Het wachtwoord moet minstens {{0}} kleine letter bevatten",
+ "password-policy-lowercase": "Het wachtwoord moet minstens {{0}} kleine letters bevatten",
+ "password-policy-recently-used": "Het wachtwoord mag niet recent gebruikt zijn",
+ "password-policy-not-email-username": "Het wachtwoord mag niet het emailadres of gebruikersnaam zijn",
+ "password-policy-not-username": "Het wachtwoord mag niet de gebruikersnaam zijn",
+ "password-policy-not-email": "Het wachtwoord mag niet het emailadres zijn",
"details": "Details",
"permissions":"Rechten",
"linkedAssets":"Gekoppelde assets",
@@ -599,6 +614,7 @@
"createUserFailed": "Aanmaken gebruiker mislukt",
"saveUserFailed": "Opslaan gebruiker mislukt",
"saveUserSucceeded": "Gebruiker succesvol opgeslagen!",
+ "savePasswordFailed": "Kon wachtwoord niet bijwerken.",
"userAlreadyExists": "Fout opgetreden! Deze gebruiker bestaat al!",
"invalidUsername": "De gebruikersnaam mag 3-255 numerieke tekens bevatten",
"invalidEmail": "Ongeldig emailadres",
diff --git a/model/src/main/java/org/openremote/model/persistence/PasswordPolicyConverter.java b/model/src/main/java/org/openremote/model/persistence/PasswordPolicyConverter.java
new file mode 100644
index 000000000..931ae5da0
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/persistence/PasswordPolicyConverter.java
@@ -0,0 +1,21 @@
+package org.openremote.model.persistence;
+
+import jakarta.persistence.AttributeConverter;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class PasswordPolicyConverter implements AttributeConverter<List<String>, String> {
+
+
+ @Override
+ public String convertToDatabaseColumn(List<String> attribute) {
+ return attribute != null ? String.join(" and ", attribute) : null;
+ }
+
+ @Override
+ public List<String> convertToEntityAttribute(String dbData) {
+ return dbData != null ? Arrays.stream(dbData.split(" and ")).toList() : null;
+ }
+
+}
diff --git a/model/src/main/java/org/openremote/model/security/Realm.java b/model/src/main/java/org/openremote/model/security/Realm.java
index 0421e5891..2bb1c67f0 100644
--- a/model/src/main/java/org/openremote/model/security/Realm.java
+++ b/model/src/main/java/org/openremote/model/security/Realm.java
@@ -20,6 +20,9 @@
package org.openremote.model.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Subselect;
@@ -27,6 +30,9 @@ import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
+import org.openremote.model.persistence.PasswordPolicyConverter;
+
+import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
@@ -42,6 +48,20 @@ public class Realm {
protected static Field[] propertyFields;
+ private static final PasswordPolicyConverter PASSWORD_POLICY_CONVERTER = new PasswordPolicyConverter();
+
+ public static class PasswordPolicyDeserializer extends JsonDeserializer<List<String>> {
+ @Override
+ public List<String> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
+ JsonNode node = p.getCodec().readTree(p);
+ List<String> policies = new ArrayList<>();
+ if (node.isArray()) {
+ node.forEach(element -> policies.add(element.asText()));
+ }
+ return policies;
+ }
+ }
+
@Id
protected String id;
@@ -57,6 +77,15 @@ public class Realm {
@Column(name = "NOT_BEFORE")
protected Double notBefore; // This will explode in 2038
+ /**
+ * List of password policies, using the "policy(value)" format. Example: "specialChars(1)".
+ * Stored in column as "policy(value) and policy(value) and policy(value)", and converted using {@link PasswordPolicyConverter}
+ */
+ @Column(name = "password_policy")
+ @Convert(converter = PasswordPolicyConverter.class)
+ @JsonDeserialize(using = PasswordPolicyDeserializer.class)
+ protected List<String> passwordPolicy;
+
@Column(name = "reset_password_allowed")
protected Boolean resetPasswordAllowed;
@@ -147,6 +176,24 @@ public class Realm {
return this;
}
+ public List<String> getPasswordPolicy() {
+ return passwordPolicy;
+ }
+
+ public String getPasswordPolicyString() {
+ return PASSWORD_POLICY_CONVERTER.convertToDatabaseColumn(passwordPolicy);
+ }
+
+ public Realm setPasswordPolicy(List<String> passwordPolicy) {
+ this.passwordPolicy = passwordPolicy;
+ return this;
+ }
+
+ public Realm setPasswordPolicy(String passwordPolicy) {
+ this.passwordPolicy = PASSWORD_POLICY_CONVERTER.convertToEntityAttribute(passwordPolicy);
+ return this;
+ }
+
public Double getNotBefore() {
return notBefore;
}
@@ -321,6 +368,7 @@ public class Realm {
", displayName='" + displayName + '\'' +
", enabled=" + enabled +
", notBefore=" + notBefore +
+ ", passwordPolicy=" + passwordPolicy +
", resetPasswordAllowed=" + resetPasswordAllowed +
", duplicateEmailsAllowed=" + duplicateEmailsAllowed +
", rememberMe=" + rememberMe +
diff --git a/ui/app/manager/src/pages/page-users.ts b/ui/app/manager/src/pages/page-users.ts
index d61881f0d..64b2446d1 100644
--- a/ui/app/manager/src/pages/page-users.ts
+++ b/ui/app/manager/src/pages/page-users.ts
@@ -5,7 +5,7 @@ import "@openremote/or-components/or-panel";
import "@openremote/or-translate";
import {Store} from "@reduxjs/toolkit";
import {AppStateKeyed, Page, PageProvider, router} from "@openremote/or-app";
-import {ClientRole, Role, User, UserAssetLink, UserQuery, UserSession} from "@openremote/model";
+import {ClientRole, Credential, Role, User, UserAssetLink, UserQuery, UserSession} from "@openremote/model";
import {i18next} from "@openremote/or-translate";
import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";
import {OrMwcDialog, showDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
@@ -15,6 +15,7 @@ import {OrAssetTreeRequestSelectionEvent, OrAssetTreeSelectionEvent} from "@open
import {getNewUserRoute, getUsersRoute} from "../routes";
import {when} from 'lit/directives/when.js';
import {until} from 'lit/directives/until.js';
+import {map} from 'lit/directives/map.js';
import {OrMwcTableRowClickEvent, TableColumn, TableRow} from "@openremote/or-mwc-components/or-mwc-table";
const tableStyle = require("@material/data-table/dist/mdc.data-table.css");
@@ -208,6 +209,8 @@ export class PageUsers extends Page<AppStateKeyed> {
@state()
protected _serviceUserFilter = this.getDefaultUserFilter(true);
@state()
+ protected _passwordPolicy: string[] = []
+ @state()
protected _roles: Role[] = [];
@state()
protected _realmRoles: Role[] = [];
@@ -321,6 +324,7 @@ export class PageUsers extends Page<AppStateKeyed> {
this._roles = roleResponse.data.filter(role => !role.composite).sort(Util.sortByString(role => role.name));
this._registrationEmailAsUsername = realmResponse.data.registrationEmailAsUsername;
this._realmRoles = (realmResponse.data.realmRoles || []).sort(Util.sortByString(role => role.name));
+ this._passwordPolicy = realmResponse.data.passwordPolicy;
this._users = usersResponse.data.filter(user => !user.serviceAccount).sort(Util.sortByString(u => u.username));
this._serviceUsers = usersResponse.data.filter(user => user.serviceAccount).sort(Util.sortByString(u => u.username));
}
@@ -348,11 +352,6 @@ export class PageUsers extends Page<AppStateKeyed> {
// Ensure user ID is set
user.id = response.data.id;
- if (user.password) {
- const credentials = {value: user.password}
- manager.rest.api.UserResource.resetPassword(manager.displayRealm, user.id, credentials);
- }
-
await this._updateRoles(user, false);
await this._updateRoles(user, true);
await this._updateUserAssetLinks(user);
@@ -371,6 +370,16 @@ export class PageUsers extends Page<AppStateKeyed> {
} finally {
await this.loadData();
+
+ // After updating the user, reset the password if it has changed.
+ // This is handled asynchronously, so it will not 'wait' before the request has succeeded.
+ if (user.password) {
+ const credentials = {value: user.password} as Credential;
+ manager.rest.api.UserResource.resetPassword(manager.displayRealm, user.id, credentials).catch(() => {
+ showSnackbar(undefined, "savePasswordFailed");
+ });
+ }
+
return result;
}
}
@@ -924,11 +933,13 @@ export class PageUsers extends Page<AppStateKeyed> {
helperPersistent ?readonly="${readonly}"
.label="${i18next.t("repeatPassword")}"
.type="${InputType.PASSWORD}" min="1"
+ style="${this._passwordPolicy ? 'margin-bottom: 0' : undefined}"
@or-mwc-input-changed="${(e: OrInputChangedEvent) => {
this._onPasswordChanged(user, suffix);
this.onUserChanged(suffix);
}}"
></or-mwc-input>
+ ${when(this._passwordPolicy, () => until(this._getPasswordPolicyTemplate(user, this._passwordPolicy)))}
`}
</div>
@@ -1072,6 +1083,66 @@ export class PageUsers extends Page<AppStateKeyed> {
`;
}
+ protected async _getPasswordPolicyTemplate(user: UserModel, passwordPolicy = this._passwordPolicy): Promise<TemplateResult> {
+ const policyMap = new Map(passwordPolicy.map(policyStr => {
+ const name = policyStr.split("(")[0];
+ const value = policyStr.split("(")[1].split(")")[0];
+ return [name, value];
+ }));
+ const policies = Array.from(policyMap.keys());
+ const policyTexts: TemplateResult[] = [];
+
+ // Minimum / maximum length warning
+ if(policies.includes("length") && policies.includes("maxLength")) {
+ policyTexts.push(html`<or-translate value="password-policy-invalid-length" .options="${{ 0: policyMap.get("length"), 1: policyMap.get("maxLength") }}"></or-translate>`);
+ } else if(policies.includes("length")) {
+ policyTexts.push(html`<or-translate value="password-policy-invalid-length-too-short" .options="${{ 0: policyMap.get("length") }}"></or-translate>`);
+ } else if(policies.includes("maxLength")) {
+ policyTexts.push(html`<or-translate value="password-policy-invalid-length-too-long" .options="${{ 0: policyMap.get("maxLength") }}"></or-translate>`);
+ }
+
+ // Special characters
+ if(policies.includes("specialChars")) {
+ const value = policyMap.get("specialChars");
+ const translation = value == "1" ? "password-policy-special-chars-single" : "password-policy-special-chars";
+ policyTexts.push(html`<or-translate value="${translation}" .options="${{ 0: value }}"></or-translate>`);
+ }
+
+ // Digits/numbers
+ if(policies.includes("digits")) {
+ const value = policyMap.get("digits");
+ const translation = value == "1" ? "password-policy-digits-single" : "password-policy-digits";
+ policyTexts.push(html`<or-translate value="${translation}" .options="${{ 0: value }}"></or-translate>`);
+ }
+
+ // Uppercase / lowercase letters
+ if(policies.includes("upperCase")) {
+ const value = policyMap.get("upperCase");
+ const translation = value == "1" ? "password-policy-uppercase-single" : "password-policy-uppercase";
+ policyTexts.push(html`<or-translate value="${translation}" .options="${{ 0: value }}"></or-translate>`);
+ }
+
+ // Warn for recently used passwords
+ if(policies.includes("passwordHistory")) {
+ policyTexts.push(html`<or-translate value="password-policy-recently-used"></or-translate>`);
+ }
+
+ // Cannot be username and/or email
+ if(policies.includes("notUsername") && policies.includes("notEmail")) {
+ policyTexts.push(html`<or-translate value="password-policy-not-email-username"></or-translate>`);
+ } else if(policies.includes("notUsername")) {
+ policyTexts.push(html`<or-translate value="password-policy-not-username"></or-translate>`);
+ } else if(policies.includes("notEmail")) {
+ policyTexts.push(html`<or-translate value="password-policy-not-email"></or-translate>`);
+ }
+
+ return html`
+ <ul>
+ ${map(policyTexts, text => html`<li>${text}</li>`)}
+ </ul>
+ `;
+ }
+
// Reset selected user or creation page, and go back to the list
protected reset() {
this.userId = undefined;